0

I have a PHP script that executes a MySQL SELECT query, and I would like to echo each row from that query to the page. I have tried multiple methods to go about doing this, but none seems to work. The most reasonable of these ways that I have come up with is provided below, but it doesn't work either.

$result = $conn->query("SELECT count FROM countTable;") or trigger_error($conn->error);
$row = $result->fetch_array(MYSQL_BOTH);
$count = sizeof($row);
for($i = 0; $i <= $count; $i++)
{
    echo $row[$i];
}

The code provided above only prints the first row resulting form the query. How can I modify this code so that it prints the entirething?

2
  • @RobertRozas Code has been edited to include the SQL query. Commented Dec 28, 2013 at 2:25
  • fetch_array() only get 1 row - Fetch a result row as an associative, a numeric array, or both Commented Dec 28, 2013 at 2:27

1 Answer 1

1

The array returned from fetch_array is the set of columns from one row of results. Your query has only one column (ie: "count"), so the size of the array will always be 1. Calling fetch_array multiple times will return each row one at a time.

What you want is something like:

while ($row = $result->fetch_array(MYSQL_BOTH)) {
   echo $row[0];
}

*Note, I haven't run this, so there might be some small syntax error I've overlooked.

Sign up to request clarification or add additional context in comments.

5 Comments

When I first tried your code, it only printed the second row. Just out of curiosity, I added a third row to the table, and now it prints out the second and third rows. It continues to omit the first. I'm working on a potential solution.
Do you have a $row = $result->fetch_array(MYSQL_BOTH) line above the while loop? If so, it's fetching the first row in advance of the while loop.
Yes, that's what the problem was. I'm a PHP noob, so I make noob mistakes. I can't vote your answer up, but if I could I would. I'm afraid the green check-mark is the best I can give you.
No worries. I was on here to ask a golang noob question myself and thought I'd poke around and see if there was anything I could answer while at it. Cheers.
I ♥ StackOverflow, but the problem is that the questions that are open to be answered are way to hard for me to even begin to comprehend, and the ones that I do understand are already answered.

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.