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


My test of whether a MySQL insertion was succesful doesn't work

全部,

我创建了一个包含三个字段的表——一个自动递增的ID和两个数据字段。这两个数据字段是外键,我错误地将它们设置为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。我使用这个变量作为控件来确保查询顺利进行。

但是,如果我检查数据库,那么查询还没有运行。如果我手动输入,我会得到一个错误,因为这两个数据字段不允许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

因此,如果您不绑定任何参数,也不设置任何值,出于某种原因,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()中获得成功结果的原因是,我猜数据正在插入您的表中。你确定你没有在里面看到任何东西吗?希望这有助于澄清问题。