我正在尝试使用 php 在 mysql 数据库中插入多行。 部分代码如下。
$b_address = $_POST["b_address"];
$s_address = $_POST["s_address"];
$query = "INSERT INTO order VALUES";
foreach ($_SESSION['buy'] as $products) {
$username = $_COOKIE["uname"];
$Product_Name = $products["Product_Name"];
$qty = $products["qty"];
$price = $products['qty'] * $products['Price'] ;
$query .= "('',
(select id from user_detail where user_name = $username ) ,
(select Product_id from products where Product_Name = $Product_Name ) ,
$qty,
$price ,
$b_address ,
$s_address ,
NOW()
),";
}
rtrim($query, ',');
但是我在选择 id 时遇到一些语法错误。 如何消除语法错误并正确运行代码?
我收到的错误如下:
errorYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order VALUES('', (select id from user_detail where user_name = ar' at line 1
编辑
我将该行更改为 $query = "INSERT INTO
订单VALUES";
现在我得到的错误是:
errorYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 21
编辑2
这是页面的完整代码,以防我盲目地在某个地方犯错。
<?php
session_start();
$con=mysql_connect('localhost','root','mypass');
if(!$con)
{
die ('connection error'.mysql_error());
}
mysql_select_db('test1',$con);
if (isset($_POST['submit'])) {
if (!empty($_POST['b_address']) && !empty($_POST['s_address']) ) {
$b_address = $_POST["b_address"];
$s_address = $_POST["s_address"];
$query = "INSERT INTO `orders` VALUES ";
foreach ($_SESSION['buy'] as $products) {
$username = $_COOKIE["uname"];
$Product_Name = $products["Product_Name"];
$qty = $products["qty"];
$price = $products['qty'] * $products['Price'] ;
$query .= "('',
(select id from user_detail where user_name = '$username' ) ,
(select Product_id from products where Product_Name = '$Product_Name' ) ,
'$qty',
'$price' ,
'$b_address' ,
'$s_address' ,
NOW()
),";
}
rtrim($query, ',');
if(!mysql_query($query,$con))
{
die ("error".mysql_error());
}
else
{
echo "Thank you for your purchase. Your order is under processing.";
unset($_SESSION['buy']);
}
}else{
echo 'All fields are required.';
}
}
最佳答案
试试这个:
请遵守顺序
$query = "INSERT INTO `order` VALUES ";
foreach ($_SESSION['buy'] as $products) {
$username = $_COOKIE["uname"];
$Product_Name = $products["Product_Name"];
$qty = $products["qty"];
$price = $products['qty'] * $products['Price'] ;
$query .= "('',
(select id from user_detail where user_name = '$username') ,
(select Product_id from products where Product_Name = '$Product_Name') ,
'$qty',
'$price' ,
'$b_address' ,
'$s_address' ,
NOW()
),";
说明:Order
是MySQL
保留字。
您不能在 SQL 中将其用于任何表名称或字段名称。
关于php - 如何在 php 中正确连接/转义此 sql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27037087/