删除记录(如果存在),否则插入

时间:2017-05-06 07:52:10

标签: php mysql

我有一个点击收藏的明星,我想检查数据库,如果记录存在则会删除记录,如果不存在则会插入记录,记录未插入的问题是什么

     <?php
    include "config.php";
    header('Content-Type: application/json');
    $landmarkid = $_GET['landmarkid'];
    $userid = $_GET['userid'];


    try {
        $query = mysqli_query($con,"SELECT * from favourite WHERE userid =$userid AND L_ID = $landmarkid");



        if(mysqli_num_rows($query) > 0)
        {
            $q1 = mysqli_query($con,"DELETE from favourite WHERE userid =$userid AND L_ID = $landmarkid");

            if($q1){
                echo '{"Deleted":"true"}';
            }
            else {
                echo '{"Deleted":"false"}';
            }
       } 
       else {
            $q2 = mysqli_query($con,"INSERT INTO favourite (userid,L_ID) VALUES ( $userid, $landmarkid) ");

            if($q2){
                echo '{"inserted":"true"}';
            }
            else {
                echo '{"inserted":"false"}';
            }
        }

        } catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
    }
?>

2 个答案:

答案 0 :(得分:0)

尝试在insert语句中添加单引号,看看它是否有效。改变这个陈述;

$q2 = mysqli_query($con,"INSERT INTO favourite (userid,L_ID) VALUES ( $userid, $landmarkid) ");

对此;

$q2 = mysqli_query($con,"INSERT INTO favourite (userid,L_ID) VALUES ( '$userid', '$landmarkid') ");

如果有问题或者您发现问题,请告诉我。

答案 1 :(得分:0)

我在下面重写了你的代码。

有些观点:

  • 您的代码对SQL注入是有趣的,因此假设id是一个数值,我强制输入变量($userid$landmarkid)使用(int)强制转换为整数。

  • 您的第一个检查查询可以返回COUNT值,这比返回*更好,然后您可以检查if语句的特定值$result['numb']。< / p>

  • 我已在SQL中正确转义了您的php变量,但您确实应该尝试使用准备好的语句

  • 我认为您不需要try{} catch {},因为您当前的代码永远不会抛出异常(据我所知)

  • 在您的删除语句中添加LIMIT,这样您就永远不会删除超过预期行数的行。这可以作为故障保护,因此您不会无意中设法删除整个表格。

 <?php
 include "config.php";
 header('Content-Type: application/json');
 $landmarkid = (int)$_GET['landmarkid'];
 $userid = (int)$_GET['userid'];

 try {
    $query = mysqli_query($con,"SELECT COUNT(*) as numb FROM 
             favourite WHERE userid = ".$userid." AND 
             L_ID = ".$landmarkid);
    $result = mysqli_fetch_aray($query);

    if($result['numb'] > 0)
    {
        $q1 = mysqli_query($con,"DELETE FROM favourite 
              WHERE userid = ".$userid." AND L_ID = ".$landmarkid." 
              LIMIT 1");
       print "deleted";
    } 
    else {
        $q2 = mysqli_query($con,"INSERT INTO favourite (userid,L_ID)
              VALUES ( ".$userid", ".$landmarkid.") ");
        print "inserted";
     }
  } 
  catch (Exception $e) {
      echo 'Caught exception: ',  $e->getMessage(), "\n";
  }
  ?>