全部,
我创建了一个包含三个字段的表 - 一个自动递增的 ID 和 2 个数据字段。这两个数据字段是外键,我错误地将它们设置为NON NULL
. 然后我运行以下 PHP 代码:
$inserted=false;
$insertQuery=$dbConnection->prepare("INSERT INTO $this->table () VALUES ()");
$inserted=$insertQuery->execute(); //Should be true if succesful, False if not.
echo $inserted;
exit;
这显示了1
- 所以 的$inserted
值为true
。我使用这个变量作为控件来确保查询正常。
但是,如果我随后检查数据库,则查询尚未运行。如果我手动输入,我会收到一个错误,因为 2 个数据字段不允许null
值。
我的问题是:鉴于插入导致错误,为什么我的代码中的值$inserted
切换到?true
PS:要在 phpMyAdmin 中手动运行查询,我会这样做:
INSERT INTO 'flashcards' () VALUES ()
我得到了这个:
#1452 - Cannot add or update a child row: a foreign key constraint fails ('project'.'table1', CONSTRAINT 'table1_ibfk_1' FOREIGN KEY ('data1') REFERENCES 'table2' ('data2') ON DELETE NO ACTION ON UPDATE NO ACTION)
PPS:如果我添加下面建议的 vardump 代码:
var_dump("Result: ", $inserted);
var_dump("Affected: ", $insertQuery->rowCount());
var_dump("Warnings: ", $insertQuery->errorInfo());
然后我得到以下信息:
string 'Result: ' (length=8)
boolean true
string 'Affected: ' (length=10)
int 1
string 'Warnings: ' (length=10)
array
0 => string '00000' (length=5)
1 => null
2 => null