0
$SQL = "INSERT INTO primarySkills (primaryName) VALUES $surveySQL";
$result = mysql_query($SQL) or die ('Cannot execute query...'.$SQL);
$surveyID = mysql_insert_id($result);

The above code will enter the table data correctly (primaryID, primaryName) but not return the id generated using mysql_insert_id(). Please let me know why the id is not returned?

What is really odd is that I use this function twice before in the same script for different tables and it works there. I double checked that primaryID is auto_increment and a primary key.

Blessings!

  • 3
    Are you sure that insert statement actually works? Looks problematic to me. – John Conde Aug 07 '16 at 03:34
  • 1
    Please [stop using mysql_functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) as they were removed from PHP – Machavity Aug 07 '16 at 03:39
  • 2
    Possible duplicate of [mysql\_insert\_id() returns 0](http://stackoverflow.com/questions/8243503/mysql-insert-id-returns-0) – Machavity Aug 07 '16 at 04:07
  • This is very unusual and I have reviewed the other mysql_insert_id() and this problem is unique. – Tiffany Fischer Aug 08 '16 at 15:24

2 Answers2

2

Stop using mysql functions
However the problem in your case could be primaryID is not a autoincrement and probably also not a primary key. For mysql_insert_id() to work, there should be a autoincrement column. Also change the query.

$SQL = "INSERT INTO primarySkills (primaryName) VALUES ($surveySQL)";

and try using mysql_insert_id() instead of mysql_insert_id($result).

coder
  • 906
  • 1
  • 12
  • 19
1

Here is an example using pdo since MYSQL functions have been removed as of php 7. I did not test your sql command. replace these values:

localhost: your host
3306: your port if different
dbname: the name of your database
root: your username
'': the last parameter is your password.

<?php
$conn = new PDO('mysql:host=localhost:3306;dbname=testdb', 'root', '');
$conn->SetAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );   
$SQL = "INSERT INTO primarySkills (primaryName) VALUES (:test)";
$insert = $conn->prepare($sql);
$insert->bindValue(":test", $surveySQL, PDO::PARAM_STR);
$insert->execute();
$last_insert_id = $conn->lastInsertId();
?>

When you have completed testing and are ready to go into production, go ahead and remove this line of code:

$conn->SetAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );   

Hope this helps.

Teddy Codes
  • 489
  • 4
  • 14