简体   繁体   中英

Why does mysql_insert_id() return 0?

When I run this code

$sql_select = "INSERT INTO `database`.`table`(Columns) VALUES (Values)... ";
$mysqlid = mysql_insert_id($sql_select->db);
echo ($mysqlid);

I get the error message

mysql_insert_id(): supplied argument is not a valid MySQL-Link 

I have tried this variation;

$mysqlid = mysql_insert_id();
echo ($mysqlid);

but that returns a 0 which, according to the documentation, means an auto_increment field was not found. The only thing I can think of is that I am not calling the auto_increment column in the $sql_select, but there is an auto_increment column in there; will that affect the behavior of mysql_insert_id?

you need to actually run the query first:

$sql= "INSERT INTO `database`.`table`(Columns) VALUES (Values)...";
$result = mysql_query($sql);

and then after that:

$id = mysql_insert_id();
echo $id

Let me know if you have still problems.

That is because $sql_select->db is not a valid MySQL Link

What you are looking for is something like this:

$sql_select = "INSERT INTO `database`.`table`(Columns) VALUES (Values)... 
$result = mysql_query($sql_select);
$mysqlid = mysql_insert_id($result->db);

$result is a valid MySQL resource.

Also don't forget to have created a mysql connection

NOTE: While I used code for the original MySQL driver it's use is discouraged. Instead you want to use MySQLi or PDO_MySQL

You need to run your query:

if($result = mysql_query($sql_select)){
    $mysqlid = mysql_insert_id();
    echo $mysqlid;
}

Cheers

your connection of mysqli is an object...so try this....

$mysqli = new mysqli("localhost", "user", "password", "dbname");

after inserting try this..

echo $mysqli->insert_id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM