1

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);

chromedude
  • 4,246
  • 16
  • 65
  • 96

4 Answers4

2

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.

chromedude
  • 4,246
  • 16
  • 65
  • 96
Micah Carrick
  • 9,967
  • 3
  • 31
  • 43
0

You should put the link identifier (the output of mysql_connect(), not mysql_query())

mysql_insert_id implicitly calls SELECT LAST_INSERT_ID() which is session-specific.

Quassnoi
  • 413,100
  • 91
  • 616
  • 614
0

Normally you can leave out that parameter; it will know that you have a database connection open. If you want to specify the connection, use the return value from mysql_connect:

$dbc = mysql_connect('localhost', 'mysql_user', 'mysql_password');

// later
echo mysql_insert_id($dbc);

Again, this is normally not necessary.

Also keep in mind that mysql_insert_id will only work after you've made an INSERT query where an index column with AUTO_INCREMENT was incremented. It will not return the latest ID that was inserted at some other time before the current session. For that you you could for example do:

SELECT MAX(id) FROM some_table;
nitro2k01
  • 7,627
  • 4
  • 25
  • 30
0

The problem is that you're using a MySQLi resource in a MySQL function (note the missing i). There are 2 different extensions there. If you're using mysqli, don't switch to mysql. So just change that function to mysqli_insert_id($dbc);

ircmaxell
  • 163,128
  • 34
  • 264
  • 314