在 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) }

除了 BDid 列是 int 之外,所有列都是 TEXT 格式。我的代码 运行 使用未准备好的语句很顺利,但我想我会更新它,使用相同的数据和相同的 table.

没有返回错误,但没有行受到影响。

GROUP 是 MySQL 中的 reserved word,因此您必须转义它才能在查询中使用它,在 PDO 查询中就像在普通查询中一样。反引号可以:

因此您必须更改为这些行:

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