MySQL MAX(id) called from PHP produces strange value
Get the solution ↓↓↓Solution:
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 themysql_fetch_*
functions, passing it the result resource you got frommysql_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);
?>
Answer
Solution:
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 usemysqli_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.
Answer
Solution:
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 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'];
?>
Answer
Solution:
the 2015 way of doing this
suppose you have database ($this->db)
$maxid = $this->db->query('SELECT MAX(c_id) FROM `customers`')->fetchColumn();
Answer
Solution:
$highest_id = mysql_result(mysql_query("SELECT MAX(c_id) FROM customers"));
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: undefined array key
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.