当有多条mysql语句连起来需要执行,比如
$sqls= “insert table a values(1,2); insert table a values(2,3);”
需要执行的话php中可以使用的方法有三个:
mysql_query
pdo
mysqli
三种方法当sqls语句没有问题的时候都是可以的。
但是
当sql语句是错误的时候会出现问题
第一条sql错误:三个方法都返回false
第一条sql正确,第二条sql错误:mysql_query、pdo、 mysqli:query也是返回true。所以这个时候你是没法判断你的sqls是否有那条语句是错误的。
解决这种办法有几个招:
1 解析sql语句
将每条sql都拆分开来执行。这样每个语句分开执行就解决了。但是这种方法多出了好几种方法,所以不可取。
2 将sqls语句保存为文本
使用cmd执行命令 mysql…. .
3 使用mysqli::multi_query方法
这个方法可以执行多条sql语句,然后使用mysqli::next_result来设置sql的偏移量,使用mysqli::error获取当前偏移的sql的错误状态
下面是第三种方法的示例代码
代码如下:
复制代码 代码如下:
$sql = Config::get('sql');
$content = file_get_contents($sql);
$config = Config::get('config')
$mysqli = mysqli_connect($config['host'], $config['user'], $config['password'], $config['dbname']);
$ret = $mysqli->multi_query($content);
if($ret === false) {
echo mysqli_error($mysqli);
}
while (mysqli_more_results($mysqli)) {
if (mysqli_next_result($mysqli) === false) {
echo mysqli_error($mysqli);
echo "\r\n";
break;
}
}
$mysqli->close();
这样的话当sqls语句中任意一条有错误的话,程序就会跳出这个错误。
如果你要编写初始化mysql的脚本的话,这招就非常好用了。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools
