PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

后端 未结 7 2292
长发绾君心
长发绾君心 2020-11-21 06:03

I do know that PDO does not support multiple queries getting executed in one statement. I\'ve been Googleing and found few posts talking about PDO_MYSQL and PDO_MYSQLND.

7条回答
  •  伪装坚强ぢ
    2020-11-21 06:33

    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

提交回复
热议问题