【发布时间】:2021-02-24 13:56:00
【问题描述】:
我试图在下面的代码中使用单行数据中的表数据作为变量的值,并且我不断收到“警告:尝试访问 C:\xampp\htdocs\ 中类型为 null 的值的数组偏移量”在第 29 行完成\test1.php"
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT lev1 FROM ref where id=1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "lev1: " . $row["lev1"]. "";
}
}
$mamo=$row["lev1"];
$conn->close();
我错了什么?
【问题讨论】:
-
“我做错了什么?” - 错误信息不只是告诉你吗?
$row不是数组,只包含 NULL。看起来你实际上并没有考虑你正在使用的代码,resp。没有费心去弄清楚它首先对谁起作用?结果集上的 while 循环结束,因为fetch_assoc将在上次迭代中处理完最后一条可用记录之后返回 NULL。因此,您现在无法通过 $row 在循环之后访问任何数据。 -
我假设第 29 行是
$mamo=$row["lev1"];。阅读fetch_assocmanual的“返回值”部分。 -
还假设
id是唯一的PK,循环完全没用......
标签: php