I am trying to get the last id which I entered to my database. Here is the code I use:
$test_query = "SELECT * FROM table ORDER BY id DESC LIMIT 1";
if ( mysql_query($test_query) ) {
echo 'OK!';
$results = mysql_fetch_array($test_query);
echo $results['id'];
print_r ($results);
}
The only output I have is the 'OK!'.
What do i do wrong?
解决方案
You need to use the output of mysql_query in mysql_fetch_array.
$res = mysql_query($test_query);
if ($res === false) {
throw new Exception("query failed");
}
$row = mysql_fetch_array($res);
echo $row["id"];
Keep in mind that this reads only one row. If you want more use the while loop construction you can find here: http://php.net/mysql_fetch_array
If you just did an INSERT query use mysql_insert_id() to fetch the id. This is a feature of MySQL. This works in conjunction with the AUTO_INCREMENT option.
Also, if this is a new site you're building use mysqli_* functions instead of mysql_*. The latter is deprecated.