I have a problem with performing sql query from php script. The query in sql looks like this:

INSERT INTO `table1` VALUES (NULL, 'Blah', 'blah', 'blah', 'blah');
INSERT INTO `table2` VALUES (NULL, @lastID, 'Other blah', 'and blah');

It works fine on phpmyadmin, but when I use it in php procedure as following:

function saveData() {
    $insert = "INSERT INTO `table1` VALUES (NULL, 'Blah', 'blah', 'blah', 'blah');
                SET @lastID = LAST_INSERT_ID();
                INSERT INTO `table2` VALUES (NULL, @lastID, 'Other blah', 'and blah')";
    mysqli_query($mysqli, $insert) or die ("<b>Insert to DB failed:</b> " . mysqli_error($mysqli));


It prints the following error:

Insert to DB failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @lastID = LAST_INSERT_ID(); INSERT INTO `table2` VALUES (NULL' at line 2

Any help would be appreciated.

  • Is the first column in query for "table1" is Primary key and auto increment field? – vijayp Sep 6 '14 at 14:29
  • @vijayp Yes, it's Primary Key and Auto_Increment – bofanda Sep 6 '14 at 14:54
  • I think you don't need to pass null for that, Can you try to pass column name in insert query with values – vijayp Sep 6 '14 at 15:08
  • Can you add column name here – vijayp Sep 6 '14 at 15:09
  • You need php.net/manual/ro/mysqli.multi-query.php for multiple queries. – Mihai Sep 6 '14 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.