0

Can anyone tell me why row[0] has data, but row[1] to row[3] are undefined (empty)?

I have 4 rows in my database having bookid = '35'.

<?php
$mysqli = new mysqli('localhost', 'root', '', 'assignment3');
$query = "select image from images where BookId='35'";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_NUM);
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
?>
0

3 Answers 3

3

You need to use fetch_array every time you want to extend to the next row. Using the numeric indices (0, 1, 2 ... n) only retrieve the columns by number in the row.

Try this:

$row = $result->fetch_array(MYSQLI_NUM);
print_r($row); // row 1
$row = $result->fetch_array(MYSQLI_NUM);
print_r($row); // row 2
$row = $result->fetch_array(MYSQLI_NUM);
print_r($row); // row 3
$row = $result->fetch_array(MYSQLI_NUM);
print_r($row); // row 4

If this makes sense to you, you can even abstract this into a for loop:

for ($i = 0; $i < 4; $i++) {
    $row = $result->fetch_array(MYSQLI_NUM);
    print_r($row);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, you have solved my problem! I always mistaken that fetch_array(MYSQLI_NUM); fetch each rows from database and insert into each array in php!
0

It is much convenient to use mysqli_fetch_all(), since it returns all the rows as an array in a single step. But it may consume much memory in case of large result-set.

Eg.

<?php
$mysqli = new mysqli('localhost', 'root', '', 'assignment3');
$query = "select image from images where BookId='35'";
$result = $mysqli->query($query);
//MYSQLI_NUM for numerical array,
//This will return both associative and numerical, if not specify any parameters.
$row = $result->mysqli_fetch_all(MYSQLI_NUM);
//this will print all rows
print_r($row);

//now it is valid to call
echo $row[0];
echo $row[1];
echo $row[2];
echo $row[3];
?>

Comments

0
select image from images where BookId='35'

This only returns one column so this is why $row[0] works and $row[1]

You need this:

SELECT * FROM images WHERE BookId = '35'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.