3

I used the query:

$sql = mysql_query("SELECT MAX(eno) FROM employee"); 

Which retrieve last record from database, but it is not working with while loop. If I used:

$sql = mysql_query("SELECT * FROM employee"); 

This query then the while loop runs properly. Why does this happen?

$sql = mysql_query("SELECT MAX(eno) FROM employee");

while ($row = mysql_fetch_assoc($sql)) {

   $asd = $row['eno'];
   echo "eno".$asd;
}
Halvor Holsten Strand
  • 19,829
  • 17
  • 83
  • 99
LOKESH
  • 1,303
  • 1
  • 16
  • 29

3 Answers3

2

You need to provide an alias something as

SELECT MAX(eno) as eno FROM employee

Also using max() will give you one row so no need to fetch through loop you may use some other function and most importantly you must start using prepared statement.

Check the below thread

Fetch only one row in PHP/MySQL

Community
  • 1
  • 1
Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63
1
$sql = mysql_query("SELECT MAX(eno) FROM employee");

fetches only one record with the value of maximum eno. for this you dont need to run any loop

$row = mysql_fetch_assoc(mysql_query($sql));

will give you the result as -

$row['MAX(eno)'];

and $sql = mysql_query("SELECT * FROM employee"); will fetch all the records on table employee

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

you have to use $row[0]

$sql = mysql_query("SELECT MAX(eno) FROM employee");

while ($row = mysql_fetch_assoc($sql)) {

    $asd = $row[0];
    echo "eno".$asd;
}
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51