Reputation: 1533
How can I do one single query with both an INSERT and SELECT in it and then read the results of selection? I want to insert and then select something, all must be done in one query...
I know it accept multiple commands in single query...But I want to read results of query and I cannot read results. I'm doing this:
$results=mysql_query("
INSERT INTO table1 (field1,field2) VALUES('aaa','bbbb') ON DUPLICATE KEY UPDATE `field1` = 'cccc', `field2`='dddddd';
SELECT field3 Form Table3 WHERE field3='eeeee';
",$connection);
while ($rows = mysql_fetch_array($results, MYSQL_NUM))
echo $rows[0];
Upvotes: 0
Views: 10681
Reputation: 37065
It is possible to send multiple statements in PHP if you are using the mysqli
extension, which is a good idea to use instead of the older mysql extension for a lot of reasons. Here is a modified example from the multiple statements section of the documentation, based on your question:
$mysqli = new mysqli("example.com", "user", "password", "database");
$sql .= "INSERT INTO table1 (field1,field2) VALUES('aaa','bbbb') ON DUPLICATE KEY UPDATE `field1` = 'cccc', `field2`='dddddd';";
$sql .= "SELECT field3 Form Table3 WHERE field3='eeeee';";
$mysqli->multi_query($sql);
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
?>
Notice that the documentation does dedicate airtime to security risks of multiple statements, which everyone is pointing out. The other reason, of course, that it's not always a great idea is if you want the second statement to be affected by the first statement.
Upvotes: 2
Reputation:
all must be done in one query...
Why do you need to do everything in one query ?
Like Wiseguy said, I think what you are looking for is called a transaction.
Also, It might be a good idea considering updating to PDO, which will give you a more complete toolset like transactions and query parameters.
Anyway, for answering your initial question, no it is not possible.
Update: Here is an example of a transaction in PDO.
try
{
$pdo->beginTransaction();
$pdo->query(' ... ');
$pdo->query(' ... ');
$pdo->query(' ... ');
$pdo->commit();
}
catch(Exception $e)
{
$pdo->rollback();
die($e->getCode() . ': ' . $e->getMessage());
}
Upvotes: 5
Reputation: 791
I wouldn't recommend this either but you can use pdo to do this as shown in this thread: PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)
Upvotes: 0
Reputation: 4849
Not possible, and wouldnt recommend doing it either, as kappa points out, if you perform 2 seperate queries you'll be able to check for results etc. which is preferable.
Upvotes: 3