簡體   English   中英

在PDO prepare語句中,對於多次執行兩次的多次插入查詢。為什么?

[英]In PDO prepare statement, for multiple insert query executing twice.why?

database.php: //database class file

public function multipleInsert($table,$attrArray,$valuesArray) {
        $sql = "INSERT INTO ".$table."(";
        $array =[];
        $appendValues = "";
        $valuesInArray = "";

        foreach ($attrArray as $key => $value) {
            $sql.="".$value.", ";
        }

        $sql = substr_replace($sql,") VALUES ",strlen($sql)-2);

        foreach ($valuesArray as $valArr) {
            $valuesInArray.= "(";
            foreach ($valArr as $key => $value) {
                array_push($array, $value);
                $valuesInArray.="?,";
            }
            $appendValues.= substr_replace($valuesInArray,"),",strlen($valuesInArray)-1);
            $valuesInArray = "";
        }
        $appendValues = substr_replace($appendValues,"",strlen($appendValues)-1);
        $sql.=$appendValues;
        //die($sql);
        $result = $this->executeQueryPRE($sql,$array);
        return $result;
    }

private function executeQueryPRE($sql,$arr) {
        try{
            $executeSQL = $this->Connection->prepare($sql);
            print_r($executeSQL);die();
            $executeSQL->execute($arr);
            if($executeSQL) {
                if($this->Connection->lastInsertId())
                    return $this->Connection->lastInsertId();
                else
                    return true;
            }
            else
                return false;
        }
        catch (PDOException $e) {
          print "Error!: " . $e->getMessage() . "<br/>";
          die();
        }
    }

sample.php //使用多個插入查詢的示例文件

require_once("database.php");
$Database = new Database;
    $arr = ["ct_name","ct_num","ct_status"];
    $arr1 = [["x","1234567890",1],["y","1234567890",1],["z","1234567890",1],["a","1234567890",1]];
    $Database->multipleInsert("contact",$arr,$arr1);

我正在嘗試使用PDO prepare語句開發一個動態的多重插入查詢。 當我嘗試執行它時,值兩次插入到表中。 我執行了print_r($ executeSQL)和die()選項,然后執行該操作,向我顯示了正確的多次插入查詢,如下所示。

PDOStatement對象([queryString] => INSERT INTO contact(ct_name,ct_num,ct_status)VALUES(?,?,?),(?,?,?),(?,?,?),(?,?,?) )

為什么要插入兩次,這是什么原因?如何克服這個問題?

不是您實際問題的答案,而是您想要解決的實際問題:

我認為這串concat東西不值得任何麻煩。
php腳本執行需要更長的時間,污染MySQL查詢緩存,容易出錯。
因此,除非您能指出一個非常非常具體的問題,否則我認為它在所有方面都失去了作用:只需准備一條語句並多次執行即可。

<?php
/*
table must be a valid table identifier
columns must be an array of valid field identifiers
recordData is an array of records, each itself an array of corresponding values for the fields in $columns
  recordData is the only parameter for which proper encoding is taken care of by this function
*/
function foo($table, $columns, $recordData) {
    $query = sprintf('
        INSERT INTO %s (%s) VALUES (%s)
    ',
        $table,
        join(',', $columns) /* put in the field ids like a,b,c,d */,
        join(',', array_pad(array(), count($columns), '?')) /* put in a corresponding number of ? placeholders like ?,?,?,? */
    );
    // resulting query string looks like INSERT INTO tablename (a,b,c,d) VALUES (?,?,?,?)
    // let the MySQL server prepare that query
    $stmt = $yourPDOInstance->prepare($query);
    // it might fail -> check if your error handling is in place here....

    // now just iterate through the data array and use each record as the data source for the prepapred statement
    // this will (more or less) only transmit the statement identifier (which the MySQL server returned as the result of pdo::prepare)
    // and the actual payload data
    // .... as long as $yourPDOInstance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); has been set somewhere prior to the prepare....
    foreach( $recordData as $record ) {
        $stmt->execute( $record );
        // might fail, so again: check your error handling ....
    }
}

$cols = ["ct_name","ct_num","ct_status"];
$data = [
    ["x","1234567890",1],
    ["y","1234567890",1],
    ["z","1234567890",1],
    ["a","1234567890",1],
];

foo("contact", $cols, $data);

(腳本僅通過php -l測試;沒有保修)

另請參閱: http : //docs.php.net/pdo.prepared-statements

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM