-6

以下是我的代码,但在 where 子句中出现错误

<?php

// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

$response = array();

$dom = new DOMDocument();
$dom->loadHTMLFile("http://www.pizzahut.com.pk/deals.html");
//echo $dom->saveHTML();
$table = $dom->getElementsByTagName('td');


for($i = 30; $i < 35; $i++ ){
    $deal = $table->item($i)->nodeValue;
   echo $deal;
}
$id = 1813660169;
$result = mysql_query("INSERT INTO cafes(deal)
        VALUES('$deal') WHERE `id` = " .$id) or die(mysql_error());


echo mysql_num_rows($result); 

if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Place successfully created.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = " ID already inserted";

        // echoing JSON response
        echo json_encode($response);
    }


?>

错误是“您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以id在第 2 行的 'WHERE = 1813660169' 附近使用正确的语法”

需要帮助

4

6 回答 6

6

基本语法中不能有子句。我认为你真正想要的是一个声明,WHEREINSERTUPDATE

UPDATE cafes SET deal = '$deal' WHERE id = $id

作为旁注,SQL Injection如果变量的值(s)来自外部,则查询很容易受到攻击。请看下面的文章,了解如何预防。通过使用PreparedStatements,您可以摆脱在值周围使用单引号。

于 2013-05-16T08:59:06.707 回答
2

插入语句未指定 where 子句,该行尚不存在,因此没有可匹配的内容。

$result = mysql_query("INSERT INTO cafes(deal)
        VALUES('$deal')) or die(mysql_error());

下面是来自 MySql 网站的插入语句的基本语法:

插入 [LOW_PRIORITY | 延迟 | HIGH_PRIORITY] [IGNORE] [INTO] tbl_name [(col_name,...)] {VALUES | VALUE} ({expr | DEFAULT},...),(...),... [ ON DUPLICATE KEY UPDATE col_name=expr [, col_name=expr] ... ]

请注意,示意图不包含 where 子句。

于 2013-05-16T08:59:57.403 回答
0

您应该用引号将变量括起来'',只需更改为

WHERE `id` = '" .$id."'")

正如建议的那样,您不能WHEREINSERT查询中使用,但您应该使用UPDATE查询,因此您的语法应如下所示:

$result = mysql_query("UPDATE cafes set deal = '$deal' WHERE `id` = '" .$id."'") or die(mysql_error());    

然后我希望您记住这些mysql_*功能已被弃用,因此我建议您切换到mysqliPDO

于 2013-05-16T08:59:40.083 回答
0

您不能在插入语句中使用 where 子句。看起来你正在寻找一个 UPDATE 查询试试这个

"UPDATE `cafes` SET deal =$deal where id =$id";
于 2013-05-16T08:59:54.160 回答
0

尽管可以将 SELECT 与 INSERT 一起使用,但不要将 WHERE 与 INSERT 一起使用,并且 SELECT 可以有 where 子句。

于 2013-05-16T09:02:02.390 回答
0

为什么要添加 WHERE 插入?它只是向表中插入记录。

于 2013-05-16T09:02:44.010 回答