【问题标题】:PHP/SQL Insert data from form and insert data from another table using prepared statementPHP/SQL 使用准备好的语句从表单中插入数据并从另一个表中插入数据
【发布时间】:2015-08-22 04:53:30
【问题描述】:

我正在尝试在我正在创建的网站上创建销售(想想 ebay),用户输入所有输入详细信息以创建可销售项目,单击按钮并将所有信息插入 db 表'salesitems' 使用准备好的语句,现在我遇到的问题是我试图从表(用户)中获取用户位置(州和郊区)详细信息,并将其插入到所有进入“销售项目”的准备好的语句中在 salesitems 表中使用 SaleState、SaleSuburb,我得到的错误是

" 致命错误:语句失败!您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以了解在 'INSERT INTO sellitems (ItemID, UserID, CatID, ItemName, ItemDesc) 附近使用的正确语法, ItemAmount,' 在 "

中的第 2 行

我希望这是清楚易懂的,我已经研究了好几个小时,在 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);
}

【问题讨论】:

  • 嗯,那个 SQL 语句是无效的,所以...

标签: php mysqli prepared-statement


【解决方案1】:

这不是 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']}')"
);

【讨论】:

  • 非常感谢,您的第二个选项很有效!
  • 第一个选项也很好用:-),再次感谢!!
  • 我想投票并做出回答,但据说我还需要 15 个声望点 :-( 对不起 dlporter98
  • 您应该能够接受答案而无需投票
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
  • 2017-11-29
  • 1970-01-01
  • 2016-04-05
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多