Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The same request in the Adminer has no errors, but in php is

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SET @lastID = last_insert_id(); INSERT INTO p_messages(letter_id, user_id, messa' at line 1).

PHP:

$DB->query("INSERT INTO p_letters(user_1_id, user_1_name, create_date) VALUES ('".htmlspecialchars($accountId)."', '".htmlspecialchars($username)."', now()); SET @lastID = LAST_INSERT_ID(); INSERT INTO p_messages(letter_id, user_id, message) VALUES (@lastID, '".htmlspecialchars($accountId)."', '".htmlspecialchars($text)."');");

SQL:

INSERT INTO p_letters(user_1_id, user_1_name, create_date) VALUES ('acc583bfa62de6f66.05116379', '212312313', now()); SET @lastID = LAST_INSERT_ID(); INSERT INTO p_messages(letter_id, user_id, message) VALUES (@lastID, 'acc583bfa62de6f66.05116379', 'Проверка');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
621 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are supposed to run your queries with separate API calls.

$DB->query("INSERT INTO ...");
$DB->query("SET @lastID = LAST_INSERT_ID()");
$DB->query("INSERT INTO ...");

note that you don't actually need the second query here as LAST_INSERT_ID() can be used directly.

Besides, you should never use a function named "HTML speacial chars" for any database interaction. You have to use prepared statements instead.

Note that a suggestion to use multi_query is unjustified and misleading, causing a lot of problems.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...