在单查询MySQL中执行INSERT和SELECT [英] INSERT and SELECT in single query MySQL

查看:155
本文介绍了在单查询MySQL中执行INSERT和SELECT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在其中同时包含INSERT和SELECT的情况下进行单个查询,然后读取选择的结果? 我要插入然后选择某些内容,所有这些操作必须在一个查询中完成...

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];

推荐答案

如果使用多个语句部分的修改示例文档,具体取决于您的问题:

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.

这篇关于在单查询MySQL中执行INSERT和SELECT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆