2

全部,

我创建了一个包含三个字段的表 - 一个自动递增的 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
4

1 回答 1

2

我进行了测试,这是我发现的:

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()是因为我猜数据正在插入您的表中。你确定你没看到里面有什么?希望这有助于澄清事情。

于 2012-07-26T23:18:10.717 回答