tags:

views:

63

answers:

3

If I try to execute two MySQL queries at once by delimitting 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?

+6  A: 

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.

cmptrgeekken
A: 

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.

Jonathan Sampson
That doesn't seem any shorter or better than a plain `mysql_query('INSERT...'); mysql_query('UPDATE...');`. ;o)
deceze
@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.
Jonathan Sampson
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
@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.
Jonathan Sampson
With all due respect, I think they're not together enough for the OP's needs, and running an unknown number of queries was not asked for. Let's let this rest. :)
deceze
@deceze: You're correct, if the user is *only* going to run two queries, my solution **is** overkill. :)
Jonathan Sampson