php 如何在一个 mysql_query 中执行多个 SQL 语句?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6821184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:22:28  来源:igfitidea点击:

How do you do multiple SQL statements in one mysql_query?

phpmysqlsql

提问by Tom

Say I wanted to do UPDATE table SET name = 'bob'and UPDATE table SET age = 55 WHERE name = 'jim'how do I do them in the same mysql_query()?

说我想做UPDATE table SET name = 'bob'以及UPDATE table SET age = 55 WHERE name = 'jim'如何在同一个 mysql_query() 中执行它们?

EDIT:Since this question has a fair amount of views I'd like to point out that as of PHP 5.5 mysql_queryand other mysql_*functions are now deprecated and shouldn't be used.

编辑:由于这个问题有相当多的观点,我想指出,从 PHP 5.5 开始mysql_query,其他mysql_*函数现在已被弃用,不应使用。

采纳答案by Mike

I've never tried this, but I think you can use mysqli::multi_query. One of the good things about mysql_queryrejecting multiple statements is that it immediately rules out some of the more common SQL injection attacks, such as adding '; DELETE FROM ... #to a statement. You might therefore want to be careful with multiple statements.

我从未尝试过,但我认为您可以使用mysqli::multi_querymysql_query拒绝多个语句的好处之一是它立即排除了一些更常见的 SQL 注入攻击,例如添加'; DELETE FROM ... #到语句中。因此,您可能需要小心处理多个语句。

回答by Mike

As it says on the top of the manual:

正如手册顶部所说:

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.

mysql_query() 将唯一查询(不支持多个查询)发送到与指定 link_identifier 关联的服务器上当前活动的数据库。

回答by Nicola Cossu

You can do "conditional" update in this way:

您可以通过这种方式进行“有条件”更新:

create table test (
id int not null auto_increment primary key,
name varchar(50),
age tinyint
) engine = myisam;

insert into test (name) values ('jim'),('john'),('paul'),('mike');


update test
set age =
case 
when name = 'jim' then 10
when name = 'paul' then 20
else 30
end

Hope that it helps you.

希望对你有帮助。