将Session变量插入到查询中时出错

时间:2015-09-21 05:02:13

标签: php mysql

我收到此错误:

  

错误:INSERT INTO order(username,productName,qty)VALUES(' denieall.joe',' Wrist Watch',' 1')   您的SQL语法有错误;查看与您的MySQL服务器版本相对应的手册,以获得正确的语法,使用附近的订单(用户名,产品名称,数量)VALUES(' denieall.joe',' Wrist Watch' ;,' 1'在第1行

<?php
session_start();
include("includes/constants.php");
include("includes/functions.php");

    if (!isset($_SESSION['username']))
    {
        redirect_to_home();

    }

//conection and select database: 
    $conn = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME) or die("Error !!!" ); 

    foreach ($_SESSION["cart_products"] as $cart_itm)
    {

        $sql = "INSERT INTO order (username, productName, qty) 
        VALUES ('{$_SESSION['username']}', '{$cart_itm['product_name']}', '{$cart_itm['product_qty']}')";

        if (mysqli_query($conn, $sql)) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        }

    }
        mysqli_close($conn);
?>

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

你应该使用order

的反引号

INSERT INTO order

INSERT INTO `order`

与任何其他保留字一样 http://dev.mysql.com/doc/refman/5.6/en/keywords.html

答案 1 :(得分:0)

您只需将其与

一起使用即可
$name = $_SESSION['username'];
$product_name = $cart_itm['product_name'];
$product_qty = $cart_itm['product_qty'];

$sql = "INSERT INTO `order` (username, productName, qty) VALUES ('$name', '$product_name', '$product_qty')";