gpt4 book ai didi

php - 我测试 MySQL 插入是否成功不起作用

转载 作者:行者123 更新时间:2023-11-29 02:32:02 24 4
gpt4 key购买 nike

全部,

我创建了一个包含三个字段的表 - 一个自动递增的 ID 和 2 个数据字段。数据的 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 - 无法添加或更新子行:外键约束失败('project'.'table1',CONSTRAINT 'table1_ibfk_1' FOREIGN KEY ('data1') REFERENCES 'table2' ('data2') ON DELETE更新时无操作无操作)

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com