2012-12-11 45 views
1

我需要一些幫助添加一個PHP代碼到我的MySQL。下面是代碼:需要添加一個PHP對象到MySQL查詢

$query_qPosts = "SELECT * FROM front_news WHERE draft = 1 AND department_id = 1 OR  department_id = 0 ORDER BY id DESC"; 

它說:「部門標識= 1」我需要<?php echo $id ?>更換1次。

回答

3
$query_qPosts = "SELECT * FROM front_news WHERE draft = 1 AND department_id = $id OR  department_id = $id ORDER BY id DESC"; 

在php中,你可以在雙引號內封裝變量,它們將構成字符串的一部分。 e.g

$foo = 'foo'; 
$echo = "I am $foo"; 
----> I am foo 

凡爲單引號,你需要連接他們進來。 例如

$foo = 'foo'; 
$echo = 'I am ' . $foo; 
----> I am foo 

根據您使用哪一個,取決於您使用的環境,通常可根據個人喜好選擇。單引號執行速度快於雙引號。

+1

。我建議使用mysqli或PDO,因爲它們支持從查詢字符串中單獨發送的參數。 – Anton

0

當您在SQL查詢中使用「AND」和「OR」時,必須用圓括號組合。否則結果是不可預測的或者查詢失敗。

如果部門可以是0或1,草案必須是1做到這一點:

"SELECT * FROM front_news WHERE draft = 1 AND (department_id = 1 OR department_id = 0) ORDER BY id DESC" 

,或者如果有選秀是一個部門必須是1或部門爲0,試試這個:

"SELECT * FROM front_news WHERE (draft = 1 AND department_id = 1) OR department_id = 0 ORDER BY id DESC" 

我不確定你想要做什麼。

您正在做雙引號,因此代碼中的每個「$」都作爲變量執行。爲了確保這種情況發生,如果你想要「{$ id}」,你可以用大括號來包裝。

0
$query_qPosts = "SELECT * FROM front_news WHERE draft = 1 AND department_id = 1 OR department_id = ".$id." ORDER BY id DESC"; 
1

如果使用mysqli,它使這個過程很簡單:

$db = new mysqli("localhost", "user", "password", "mydatabase"); 
$query_qPosts = $db->prepare("SELECT * FROM front_news WHERE draft = 1 AND department_id = ? OR department_id = 0 ORDER BY id DESC") 
$id = 1; 
$query_qPosts->bind_param("i",$id) 
if (!$query_qPosts->execute()) { 
    echo "There was an error (" . $query_qPosts->errno . ") " . $query_qPosts->error; 
} 
0

嘗試

"SELECT * 
FROM front_news 
WHERE draft = 1 
    AND department_id = ".<?php echo (int)$id?>." 
    OR department_id = 0 
ORDER BY id DESC"; 
0

試試這個代碼:

$ query_qPosts =「SELECT * FROM front_news WHERE draft = 1 AND department_id = $ id OR department_id = 0 ORDER BY id DESC「;

請確保$ id爲號,此方法打開你的代碼多達注入攻擊,因此你需要把變量,直接進入您的查詢字符串之前,淨化你的投入不是空