这个SQL语句有什么问题?

时间:2013-07-23 19:48:14

标签: php sql

这是包含PHP文件:

<?php
session_start();
include("../includes/dbcxnfunction.inc");

$billid = $_POST['billid'];
$userid = $_SESSION['userid'];

$query = "IF EXISTS ( SELECT * FROM favoritebills WHERE userid = '$userid' AND billid = '$billid' )
              DELETE FROM favoritebills WHERE userid = '$userid' and billid = '$billid'         
          ELSE
              INSERT INTO favoritebills (userid,billid) VALUES($userid,$billid) ";

$result = mysqli_query(dbcxn('bill'),$query)
              or exit("Couldn't execute query for favorites");

if($result)
    {
    $request = "true";
    }
else 
    {
        $request = "false";
    }

echo $request;

?>

查询是:

"IF EXISTS ( SELECT * FROM favoritebills WHERE userid = '$userid' AND billid = '$billid' )
          DELETE FROM favoritebills WHERE userid = '$userid' and billid = '$billid'         
      ELSE
          INSERT INTO favoritebills (userid,billid) VALUES($userid,$billid) ";

userid和billid都是整数。

这是我的网络标签:

enter image description here

在我的.js文件中,我有console.log(response);

控制台正在记录“无法执行收藏夹查询”

2 个答案:

答案 0 :(得分:1)

您不能在查询中使用IF作为语句,它只能在存储过程中使用。要做你想做的事,你需要两个单独的查询。试试这个:

$del_query = "DELETE FROM favoritebills WHERE userid = '$userid' and billid = '$billid'";
$ins_query = "INSERT INTO favoritebills (userid,billid) VALUES($userid,$billid) ";

$res = mysqli_query(dbcxn('bill'),$del_query)
  or die ("Couldn't execute DELETE query: " . dbxcn('bill')->error);
if (dbcxn('bill')->affected_rows == 0) { // The row didn't exist, so add it
  $res = mysqli_query(dbcxn('bill'),$ins_query)
    or die ("Couldn't execute INSERT query: " . dbxcn('bill')->error);
}

$result = "true"; // No need to test for false, since we die above in that case

答案 1 :(得分:0)

你是否意识到如果记录存在,你就消除它们,什么都不留? 只有在记录不存在时才会发生插入。

不要试图将它们组合起来, 运行2个查询,     从哪里删除       然后     插入