Reputation: 77
I am performing some queries. Problem is that looping over array throws
Undefined offset: 1
This is code that I used:
$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>";
}
Upvotes: 0
Views: 267
Reputation: 22656
You have an array of rows in $results
however when looping you loop from 0 to the number of columns:
$i <= sizeof($results[0])
If the number of columns is greater than the number of results you will get an undefined offset. Try this:
for ($i = 0; $i <= sizeof($results) - 1; $i++) {
$id=$results[$i]['id'];
$name=$results[$i]['name'];
$books=$books."<option value='".$id."'>".$naziv."</option>";
}
or, more succinctly:
foreach($results as $result) {
$id=$result['id'];
$name=$result['name'];
$books=$books."<option value='".$id."'>".$naziv."</option>";
}
Upvotes: 1