我正在执行一些查询。问题是循环数组抛出
未定义的偏移量:1
这是我使用的代码:
$id=1;
$books="";
$prep_stmt= "SELECT * FROM books WHERE id=?";
$stmt = $mysqli->prepare($prep_stmt);
$stmt->bind_param('i', $id);
$stmt->execute();
if (!$stmt) {
die('There was an error running the query [' . $mysqli->error . ']');
exit();
}
$meta = $stmt->result_metadata();
while ($field1 = $meta->fetch_field()) {
$parameters[] = & $row[$field1->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch()) {
foreach ($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
if ($stmt->num_rows>0){
for ($i = 0; $i <= sizeof($results[0]) - 1; $i++) {
$id=$results[$i]['id'];
$name=$results[$i]['name'];
$books=$books."<option value='".$id."'>".$naziv."</option>";
}
答案 0 :(得分:1)
$results
中有一系列行,但是当你循环从0循环到列时:
$i <= sizeof($results[0])
如果列数大于结果数,您将获得未定义的偏移量。试试这个:
for ($i = 0; $i <= sizeof($results) - 1; $i++) {
$id=$results[$i]['id'];
$name=$results[$i]['name'];
$books=$books."<option value='".$id."'>".$naziv."</option>";
}
或者,更简洁:
foreach($results as $result) {
$id=$result['id'];
$name=$result['name'];
$books=$books."<option value='".$id."'>".$naziv."</option>";
}