douzao2992 2016-01-19 06:06
浏览 13

无法使用预准备语句将值插入表2

I have two tables, called items and posts. The primary key item_id in the table one is the foreign key in the table two, using INT UNSIGNED NOT NULL. The table one stores the item_id (UNSIGNED NOT NULL AUTO_INCREMENT), user id and the title of the post. The table two stores the following info: item_id, user_id, message, and posted_on

I do the validation for the new item id before running the query to make sure that there is a new post before any query is run:

// 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;
}

After that, I make the INSERT INTO query using prepared statement for the table 2 like this:

$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();

Everything goes well, except that the item_id, which is inserted into the table2, appears to be 0 all the time, but not the same integer as it should be in the table 1 (Primary - Foreign' keys relationship b/w the two tables).

What did I do wrongly? can you help? Thanks.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 R语言Rstudio突然无法启动
    • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
    • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
    • ¥15 用windows做服务的同志有吗
    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值