2017-06-15 48 views
-1

我有下面的查詢,它工作得很好。使用php echo語句添加where子句

我可以作出聲明找到登錄的用戶ID:

$memberID = getLoggedMemberID(); 

是否可以添加到下面的SQL查詢嗎?喜歡的東西:你的意思是這樣

WHERE membership_userrecords.MemberID = $memberID 

任何意見將是巨大的

<?php 
$servername = "localhost"; 
$username = "root"; 
$password = "fdggsdtw3fg3f"; 
$dbname = "crm4"; 
// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 

// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 
      $memberID = getLoggedMemberID(); 

       $sql = "select * from membership_userrecords INNER JOIN Orders ON membership_userrecords.pkValue = Orders.id"; 

$result2 = $conn->query($sql); 
$row = $result2->fetch_assoc(); 
echo $row["id14"]; 

?> 
+0

不知道我是否有誤解,但是您是在[預備陳述](http://php.net/manual/en/mysqli.prepare.php)之後?這些將使您可以安全地將您的值放入查詢中。 – Mikey

+0

因此,目前,我已將用戶標識存儲在名爲$ memberID的變量中。我需要能夠查詢說WHERE DBFIELD = VARIABLE。我不知道該怎麼做? – Kieran

回答

0

$ sql =「select * from membership_userrecords INNER JOIN Orders ON membership_userrecords.pkValue = Orders.id WHERE membership_userrecords.MemberID =」。 mysql_real_escape_string($ memberId);

要驗證這一點,您可以打印$ sql並檢查memberId是否被成功替換。

+0

如果您只是將一個變量傳遞給SQL語句而沒有真正的限制,那麼您正在向潛在的SQL注入開放。 – Mikey

+0

是的,我知道,但這只是一個想法,該變量可以確實被替換。 – bharath

0

最簡單的形式,你可以改變:

$sql = "select * from membership_userrecords 
INNER JOIN Orders ON membership_userrecords.pkValue = Orders.id"; 

要:

$sql = "select * from membership_userrecords 
INNER JOIN Orders ON membership_userrecords.pkValue = Orders.id 
WHERE membership_userrecords.MemberID = " . mysql_real_escape_string($memberID); 
0

去你在您的評論說,我認爲以下可能是你以後在做什麼:

$memberID = getLoggedMemberID(); 

$sql = "SELECT * 
     FROM membership_userrecords 
     INNER JOIN Orders ON membership_userrecords.pkValue = Orders.id 
     WHERE membership_userrecords.MemberID = ?"; 

$statement = $conn->prepare($sql); 
$statement->bind_param('i', $memberID); 

$result2 = $statement->execute();