2013-04-02 13 views
1

我想添加一個if語句到一個mysql查詢,以便它在查詢運行之前檢查用戶是否存在於user_id列中名爲ptb_users的表中。如何添加一個如果confiting到mysql查詢?

用戶可以在其他用戶的牆上寫字,並且在用戶可以在用戶牆上寫字之前/在查詢插入到ptb_wallposts之前,我希望它檢查from_user_id = ptb_users.user_id。

我試圖做到這一點,但我得到的語法錯誤都在我的頁面可以有人請能有人告訴我我怎麼會需要構建這樣的:如果存在

<?php 
// check if the review form has been sent 
if(isset($_POST['review_content'])) 
{ 
    $content = $_POST['review_content']; 
     //We remove slashes depending on the configuration 
     if(get_magic_quotes_gpc()) 
     { 
       $content = stripslashes($content); 
     } 
     //We check if all the fields are filled 
     if($_POST['review_content']!='') 
     { 

(從ptb_users其中USER_ID選擇USER_ID = @id) 開始

  { 
      $sql = "INSERT INTO ptb_wallposts (id, from_user_id, to_user_id, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$profile_id."', '".$content."');"; 
      mysql_query($sql, $connection); 

      $_SESSION['message']="<div class=\"infobox-wallpost\"><strong>Wall Post Added</strong> - Your comment was posted to {$profile[2]}'s wall.</div><div class=\"infobox-close4\"></div>"; 
header("Location: {$_SERVER['HTTP_REFERER']}"); 


     } } 
} 

端 別的 開始 回聲 「的錯誤用戶犯規存在」 端

?> 
+0

請,在此之前任何* *否則,在[正確的SQL逃逸(http://bobby-tables.com/php)讀取,以避免嚴重損害生涯[ SQL注入漏洞](http://bobby-tables.com/)。不要在新代碼中使用'mysql_query',這是危險的,不推薦使用,並且將從未來版本的PHP中刪除。 [PDO](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/)只需半小時[學習](http ://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/),所以除非你有一些遺留項目,否則就用它。 – tadman

+0

是否有任何理由爲什麼你從頭開始構建這個應用程序,而不是從[一個流行的框架](http://www.phpframeworks.com/top-10-php-frameworks/)開始?你將犯下無數的錯誤,並將不得不重塑那些已經被專家編碼,打包和記錄的東西。 – tadman

回答

0

這裏的if語句的例子(從MySQL參考)

IF search_condition THEN statement_list 
[ELSEIF search_condition THEN statement_list] ... 
[ELSE statement_list] 
END IF 

讓我解釋一下更好,我會PHP和SQL之間的比較,如果語句

PHP:

IF(variable > 0){ 
    anything..  
} 

SQL:

IF variable > 0 THEN anything.. 

瞭解更多:MySQL Reference - IF STATEMENT

+0

在MySQL裏面做'IF'似乎是一個失敗的原因。這是應用程序邏輯。 – tadman

相關問題