我正在尝试将数据库值存储在PHP变量中,但是id显示未定义的索引错误

时间:2019-07-15 10:39:30

标签: php

我正在尝试使用PHP将数据库中的id存储到一个数组中,但是它显示错误。

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webmirchi";
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id FROM jobinfo";
$result = $conn->query($sql);
$data = array();
while($row = $result->fetch_row())
{
$data[] = $row['id'];
}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
$arrlength = count($data);
for($x = 0; $x < $arrlength; $x++) {

echo $data[$x];
echo "<br>";
}
$conn->close();
?>
  

注意:未定义的索引:第19行的E:\ xampp \ htdocs \ demo1.php中的ID

1 个答案:

答案 0 :(得分:0)

您必须定位索引而不是列名“ id”。这样就可以了:

$sql = "SELECT id FROM jobinfo order by 1 asc";

if ($result = $conn->query($sql)) {
   $data = array();

   while($row = $result->fetch_row())
   {
      $data[] = $row[0];
   }

   $arrlength = count($data);
   for($x = 0; $x < $arrlength; $x++) {
      echo $data[$x];
      echo "<br>";
   }
}