Search code examples
phpmysqlmysql-insert-id

What do you put in the parentheses of mysql_insert_id()?


I tried setting a variable like this: $test_id = mysql_insert_id($dbc); because I wanted to get the id of the last row inserted. I am able to connect to the database and insert the row but the next line (setting $test_id) it says this: supplied argument is not a valid MySQL-Link resource . Any ideas?

Here's the code:

$user_id = $_SESSION['user_id'];

$q = "INSERT INTO tests (user_id, title, subject, creation_date) VALUES ('$user_id', '$title', '$subj', NOW())"; //query to insert test details into tests table
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
$test_id = mysql_insert_id($dbc);

if (mysqli_affected_rows($dbc) == 1) {//if the query ran correctly and the test details were added to the database

$q = "INSERT INTO content (test_id, field1) VALUES ($test_id, '$content')"; //query to insert test content into content table
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));

$dbc is defined like this:

$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASS, DB_NAME);


Solution

  • From the comments: Oh, I see now. You're mixing mysql_* with mysqli_* functions. Those are different libraries. They don't mix. Use mysqli_insert_id() instead.