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
How do you do multiple SQL statements in one mysql_query?
提问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_query
and 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_query
rejecting 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_query。mysql_query
拒绝多个语句的好处之一是它立即排除了一些更常见的 SQL 注入攻击,例如添加'; DELETE FROM ... #
到语句中。因此,您可能需要小心处理多个语句。
回答by Mike
回答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.
希望对你有帮助。