简体   繁体   中英

Mysql multiple queries and mysql_insert_id()?

Hi Im duplicating a row with multiple queries and would like to get the mysql_insert_id() from the result. The duplicating works fine but I seem unable to get the last id from it.

Here is my code:

    $mysqli = new mysqli("localhost", "xxxx", "xxxx", "xxxx");

if ($mysqli->connect_errno) {
    echo($error_page_header);
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    echo($error_page_footer);
    exit;
}

$sql = "CREATE TEMPORARY TABLE tmp ENGINE=MEMORY SELECT * FROM test_table WHERE id=1; ";
$sql.= "UPDATE tmp SET id=NULL; ";
$sql.= "INSERT INTO test_table SELECT * FROM tmp; ";
$sql.= "DROP TABLE tmp; ";

if (!$mysqli->multi_query($sql)) {
    echo($error_page_header);
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
    echo($error_page_footer);
    exit;

} do {
    if ($res = $mysqli->store_result()) {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
        $res->free();
    }

} while ($mysqli->more_results() && $mysqli->next_result());    

echo( 'id: ' . mysql_insert_id() ); // prints 0

Don't be confused .. ext/mysql and mysqli are not compatible and can't be used with each other. Use $mysqli->insert_id (it's per-connection)

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