我尝试将一些数据插入数据库。 首先,我确保我有数据。 我找不到原因,为什么没有插入数据。
echo 'os_id = ', $os_id, ' os_shoph = ', $os_shoph, ' os_shopd = ', $os_shopd;
$insert = $db->prepare("INSERT `f2go`.`prints` ("
. "prt_os_id, prt_ts, prt_shoph, prt_shopd)"
. "VALUES (?, NOW(), ?, ? )");
$insert->bind_param('iss',
$os_id,
$os_shoph,
$os_shopd);
if($insert->execute()) {
echo '<h1>Print new order ', $os_id, '</h1>';
} else {
echo '<h1>Re-print order ', $os_id, '</h1>';
}
}
我添加了错误检查。
if (!($insert = $db->prepare("INSERT `f2go`.`prints` ("
. "prt_os_id, prt_ts, prt_shoph, prt_shopd)"
. "VALUES (?, NOW(), ?, ? )"))) {
echo "Prepare failed: (" . $db->errno . ") " . $db->error;
}
if (!$insert->bind_param("iss", $os_id, $os_shoph, $os_shopd)) {
echo "Binding parameters failed: (" . $insert->errno . ") " . $insert->error;
}
if (!$insert->execute()) {
echo "Execute failed: (" . $insert->errno . ") " . $insert->error;
}
结果是:
os_id = "206" os_shoph = 0228099392 os_shopd = example
Re-print order "206"
Execute failed: (1062) Duplicate entry '0' for key 'prt_os_id'
数据库列os_id设置为'unique' 我无法弄清楚为什么os_id = 206会被视为'0'
答案 0 :(得分:0)
在'prt_os_id'字段中插入'iss'值,它似乎是一个整数字段。 这个错误 执行失败:(1062)键'prt_os_id'重复输入'0' 参考插入查询将“0”值放在键prt_os_id中,当这种情况发生两次时,会显示此错误,那么为什么要插入“0”值?因为绑定中传递的第一个值是'iss',它是字符串值。它应该是:
$insert->bind_param("1", $os_id, $os_shoph, $os_shopd))
$insert->bind_param("2", $os_id, $os_shoph, $os_shopd))
$insert->bind_param("3", $os_id, $os_shoph, $os_shopd))
$insert->bind_param("4", $os_id, $os_shoph, $os_shopd))
等等。
答案 1 :(得分:0)
只需删除$os_id
!!
测试
<?php
$os_id ='"206"';
echo 'os_id = '.intval($os_id).'<br />';
$os_id ="206";
echo 'os_id = '.intval($os_id).'<br />';
$os_id =206;
echo 'os_id = '.$os_id.'<br />';
$os_id ="206";
echo 'os_id = '.$os_id.'<br />';
echo '-------------------------------------------------------------------------<br />';
$os_id ='"206"';
$os_id =trim($os_id, '"');
echo 'os_id = '.$os_id;
?>
输出
os_id = 0
os_id = 206
os_id = 206
os_id = 206os_id = 206