簡體   English   中英

在PHP中使用PDO更新MySQL數據庫

[英]Updating MySQL database using PDO in PHP

到處環顧四周,這使我發瘋,嘗試使用PDO在PHP中使用具有可變大小數組的基本更新,這是我的代碼:

function Database_Update($table,$set,$where) {
    $con = DB_PDO_Connect();

    //Create bind array that picks up values as they have places made for them
    $bind = array();

    //Write SET part of statement, with ? as variable places
    $prep = "UPDATE $table SET ";
    foreach ($set as $key => $value){
        $prep .= $key."=?, ";
        $bind[] = $value;
    }
    $prep = rtrim($prep, " ,") . " ";

    //Write WHERE part of statment, with ? as variable places
    $prep .= "WHERE ";
    foreach ($where as $key => $value){
        $prep .= $key . "=?, ";
        $bind[] = $value;
    }
    $prep = rtrim($prep, " ,");

    var_dump($prep);
    echo('<br>');
    var_dump($bind);
    echo('<br>');
    var_dump($table);

    try {
        $stmt = $con->prepare($prep);
        $stmt->execute($bind);
        echo $affected_rows = $stmt->rowCount();
        //$a_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $e->getMessage(), E_USER_ERROR);
    }

    $con = null;
}

在代碼中, $prep輸出如下所示:

string(138) "UPDATE Test SET Group=?, PartName=?, PartNum=?, NumInstock=?, Shelf=?, NumUsed=?, Distributor=?, DistributorPartNum=?, Cost=? WHERE DBid=?"

$ bind變量如下所示:

array(10) { [0]=> string(0) "" [1]=> string(24) "Bearing C Spherical" [2]=> string(5) "Hello" [3]=> string(1) "5" [4]=> string(27) "Black Bearing Box 2 shelf 3" [5]=> string(1) "0" [6]=> string(3) "FKS" [7]=> string(6) "GE 8 C" [8]=> string(0) "" [9]=> int(6) }

除int的BDid列外,所有列均采用TEXT格式。 Ive的代碼使用未聲明的語句可以平穩運行,但我想我將使用相同的數據和相同的表對其進行更新。

不返回任何錯誤,但不影響任何行。

GROUP是MySQL中的保留字 ,因此您必須對其進行轉義以在查詢,PDO查詢中使用它,就像在普通查詢中一樣。 反引號將:

因此,您必須更改為以下幾行:

$prep .= "`$key`=?, ";
...
$prep .= "`$key`=?, ";

暫無
暫無

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

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