我不知道我的查询有什么问题 我想添加一个特定的范围,然后将范围的id添加到同一表单中的项目表
$range_info = array (
'min_price' => $_POST['min_price'],
'max_price' => $_POST['max_price']
);
$item_info = array (
'item_name' => $_POST['item_name'],
'cat_id' => $cat_id,
'total_quantity' => $_POST['total_quantity'],
'available_for_sale' => $_POST['available_for_sale'],
'description' => $_POST['desc'],
'user_id' => $data['user_id']
);
$range_fields = '`' . implode("`, `", array_keys($range_info)) . '`';
$range_data = '\'' . implode("', '", $range_info) . '\'';
$fields = '`' . implode("`, `", array_keys($item_info)) . '`';
$data = '\'' . implode("', '", $item_info) . '\'';
mysql_query("INSERT INTO range($range_fields) VALUES ($range_data); INSERT
INTO items($fields, `range_id`) VALUES ($data, '".mysql_insert_id()."'");
答案 0 :(得分:1)
您需要在此处分离您的查询(并且您忘记关闭括号):
mysql_query("INSERT INTO range($range_fields) VALUES ($range_data)");
mysql_query("INSERT INTO items($fields, `range_id`) VALUES ($data, '".mysql_insert_id()."')");
请注意,您的查询不安全!在使用之前尝试清理帖子的数据,或者使用预设语句与mysqli
或转而使用 PDO !
答案 1 :(得分:0)
将插入查询存储到单独的变量中并运行
$range_info = array (
'min_price' => $_POST['min_price'],
'max_price' => $_POST['max_price']
);
$item_info = array (
'item_name' => $_POST['item_name'],
'cat_id' => $cat_id,
'total_quantity' => $_POST['total_quantity'],
'available_for_sale' => $_POST['available_for_sale'],
'description' => $_POST['desc'],
'user_id' => $data['user_id']
);
$range_fields = '`' . implode("`, `", array_keys($range_info)) . '`';
$range_data = '\'' . implode("', '", $range_info) . '\'';
$fields = '`' . implode("`, `", array_keys($item_info)) . '`';
$data = '\'' . implode("', '", $item_info) . '\'';
/*insert queries*/
$qr1 = "INSERT INTO range($range_fields) VALUES ($range_data)";
$qr2 = "INSERT INTO items($fields, `range_id`) VALUES ($data, '".mysql_insert_id()."')";
mysql_query($qr1);
mysql_query($qr2);
注意:
现在不推荐使用原始MySQL扩展,并且在连接到数据库时会生成E_DEPRECATED错误。而是使用MySQLi或PDO_MySQL扩展。
MySQLi教程:https://www.w3schools.com/PhP/func_mysqli_connect.asp