mysqli预处理语句 - 非null变量的null错误?

时间:2013-10-08 14:09:35

标签: php mysqli prepared-statement

最后开始学习准备好的陈述。尝试运行一对简单插入时,我遇到了一个令人抓狂的错误:

$p_stmt = $mysqli->prepare("INSERT INTO ww_pages (page_key) VALUES (?)");
$p_stmt->bind_param('s', $page_key);
$p_stmt->execute();

$pv_stmt = $mysqli->prepare("INSERT INTO ww_page_versions (page_id, page_title, page_content, version_notes, version_timestamp) VALUES (?, ?, ?, ?, ?)");
$pv_stmt->bind_param('issss', $p_stmt->insert_id, $page_title, trim($_POST["page_content"]), trim($_POST["version_notes"]), date("Y-m-d H:i:s"));
$pv_stmt->execute();
echo $pv_stmt->error;

echo $pv_stmt->error;出现此错误:Column 'page_id' cannot be null

我确信您可以解释,我正在尝试为page_id分配第一个语句的insert_id。我100%确定此值为非null,并返回一个整数值。我用这个直接测试了它:

echo "NEW ID: ".$p_stmt->insert_id."::".is_int($p_stmt->insert_id);

输出? NEW ID: 13::1

我做错了什么?当列不为空时,为什么我得到“列不能为空”?我在网上找到的唯一解决方案是涉及意外的空值。

1 个答案:

答案 0 :(得分:1)

试试这个:

$p_stmt = $mysqli->prepare("INSERT INTO ww_pages (page_key) VALUES (?)");
$p_stmt->bind_param('s', $page_key);
$p_stmt->execute();
$aux = $p_stmt->insert_id; //just this aux var an replace it in the second insert
$pv_stmt = $mysqli->prepare("INSERT INTO ww_page_versions (page_id, page_title, page_content, version_notes, version_timestamp) VALUES (?, ?, ?, ?, ?)");
$pv_stmt->bind_param('issss', $aux, $page_title, trim($_POST["page_content"]), trim($_POST["version_notes"]), date("Y-m-d H:i:s"));
$pv_stmt->execute();