Probably a stupid question but why does the following loop works ? There is nothing wrong with it I just want to understand how does this code know how many entries I have in database.

$result = mysql_query("SELECT * FROM post_categories");

while ($row = mysql_fetch_array($result)){

echo $row['Name'];

}

And why doesnt this echo all the entries. It echoes the first statement in my database 'Name' row.

$result = mysql_query("SELECT * FROM post_categories");

$row = mysql_fetch_array($result)

echo $row['Name'];

Regards,

Martin

You can see other entries by using mysql_data_seek(): http://www.php.net/manual/en/function.mysql-data-seek.php
When using while() with mysql_fetch_array() there will be a move of the internal row pointer for the query result, so it moves from one key to another, automatically:

<?php
$result = mysql_query("SELECT * FROM post_categories");
$row = mysql_fetch_array($result);
echo $row['Name'];
print_r($row);

mysql_data_seek($result, 1);
$row = mysql_fetch_array($result);
print_r($row);

mysql_data_seek($result, 2);
$row = mysql_fetch_array($result);
print_r($row);
?>

bye :)

note: using mysql_fetch_array() you will end up with an array with both numerical and field name keys, if you use mysql_fetch_assoc() you will get just the table field names.

commented: Thanks for good answer +1

I think this

$result = mysql_query("SELECT * FROM post_categories");

while ($row = mysql_fetch_array($result)){

echo $row['Name'];

}

Will not stop outputting, while $row = mysql_fetch_array($result)) if still equal to be true.

And this one will only output one

$result = mysql_query("SELECT * FROM post_categories");

$row = mysql_fetch_array($result)

echo $row; //because of this

However, this will output all of them also

$result = mysql_query("SELECT * FROM post_categories");

print_r(mysql_fetch_array($result));

@veedeoo print_r(mysql_fetch_array($result)); won't print all the result, but only the first available row, because mysql_fetch_array():

Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

So if you don't want to use a while loop, but you still want to print the first and, for example, the fifth row, you can move the pointer using mysql_data_seek:

mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number. The next call to a MySQL fetch function, such as mysql_fetch_assoc(), would return that row.

bye :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.