PHP / SQL从表单插入数据并使用预准备语句

时间:2015-08-22 04:53:30

标签: php mysqli prepared-statement

我试图在我创建的网站上创建销售(想想易趣),用户输入所有输入详细信息以创建可销售商品,点击按钮和所有信息插入进入db表' sellitems'使用准备好的声明,现在我遇到的问题是我试图从表(用户)中获取用户位置(State& Suburb)详细信息,并将其插入到准备好的语句中,这些语句全部进入&#34 ; sellingitems"在sellitems表中使用SaleState,SaleSuburb,我得到的错误是

"致命错误:声明失败!您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册,以获得正确的语法,以便在' INSERT INTO sellitems(ItemID,UserID,CatID,ItemName,ItemDesc,ItemAmount,'在"第2行; / p>

我希望这是清楚易懂的,我已经研究了很多时间,并且无法通过加入或其他方式帮助我找到INSERT上的任何内容,请询问我是否需要澄清任何内容并提前感谢您的帮助! !

$stmt = mysqli_prepare($conn, "INSERT INTO sellingitems (ItemID, UserID, CatID, ItemName, ItemDesc, ItemAmount, TimeFrame, ItemCond, Postage, Returns, SaleState, SaleSuburb)
    SELECT State, Suburb FROM user WHERE UserID = '$UID' 
    VALUES ('',?,'',?,?,?, CURRENT_TIMESTAMP,?,?,?,State,Suburb)");

if ($stmt === false) {
trigger_error('Statement failed! ' . htmlspecialchars(mysqli_error($conn)), E_USER_ERROR);
}

$bind = mysqli_stmt_bind_param($stmt, 'issdsssss', $UID, $ItemName, $ItemDesc, $Amount, $ItemCond, $Postage, $Returns);

if ($bind === false) {
trigger_error('Bind param failed!', E_USER_ERROR);
}

$exec = mysqli_stmt_execute($stmt);

if ($exec === false) {
trigger_error('Statement execute failed! ' . htmlspecialchars(mysqli_stmt_error($stmt)), E_USER_ERROR); 
}


if ($stmt == false) {
    $response = "Sorry something went wrong. : ";
    print_r($response);
    print_r($stmt->mysqli_error);
    print_r($stmt->error);
    return;

} else {
    $response = "Sale Created.";
    print_r($response);
}

1 个答案:

答案 0 :(得分:0)

这不是INSERT SELECT的正确语法。 See the documentation

请改为尝试:

$stmt = mysqli_prepare($conn, "INSERT INTO sellingitems (ItemID, UserID, CatID, ItemName, ItemDesc, ItemAmount, TimeFrame, ItemCond, Postage, Returns, SaleState, SaleSuburb)
    SELECT '',?,'',?,?,?, NOW(),?,?,?,State,Suburb FROM user WHERE UserID = '$UID'");

更好的是将两个语句分开,如下所示:

$result = mysqli_query($conn, "SELECT State, Suburb FROM user WHERE UserID = '$UID'");
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

$stmt = mysqli_prepare(
    $conn, 
    "INSERT INTO sellingitems (
        ItemID, 
        UserID, 
        CatID, 
        ItemName, 
        ItemDesc, 
        ItemAmount, 
        TimeFrame, 
        ItemCond, 
        Postage, 
        Returns, 
        SaleState, 
        SaleSuburb)
     VALUES
     ('', ?, '', ?, ?, ?, NOW(), ?, ?, ?, '{$row['State']}', '{$row['Suburb']}')"
);