php PDO支持多个查询(PDO_MYSQL、PDO_MYSQLND)

xmjla07d  于 2022-12-02  发布在  PHP
关注(0)|答案(7)|浏览(161)

我确实知道PDO不支持在一条语句中执行多个查询。我一直在谷歌上搜索,发现很少有帖子讨论PDO_MYSQL和PDO_MYSQLND。
PDO_MySQL是一个比其他传统MySQL应用程序更危险的应用程序。传统MySQL只允许一个SQL查询。PDO_MySQL没有这样的限制,但您有被注入多个查询的风险。
发件人:Protection against SQL Injection using PDO and Zend Framework (June 2010; by Julian)
似乎PDO_MYSQL和PDO_MYSQLND确实提供了对多个查询的支持,但是我无法找到关于它们的更多信息。这些项目已经停止了吗?现在是否有任何方法可以使用PDO运行多个查询?

hfwmuf9z

hfwmuf9z1#

据我所知,在PHP 5.3中,PDO_MYSQLND取代了PDO_MYSQL。令人困惑的是,名称仍然是PDO_MYSQL。所以现在ND是MySQL+PDO的默认驱动程序。
总之,要一次执行多个查询,您需要:

  • PHP 5.3以上版本
  • 迈斯金德
  • 仿真的预准备陈述式。请确定PDO::ATTR_EMULATE_PREPARES设定为1(预设值)。或者,您可以避免使用预准备陈述式,而直接使用$pdo->exec
    使用exec
$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');

// works regardless of statements emulation
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);

$sql = "
DELETE FROM car; 
INSERT INTO car(name, type) VALUES ('car1', 'coupe'); 
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";

$db->exec($sql);

使用语句

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');

// works not with the following set to 0. You can comment this line as 1 is default
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);

$sql = "
DELETE FROM car; 
INSERT INTO car(name, type) VALUES ('car1', 'coupe'); 
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";

$stmt = $db->prepare($sql);
$stmt->execute();

注意:

使用模拟预准备语句时,确保在DSN(从5.3.6开始可用)中设置了正确的编码(反映实际数据编码)。否则为there can be a slight possibility for SQL injection if some odd encoding is used

vfhzx4xs

vfhzx4xs2#

在摆弄了半天这个之后,发现PDO有一个bug在那里...

//This would run as expected:
$pdo->exec("valid-stmt1; valid-stmt2;");

--

//This would error out, as expected:
$pdo->exec("non-sense; valid-stmt1;");

--

//Here is the bug:
$pdo->exec("valid-stmt1; non-sense; valid-stmt3;");

它将执行"valid-stmt1;",在"non-sense;"停止,并且从不抛出错误。将不运行"valid-stmt3;",返回true,并谎称一切运行良好。
我希望它在"non-sense;"上出错,但它没有。
这里是我找到这个信息的地方:Invalid PDO query does not return an error
下面是错误:https://bugs.php.net/bug.php?id=61613
所以,我试着用mysqli做这个,还没有真正找到任何关于它如何工作的可靠答案,所以我想我只是把它留在这里给那些想使用它的人。

try{
    // db connection
    $mysqli = new mysqli("host", "user" , "password", "database");
    if($mysqli->connect_errno){
        throw new Exception("Connection Failed: [".$mysqli->connect_errno. "] : ".$mysqli->connect_error );
        exit();
    }

    // read file.
    // This file has multiple sql statements.
    $file_sql = file_get_contents("filename.sql");

    if($file_sql == "null" || empty($file_sql) || strlen($file_sql) <= 0){
        throw new Exception("File is empty. I wont run it..");
    }

    //run the sql file contents through the mysqli's multi_query function.
    // here is where it gets complicated...
    // if the first query has errors, here is where you get it.
    $sqlFileResult = $mysqli->multi_query($file_sql);
    // this returns false only if there are errros on first sql statement, it doesn't care about the rest of the sql statements.

    $sqlCount = 1;
    if( $sqlFileResult == false ){
        throw new Exception("File: '".$fullpath."' , Query#[".$sqlCount."], [".$mysqli->errno."]: '".$mysqli->error."' }");
    }

    // so handle the errors on the subsequent statements like this.
    // while I have more results. This will start from the second sql statement. The first statement errors are thrown above on the $mysqli->multi_query("SQL"); line
    while($mysqli->more_results()){
        $sqlCount++;
        // load the next result set into mysqli's active buffer. if this fails the $mysqli->error, $mysqli->errno will have appropriate error info.
        if($mysqli->next_result() == false){
            throw new Exception("File: '".$fullpath."' , Query#[".$sqlCount."], Error No: [".$mysqli->errno."]: '".$mysqli->error."' }");
        }
    }
}
catch(Exception $e){
    echo $e->getMessage(). " <pre>".$e->getTraceAsString()."</pre>";
}
btqmn9zl

btqmn9zl3#

快速而肮脏的方法:

function exec_sql_from_file($path, PDO $pdo) {
    if (! preg_match_all("/('(\\\\.|.)*?'|[^;])+/s", file_get_contents($path), $m))
        return;

    foreach ($m[0] as $sql) {
        if (strlen(trim($sql)))
            $pdo->exec($sql);
    }
}

在合理的SQL语句结束点拆分。没有错误检查,没有注入保护。在使用它之前了解您的使用。就个人而言,我使用它来播种原始迁移文件以进行集成测试。

smdnsysy

smdnsysy4#

Like thousands of people, I'm looking for this question:

Can run multiple queries simultaneously, and if there was one error, none would run I went to this page everywhere

But although the friends here gave good answers, these answers were not good for my problem
So I wrote a function that works well and has almost no problem with sql Injection.
It might be helpful for those who are looking for similar questions so I put them here to use

function arrayOfQuerys($arrayQuery)
{
    $mx = true;
    $conn->beginTransaction();
    try {
        foreach ($arrayQuery AS $item) {
            $stmt = $conn->prepare($item["query"]);
            $stmt->execute($item["params"]);
            $result = $stmt->rowCount();
            if($result == 0)
                $mx = false;
         }
         if($mx == true)
             $conn->commit();
         else
             $conn->rollBack();
    } catch (Exception $e) {
        $conn->rollBack();
        echo "Failed: " . $e->getMessage();
    }
    return $mx;
}

for use(example):

$arrayQuery = Array(
    Array(
        "query" => "UPDATE test SET title = ? WHERE test.id = ?",
        "params" => Array("aa1", 1)
    ),
    Array(
        "query" => "UPDATE test SET title = ? WHERE test.id = ?",
        "params" => Array("bb1", 2)
    )
);
arrayOfQuerys($arrayQuery);

and my connection:

try {
        $options = array(
            //For updates where newvalue = oldvalue PDOStatement::rowCount()   returns zero. You can use this:
            PDO::MYSQL_ATTR_FOUND_ROWS => true
        );
        $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password, $options);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo "Error connecting to SQL Server: " . $e->getMessage();
    }

Note:

This solution helps you to run multiple statement together,
If an incorrect a statement occurs, it does not execute any other statement

cyej8jka

cyej8jka5#

PDO确实支持这一点(截至2020年)。然后调用nextRowset(),如果您有多个SELECT结果,那么它将跳转到下一个SELECT结果。结果集的顺序将与查询的顺序相同。显然,请考虑安全隐患-因此不要接受用户提供的查询,使用参数等。例如,我将它用于由代码生成的查询。

$statement = $connection->query($query);
do {
  $data[] = $statement->fetchAll(PDO::FETCH_ASSOC);
} while ($statement->nextRowset());
ggazkfy8

ggazkfy86#

请尝试以下功能:多个查询和多个值插入。

function employmentStatus($Status) {
$pdo = PDO2::getInstance();

$sql_parts = array(); 
for($i=0; $i<count($Status); $i++){
    $sql_parts[] = "(:userID, :val$i)";
}

$requete = $pdo->dbh->prepare("DELETE FROM employment_status WHERE userid = :userID; INSERT INTO employment_status (userid, status) VALUES ".implode(",", $sql_parts));
$requete->bindParam(":userID", $_SESSION['userID'],PDO::PARAM_INT);
for($i=0; $i<count($Status); $i++){
    $requete->bindParam(":val$i", $Status[$i],PDO::PARAM_STR);
}
if ($requete->execute()) {
    return true;
}
return $requete->errorInfo();
}
rqqzpn5f

rqqzpn5f7#

已尝试以下代码

$db = new PDO("mysql:host={$dbhost};dbname={$dbname};charset=utf8", $dbuser, $dbpass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

然后

try {
 $db->query('SET NAMES gbk');
 $stmt = $db->prepare('SELECT * FROM 2_1_paidused WHERE NumberRenamed = ? LIMIT 1');
 $stmt->execute(array("\xbf\x27 OR 1=1 /*"));
 }
 catch (PDOException $e){
 echo "DataBase Errorz: " .$e->getMessage() .'<br>';
 }
 catch (Exception $e) {
 echo "General Errorz: ".$e->getMessage() .'<br>';
 }

而且得到了

DataBase Errorz: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/*' LIMIT 1' at line 1

如果在$db = ...之后添加$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
然后得到空白页
如果改为SELECT尝试DELETE,则在这两种情况下都会出现如下错误

DataBase Errorz: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM 2_1_paidused WHERE NumberRenamed = '¿\' OR 1=1 /*' LIMIT 1' at line 1

所以我的结论是不可能注射...

相关问题