简体   繁体   中英

how to solve php error Undefined variable: id?

it is my code . it shows perfect output but one php error shown that is it is my code . it shows perfect output but one php error shown that is

<tbody>
   <?php
      while ($row = mysqli_fetch_array($result)) {
          $sum+= $row["Price"];
          $id .= $row["id"] . ",";
          echo "<tr><td>" . "#" . $row["id"] . "</td><td>" . $row["Name"] . "</td><td>Rs " . $row["Price"] . "</td><td><a href='cart-remove.php?id={$row['id']}' class='remove_item_link'> Remove</a></td></tr>";
      }
      $id = rtrim($id, ", ");
      echo "<tr><td></td><td>Total</td><td>Rs " . $sum . "</td><td><a href='success.php?itemsid=" . $id . "' class='btn btn-primary'>Confirm Order</a></td></tr>";
      ?>
</tbody>

Undefined variable: id.

You try to concatenate the $id variable but you haven't set it anywhere so it is undefined. You simple have to define it before your while loop like:

<tbody>
<?
$id = "";
while ($row = mysqli_fetch_array($result)) {
    $sum+= $row["Price"];
    $id .= $row["id"] . ",";
    echo "<tr><td>" . "#" . $row["id"] . "</td><td>" . $row["Name"] . "</td><td>Rs " . $row["Price"] . "</td><td><a href='cart-remove.php?id={$row['id']}' class='remove_item_link'> Remove</a></td></tr>";
}
$id = rtrim($id, ", ");
echo "<tr><td></td><td>Total</td><td>Rs " . $sum . "</td><td><a href='success.php?itemsid=" . $id . "' class='btn btn-primary'>Confirm Order</a></td></tr>";
?>
</tbody>

This will solve your issue but check @devpro answer. He is using a way more elegant solution and a better approach.

You can also achieve your desired result as:

Example:

$idArray = array(); // initialize array
while () { // your while loop
$idArray[] = $row["id"]; // save id into an array
}
$id = implode(',', $idArray); // now you can use this variable as you need.

Here, i am saving $id into an array. then you just need to use implode() method.

By using this, you do not need to use trim() method to remove last comma (,)

Side Note: This is just an example to use array and implode() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM