2017-05-06 94 views
0

我有一個點擊最喜歡的明星,我想檢查數據庫,如果記錄存在它將刪除記錄,如果它不存在它將插入記錄,什麼是問題未插入記錄刪除記錄,如果它存在,否則插入

 <?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"; 
    } 
?> 
+0

真的嗎?讓__sure__明白'mysqli_query'和'mysql_query'之間的區別,然後再來。 –

+0

@u_mulder抱歉,現在呢? –

+0

現在你必須明白這一行是什麼意思'$ query =($ con,「SELECT * from favorite where userid ='$ userid'AND L_ID ='$ landmarkid'」);' –

回答

0

嘗試向您的插入語句中添加單引號,看看它是否有效。改變這種說法;

$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') "); 

讓我知道是否有幫助,或者如果您發現問題。

+0

沒有任何內容插入 –

+0

你不需要引用標記時,整合整數值。我假設的* id * s是整數。 – Martin

0

我已在下面重寫您的代碼。

幾點:

  • 你的代碼是vulerable SQL注入這樣假設ID是一個數值我強迫輸入瓦爾($userid$landmarkid)是使用(int)鑄造整數。

  • 你的第一個檢查查詢可以返回一個值COUNT,它比返回*更好,那麼你可以爲你的if語句,$result['numb']檢查特定值。

  • 我已經在SQL中正確地轉義了您的php變量,但您確實應該嘗試使用爲此編寫的語句

  • 我不認爲你需要的try{} catch {}這裏作爲當前的代碼不會拋出異常(據我所知)

  • 添加LIMIT您delete語句使你永遠不能刪除比多預定的行數。這充當故障安全,因此您不會無意刪除整個表格。


<?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"; 
    } 
    ?> 

相關問題