-1

Hi I have created a while loop but cannot understand why it loops forever. Could somebody please explain why?

while ($i<3){
  if ($i=1){
    $x='psu';
  }else if ($i=2){
    $x='cases';
  }
  $sqlcpu = "SELECT * FROM $x WHERE name LIKE '%{$term}%'";
$query = mysqli_query($db, $sqlcpu);

while ($row = mysqli_fetch_array($query)){
?><br /> Name: <a  href="productpage<?php $x ?>.php?idcpu=<?php echo $row['id$x'] ?>"><?php echo $row['name'];?></a>
<?php
echo ' Price: &pound;'.$row['price'];
}
  $i++;
}

There are other problems with this code but they are not my main concern right now as this loop seems like it should be simple. The variables $x and $i never change after $i=1

JackGroves
  • 50
  • 6

1 Answers1

1

if ($i=1) You're assinging 1 to $i here, instead of comparing 1 and $i, use

if ($i==1)

instead.

Instead of the for/if-elseif construct you could also use

foreach( array('psu', 'cases') as $table ) {
    $sqlcpu = "SELECT * FROM $table WHERE name LIKE '%{$term}%'";
VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • Just to add. `$i` is always 1 since it's being reassigned to 1 (instead of being checked for equality) every loop iteration. – Carcigenicate Mar 06 '16 at 00:23
  • And then there are the possible [sql injections](http://php.net/manual/en/security.database.sql-injection.php), missing [error handling](http://docs.php.net/manual/en/mysqli.errno.php) and missing [output encoding](http://docs.php.net/htmlspecialchars) – VolkerK Mar 06 '16 at 00:26
  • Thanks it's been a while since I've used php and I should have noticed that. Unfortunately there is a dulled down snippet of my page meaning I can't use an array but thank you for your advice – JackGroves Mar 06 '16 at 12:52