Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL MAX(id) called from PHP produces strange value

Tags:

php

mysql

I am just trying to get the auto incremented value of a table that is currently the highest. I do not need to know what the next auto increment is, just the highest value of what is in the table right now. I am using the code below, but regardless of what the actual auto increment is, what table I last inserted into, what table was last updated / modified, or any other factors that I can see, the value always returns Resource id #4. This is perplexing to me for two reasons. First I don't understand why the number is always 4, second I do not understand why I am getting back a string value (with letters and a symbol) instead of just an integer. What is the deal here?

<?php $highest_id = mysql_query("SELECT MAX(c_id) FROM customers"); ?>

like image 500
ubiquibacon Avatar asked Jun 29 '10 04:06

ubiquibacon


3 Answers

mysql_query doesn't return the value from the query, it returns a result resource. To get the actual value, you need to use one of the mysql_fetch_* functions, passing it the result resource you got from mysql_query.

<?php
    $result = mysql_query("SELECT MAX(c_id) FROM customers");
    $row = mysql_fetch_row($result);
    $highest_id = $row[0];
?>

or the shorter...

<?php
    $highest_id = mysql_result(mysql_query("SELECT MAX(c_id) FROM customers"), 0);
?>
like image 83
Amber Avatar answered Nov 19 '22 15:11

Amber


This is my answer:

require_once 'db_cconnection.php';
$query = "SELECT MAX(stud_id) FROM student_tbl";
$result = mysqli_query($connection,  $query);
$row = mysqli_fetch_row($result);
echo $row[0];

When you use mysqli_fetch_row it will fetch only one row, as we only want one row. $row will be an array. So we need to get its value through array index.

like image 43
Amit Mhaske Avatar answered Nov 19 '22 17:11

Amit Mhaske


mysql_query returns a result handle, not the actual result. In other words, your query's result is saved as resource id #4 (and that's not guaranteed to be the same always, it's coincidence if you see it that way all the time).

To access the result you need to use something like mysql_fetch_array or one of the other functions in the same family.

Something like this:

<?php 

$query = mysql_query("SELECT MAX(c_id) as max FROM customers"); 
$row = mysql_fetch_array($query);
$highest_id = $row['max'];

?>
like image 3
Mark Elliot Avatar answered Nov 19 '22 15:11

Mark Elliot