我有一个带有字段a1
, a2
, a3
, b1
, ...
, d1
,的 MySQL 表d2
,每个字段都BOOLEAN
在 CREATE 语句中声明为 a 。(我也试过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) VALUES(?,?,?,?,?,?, ?,?,?,?,?,?,?,?,?,?);
我还输出$data
了代码:implode(",",$data);
它给了我这个输出:
1,1,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) VALUES(1,1,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());
}
}