我有一个 MySQL 表,其中包含字段 a1
、a2
、a3
、b1
、...
、d1
、d2
,每个字段都在 CREATE 语句中声明为 BOOLEAN
。 (我也试过 TINYINT(1)
但遇到了同样的问题)。
然后我有这个从 HTML 表单接收数据的 PHP 函数:
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
,结果是这样的:
INSERT INTO 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"
。
现在唯一的问题是我不明白为什么查询总是失败,因为我像这样把两个位放在一起:
INSERT INTO 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());
}
}
最佳答案
由于您实际上是将关联数组传递给 PDO,因此您可以绑定(bind)到命名参数。 ?
或位置占位符的使用需要标准的索引数组。如果您反对使用命名参数,只需将 $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"
关于php - MySQL Insert 动态失败但直接工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18730038/