Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

php - INSERT and SELECT in single query MySQL

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];
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...