我有两个表,分别叫items
和posts
。表1中的主键 item_id 是表2中的外键,使用INT UNSIGNED NOT NULL
。表1存储item_id
(UNSIGNED NOT NULL AUTO_INCREMENT),用户ID和帖子的标题。表格2存储以下信息:item_id, user_id, message,
和posted_on
我在运行查询之前对新商品ID进行验证,以确保在运行任何查询之前有新帖子:
// Validate item ID ($itemid), which may not be present:
if (isset($_POST['itemid']) && filter_var($_POST['itemid'], FILTER_VALIDATE_INT, array('min_range' => 1)) ) {
$itemid = $_POST['itemid'];
} else {
$itemid = FALSE;
}
之后,我使用表2的预准备语句进行INSERT INTO
查询,如下所示:
$q = "INSERT INTO tablename2 (item_id, user_id, message, posted_on) VALUES (?,?,?, UTC_TIMESTAMP())";
//Prepare the statement
$stmt = $mysqli->prepare($q);
//Bind the parameters
$stmt->bind_param('iis', $item_id, $user_id, $message);
//Assign values to variables
$item_id = (int)$_POST['itemid'];
$user_id = $_SESSION['user_id'];// The user_id value would normally come from the session.
$message = strip_tags($_POST['message']);
//Execute the statement
$stmt->execute();
if ($mysqli->affected_rows == 1) {//
echo '<p>Your post has been entered.</p>';
} else {
echo '<p>Your post could not be handled due to a system error.</p>';
echo '<p>' . $stmt->error . '</p>';
}
// Close the statement:
$stmt->close();
一切顺利,但插入到table2中的item_id
似乎始终为0,但与表中应该的整数不同1(Primary - Foreign' keys relationship b/w the two tables
)。
我做错了什么?你能帮我吗?感谢。