-5

这是包含的 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 都是整数。

这是我的网络标签:

在此处输入图像描述

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

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

4

2 回答 2

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
于 2013-07-23T19:58:33.967 回答
0

您是否意识到,如果记录存在,您会删除它们,什么都没有?插入仅在记录不存在时发生。

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

于 2013-07-23T19:58:48.680 回答