help understanding query

+2 jamie y · July 11, 2015
I have a database set up that I am working with that has just a few records. I am getting the records just fine but I don't understand why a few things don't work. Here is my code

$number = (int) $_GET['n'];
$query = "SELECT * FROM `questions`
             WHERE question_number = $number";
//Get choices
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$question = $result->fetch_assoc();

issue 1:
If I do a var dump on $question, I get NULL output to the screen. If I do

echo $question['text']

then it works. I see the question.

issue 2:

why can't I use a foreach loop on the question variable? I am guessing foreach loops don't work well on associative arrays?

my working loop

the results here

My questions
1. Why would question be null in a var_dump or a print_r?
2. Can you explain why the foreach loop fails but a while loop works?

Post a Reply


Oldest  Newest  Rating
0 Sheldon Juncker · July 20, 2015
1. MySQLi fetching is done lazily meaning that the row is not loaded from the database until you access it. Thus when you dump out the array it doesn't contain anything because you haven't accessed any of elements. This isn't really a bug, if I understand it correctly.

2. A foreach loop such as foreach(fetch() as $row) only evaluates fetch() once whereas the while loop while($row = fetch()) evaluates the fetch() multiple times. That's why you need to use a while loop and not a foreach loop. 

Note that I can't actually see your loop code because it isn't displaying correctly. I think that this is a TNB issue though.

Let me know if that helps!
0 Ebube okulu · July 12, 2015
pls can someone help me out am new to php qery
  • 1



Server-side, HTML embedded scripting language used to create dynamic Web pages.