MySQL 插入动态失败,但直接工作


MySQL Insert failing dynamically but working directly

我有一个MySQL表,其中包含字段a1a2a3b1...d1d2,每个字段在CREATE语句中声明为BOOLEAN。(我也尝试了TINYINT(1)但遇到了同样的问题)。

然后我有这个PHP函数,它从HTML表单接收数据:

public function add($a) {
    $sql = "INSERT INTO property_classification 
           (a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2) 
           VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
    // creating the classification_id
    // e.g. "a1a2a3" => ["a1","a2","a3"]
    $classifications = str_split($a['classifications'], 2);
    $data = array();
    // compile $data array
    foreach (self::$classification_fields as $classification) {
        // if user array contained any classification, set to true
        if (in_array($classification, $classifications)) {
            $data[$classification] = "1"; // I tried `true` too
        } else {
            $data[$classification] = "0"; // I tried `false` here
        }
    }
    // set type for binding PDO params
    foreach ($data as $key=>$value) settype($data[$key], 'int'); // tried 'bool'
    $this->db->query($sql, $data);
    $a['classification_id'] = $this->db->lastInsertId();
    $this->log($a['classification_id']); // Output: "0"
    ...

输出应该是 1+ 中的有效 ID,但插入失败,因此lastInsertId()返回 0。

我检查了$sql编译的内容,结果是这样的:

插入property_classification(a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2)值(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);

我还使用以下代码输出$dataimplode(",",$data);,它给了我这个输出:

1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

0

,0,0,0,0,0,0,0,0,

这是完美的,因为输入是"a1a2"

现在唯一的问题是我不明白为什么查询一直失败,因为我像这样将两个位放在一起:

插入property_classification (a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2) 值(1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);

然后我在MySQL查询浏览器中执行了该查询,它起作用了。

那么为什么它会通过PDO失败呢?


DBO 类

function query($sql, $data) {
    try {
        $this->query = $this->db->prepare($sql);
        if (!is_null($data) && is_array($data))
            $this->query->execute($data);
        else
            $this->query->execute();
    } catch (PDOException $e) {
        array_push($this->log, $e->getMessage());
    }
}

由于您实际上是将关联数组传递给 PDO,因此您可以绑定到命名参数。 使用?或位置占位符需要标准索引数组。 如果您反对使用命名参数,只需将$data[$classification] =替换为$data[] =

请尝试以下操作。

public function add($a) {
    $sql = "INSERT INTO property_classification 
           (a1,a2,a3,b1,b2,b3,b4,b5,b6,b7,b8,c1,c2,c3,d1,d2) 
           VALUES(:a1,:a2,:a3,:b1,:b2,:b3,:b4,:b5,:b6,:b7,:b8,:c1,:c2,:c3,:d1,:d2);";
    // creating the classification_id
    // e.g. "a1a2a3" => ["a1","a2","a3"]
    $classifications = str_split($a['classifications'], 2);
    $data = array();
    // compile $data array
    foreach (self::$classification_fields as $classification) 
        $data[$classification] = in_array($classification, $classifications) ? 1 : 0;
    $this->db->query($sql, $data);
    $a['classification_id'] = $this->db->lastInsertId();
    $this->log($a['classification_id']); // Output: "0"