Search code examples
phpmysqlmysql-insert-id

mysql_insert_id() always returning 0


I have this code that I need to populate through a form a new line in two tables with a foreign key constrain. This doe refer to the first insert only, and I need identify the last_id generated to use it for the related table. But $last_id returns Always zero notwistanding the new record is create.

   //Connect to Database 
 $con=mysqli_connect($db_host,$db_username,$db_pass,$db_name); 
 if (mysqli_connect_errno())
   {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }
// Database connesso

// Devo inserire il record in Documents prima perché é quello che genera la Primary Key

 $sql=" INSERT INTO Documents (doc_name, doc_type, doc_manager, doc_pointer) VALUES ('$upload_name','Privacy','Agente di riferimento','$pic')";
 $last_id = mysql_insert_id();
 Echo "Last Protocol Number =".$last_id."<br>";

Absolutely similar code works perfectly in another script thus should not be an php version issue:

//Writes the information to the database mysql_query("INSERT INTO documents (doc_name,doc_type,doc_manager,doc_pointer) VALUES ('$name', '$type', '$manager', '$pic')") ; $id = mysql_insert_id(); Echo "Last Protocol Number =".$id."
";

Not able to understand where the issue is.


Solution

  • You forgot to run your query and you've mixed mysql_ and mysqli_ APIs

    $sql=" INSERT INTO Documents (doc_name, doc_type, doc_manager, doc_pointer) VALUES ('$upload_name','Privacy','Agente di riferimento','$pic')";
    mysqli_query($con, $sql);
    $last_id = mysqli_insert_id($con);
    

    FYI, this example has no error handling. You should add it.