July 24, 2013
mysql_fetch_assoc() returning single row even though there are many rows
Nanu146’s Question:
i am trying to run this program but unexpectedly the mysql_fetch_assoc() function is returning only the first entry even though there are many entries and further more in foreach loop error say that illegal ‘parameter’ username is given
<?php
$dbc=mysql_connect("localhost","root","nanu");
mysql_select_db('users');
$getQuery='SELECT * FROM userst ORDER BY username';
$result=mysql_query($getQuery,$dbc);
$rel=mysql_fetch_assoc($result);
echo'<pre>'.print_r($rel).'<pre/>';
echo"<br/>".$rel['username']."<br/>";
foreach($rel as $Query[]){
echo $Query['username'];
}
?>
$rel=mysql_fetch_assoc($result);
will only fetch one row at a time depending on the resource pointer.
This pointer will increase once you use that statement, so using it with a loop statement will give you all the rows.
while ($rel = mysql_fetch_assoc($result)) {
echo $rel['username'];
}
Please try more safer API’s like mysqli
or PDO
instead of mysql_*
API. They are deprecated.
http://php.net/manual/en/mysqlinfo.api.choosing.php
It is not recommended to use the old mysql extension for new development, as it has been deprecated as of PHP 5.5.0 and will be removed in the future.