php 页面多mysql查询_使用PHP执行多个MYSQL查询

bd96500e110b49cbb3cd949968f18be7.png

I am trying to use PHP to run consecutive MYSQL statements as shown in the code snippet below (which just copies one row to another and renames the id via a tmp table).

I am getting a repeated syntax error message. I've tried numerous iterations. And the code looks like code I've researched in the PHP Manual and other myql questions on SO (which do not include the php dimension).

Can anyone shine a light on why my php syntax is incorrect?

include("databaseconnect.php");// This obviously works. Used a zillion time

$sql ="CREATE TEMPORARY TABLE tmp SELECT * FROM event_categoriesBU WHERE id

= 1;";

$sql.="UPDATE tmp SET id=100 WHERE id = 1;";

$sql.="INSERT INTO event_categoriesBU SELECT * FROM tmp WHERE id = 100;";

if ($conn->query($sql) === TRUE)

{

echo "Table row copied successfully. Do something with it";

}

else

{

echo "Error creating table: " . $conn->error;

//close connection etc

}

PHP Message back-

Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE tmp SET id=100 WHERE id = 1INSERT INTO event_categoriesBU SELECT * FROM t' at line 1

解决方案

Don't run a bunch of queries at once. Usually the success of one depends on all the other operations having been performed correctly, so you can't just bulldozer along as if nothing's gone wrong when there's a problem.

You can do it like this:

$queries = [

"CREATE TEMPORARY TABLE tmp SELECT * FROM event_categoriesBU WHERE id = 1",

"UPDATE tmp SET id=100 WHERE id = 1",

"INSERT INTO event_categoriesBU SELECT * FROM tmp WHERE id = 100"

];

foreach ($query as $query) {

$stmt = $conn->prepare($query);

$stmt->execute();

}

Don't forget to enable exceptions so that any query failures will stop your process instead of the thing running out of control.

The reason you don't use multi_query is because that function does not support placeholder values. Should you need to introduce user data of some kind in this query you need to use bind_param in order to do it safely. Without placeholder values you're exposed to SQL injection bugs, and a single one of those is enough to make your entire application vulnerable.

It's worth noting that PDO is a lot more flexible and adaptable than mysqli so if you're not too heavily invested in mysqli, it's worth considering a switch.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值