简体   繁体   中英

i am trying to add 2 queries at the same time using php and mysql

i don't know what is the problem with my query i want to add a specific range, then add the id of the range to the table of items within the same form

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

You need to separate your queries (and you forgot to close a parentheses) here :

mysql_query("INSERT INTO range($range_fields) VALUES ($range_data)");
mysql_query("INSERT INTO items($fields, `range_id`) VALUES ($data, '".mysql_insert_id()."')");

Note that your queries are insecure ! try to sanitize the data of your post before using it or use prepared statements with mysqli or move to PDO instead!

Store the insert queries into a separate variable and run

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

Note:

The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MySQLi or PDO_MySQL extensions.

MySQLi tutorial: https://www.w3schools.com/PhP/func_mysqli_connect.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM