0

If I try to execute two MySQL queries at once by delimiting them with a semicolon, it works fine in PHP MyAdmin, but the query doesn't work at all in PHP mysql_query().

Does anyone know why?

3 Answers 3

6

mysql_query only allows you to make one query at a time. This helps prevent SQL injection.

From the docs:

mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.

If what you're trying to do is make sure that the two queries run in one transaction, check out this article on transaction control with PHP and MySQL.

Sign up to request clarification or add additional context in comments.

Comments

0

This might explain/help: http://joseph.randomnetworks.com/archives/2005/10/11/guide-to-php-security/

Comments

0

For security reasons, you can only run one query at a time. You could cycle through an array of queries though, and run each independently.

$queries[] = "INSERT INTO users (name) VALUES ('jonathan')";
$queries[] = "UPDATE users SET name = 'Jonathan' WHERE name = 'jonathan'";

foreach ($queries as $query) {
  mysql_query($query);
}

You could even explode a single string containing two queries into an array:

$sql = "INSERT INTO users (name) values ('jonathan');
        INSERT INTO users (name) values ('sampson')";

$queries = explode(";", $sql);

Where $queries would become an array of queries which we could then cycle through.

6 Comments

That doesn't seem any shorter or better than a plain mysql_query('INSERT...'); mysql_query('UPDATE...');. ;o)
@deceze Don't focus on the specific examples. The OP didn't ask about shorter or better queries. They asked about running them together. Consider also the array could be dynamically built, unlike hard-coded mysql_query() calls.
Well, you're still not running them together, but your source code became longer. You'll have to write and run the queries somewhere in your source anyway, and you might as well do it as plainly and concise as possible. Dynamically running queries from somewhere else is quite a nono in most cases, IMHO.
@deceze: I don't think you understand the larger application of my example, with all do respect. You may not know how many INSERTS or UPDATES you'll want to do ahead of time. And I understand that these aren't ran together, but they're together-enough for the OP's needs.
@deceze: You're correct, if the user is only going to run two queries, my solution is overkill. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.