简体   繁体   English

如何解决PHP错误未定义的变量:ID?

[英]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 . 它显示了完美的输出,但显示了一个php错误,这是我的代码。 it shows perfect output but one php error shown that is 它显示了完美的输出,但是显示了一个php错误,它是

<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. 未定义的变量:ID。

You try to concatenate the $id variable but you haven't set it anywhere so it is undefined. 您尝试连接$id变量,但尚未在任何位置进行设置,因此未定义。 You simple have to define it before your while loop like: 您只需在while循环之前定义它,例如:

<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. 这将解决您的问题,但请检查@devpro答案。 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. 在这里,我将$id保存到数组中。 then you just need to use implode() method. 那么您只需要使用implode()方法即可。

By using this, you do not need to use trim() method to remove last comma (,) 通过使用此方法,您无需使用trim()方法删除最后一个逗号(,)

Side Note: This is just an example to use array and implode() . 注意:这只是使用arrayimplode()的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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