简体   繁体   English

在PHP中使用PDO更新MySQL数据库

[英]Updating MySQL database using PDO in PHP

Looked around everywhere and this is driving me mad, trying to do a basic update in PHP using PDO, with variable sized arrays, here is my code: 到处环顾四周,这使我发疯,尝试使用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;
}

is in in the code, the $prep output looks like this: 在代码中, $prep输出如下所示:

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

And the $bind variable looks like this: $ 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) }

All columns are in TEXT format apart from the BDid column which is in int. 除int的BDid列外,所有列均采用TEXT格式。 Ive had the code running smoothly with un-preared statements but thought I would update it, with the same data in and the same table. Ive的代码使用未声明的语句可以平稳运行,但我想我将使用相同的数据和相同的表对其进行更新。

No errors are returned, but no rows are affected. 不返回任何错误,但不影响任何行。

GROUP is a reserved word in MySQL, so you have to escape it to use it in a query, in a PDO query just as you would in a normal query. GROUP是MySQL中的保留字 ,因此您必须对其进行转义以在查询,PDO查询中使用它,就像在普通查询中一样。 Backticks will do: 反引号将:

So you'd have to change to these lines: 因此,您必须更改为以下几行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM