全部,
我创建了一个包含三个字段的表 - 一个自动增量 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
最佳答案
我进行了测试,结果如下:
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`age` int(11) NOT NULL,
`email` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
从控制台:
INSERT INTO `test` () VALUES ();
// Result:
1 row(s) affected, 2 warning(s):
1364 Field 'name' doesn't have a default value
1364 Field 'email' doesn't have a default value
然后选择:
mysql> select * from test;
+----+------+-------+
| id | name | email |
+----+------+-------+
| 1 | 0 | |
+----+------+-------+
1 row in set (0.00 sec)
另一个插入测试:
mysql> INSERT INTO `test` () VALUES(NULL, NULL, NULL);
ERROR 1048 (23000): Column 'name' cannot be null
因此,如果您未绑定(bind)任何参数且未设置任何值,出于某种原因,MySQL 不会将缺失值视为 NULL
。有趣的是,即使没有设置默认值,数据仍然会被插入(因此默认值特定于列类型)。
一些 PHP 代码进一步说明了这一点:
$pdo = new PDO('mysql:host=10.1.1.37;dbname=testing', 'user', 'pw');
$query = $pdo->prepare("INSERT INTO `test` () VALUES ()");
$result = $query->execute();
var_dump("Result: ", $result);
var_dump("Affected: ", $query->rowCount());
var_dump("Warnings: ", $query->errorInfo());
/*
string(8) "Result: "
bool(true)
string(10) "Affected: "
int(1)
string(10) "Warnings: "
array(3) {
[0]=>
string(5) "00000"
[1]=>
NULL
[2]=>
NULL
}
*/
因此,您从 execute()
获得成功结果的原因是因为我猜测数据已插入到您的表中。你确定你没看到里面有什么吗?希望这有助于解决问题。
关于php - 我对 MySQL 插入是否成功的测试不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11679093/