-1

I am trying to fetch all the rows from table 'student'. But it returns only first row in an array. How can I fetch all the rows in an array?

my code is-

<?php
  // con ref
  $dbCon = mysql_connect("localhost","root","") or die("connection problem".mysql_error());
  // db con
  mysql_select_db("mysql_db",$dbCon);
  $sql = "select * from student ";
  $data = mysql_query($sql);
  $row = mysql_fetch_array($data);
  print_r($row);
?>
Brian Webster
  • 30,033
  • 48
  • 152
  • 225
Anjani Gupta
  • 7
  • 1
  • 8
  • google is your friend. "fetch all the rows in an array" = many results: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&ie=UTF-8#hl=en&safe=active&sclient=psy-ab&q=fetch%20all%20the%20rows%20in%20an%20array&oq=&gs_l=&pbx=1&fp=d76eed8efe782f95&ion=1&bav=on.2,or.r_cp.r_qf.&bvm=bv.44158598,d.aWM&biw=1680&bih=903 – Robert Mar 24 '13 at 17:41
  • [Please, don't use mysql_* functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) in new code. They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the red box? Learn about prepared statements instead, and use [pdo](https://wiki.php.net/rfc/mysql_deprecation) or [mysqli](http://stackoverflow.com/questions/tagged/mysqli). – zessx Mar 24 '13 at 17:41

4 Answers4

2

As per the docs on mysql_fetch_array():

Fetch a result row as an associative array, a numeric array, or both

Note a result.

You will want to loop through all rows, something like:

while($row = mysql_fetch_array($data)) {
   // Use $row here..
}

Also, you should note that the use of mysql_* functions is deprecated. See the big red box here. Consider using PDO or MySQLi instead.

juco
  • 6,331
  • 3
  • 25
  • 42
1

You need to loop through the results.

while( $row = mysql_fetch_array($data) ) {
    print_r($row);
}
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
0
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example"; 

$result = mysql_query($query) or die(mysql_error());


while($row = mysql_fetch_array($result)){
echo $row['name']. " - ". $row['age'];
echo "<br />";
}
?>

An example how to iterate over a result.

http://www.tizag.com/mysqlTutorial/mysqlfetcharray.php

0

Number one stop using msql_ it is deprecated. Number two read the man- http://php.net/manual/en/function.mysql-fetch-array.php

It clearly states that the function mysql_fetch_array returns a row

Ed Heal
  • 59,252
  • 17
  • 87
  • 127