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"); ?>
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);
?>
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.
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'];
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With