0

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

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you I skipped the whole temporary table thing and followed the example on the link you send. works great now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.