PHP code question. I don't understand why this works

In the code below I connect to my DB and then SELECT * FROM the users table. I don’t understand why the WHILE loop works. $row contains nothing. So, it doesn’t ‘equal mysql_fetch_object($results)’. Yet, it is passed and the ‘$row->username’ are echoed. I’m a newb. If you reply, first “Thanks you” second "please speak to me as if i were a child’, lol.

[php]

$conn = mysql_connect(‘localhost’,‘root’,‘root’) or die(‘Could no connect’);

mysql_select_db(‘practice’);

$sql = mysql_query(‘SELECT * FROM users’);

while ($row = mysql_fetch_object($sql)) {
echo $row->username . “
”;
}

[/php]

I know why now! It’s a single ‘=’ so $row is just being assigned to the fetched object. If it were a double or triple ‘=’. Things would be different!

Before you get too excited it should be noted you’re using obsolete mysql, you should be using mysqli or PDO. I suggest going over to php.net to see how to implement either one of them (I suggest PDO). Though to be honest you would be basically be doing the same thing with the while statement. :wink:

No worries. I’m doing a little tutorial on anti patterns :slight_smile:

I’m not sure how anti-patterns applies to this, but,

The while expression is basically saying, “while you still have rows, continue assigning them to $row.”

Sponsor our Newsletter | Privacy Policy | Terms of Service