2015-11-24 53 views
0

我有一個名爲$ addressdb的數據庫。我想通過用戶輸入的結果($ usersName)搜索該數據庫上的表。我的錯誤可能真的很愚蠢。我是mySQL的新手。使用PHP變量來搜索SQL數據庫

<?php 

//IF THE LOGIN is submitted... 
if ($_POST['Login']){ 
    $servername = "localhost"; 
    $username = "root"; 
    $password = ""; 
    $dbname = "addressdb"; 
    $usersName = $_POST['users']; 

// Create connection 
$conn = mysqli_connect($servername, $username, $password, $dbname); 
// Check connection 
if (!$conn) { 
    die("Connection failed: " . mysqli_connect_error()); 
} 

$sql = "SELECT userID, userName FROM users WHERE userName =$usersName"; 
$result = mysqli_query($conn, $sql); 

...

我的錯誤的行

$sql = "SELECT userID, userName FROM users WHERE userName =$usersName"; 

更具體的變量調用。

+0

用單引號括住'$ userName':'userName ='$ usersName'' –

+1

我總是喜歡使用'WHERE userName ='「。$ username。」'' – Peter

+0

謝謝!有效! – LifeofBob

回答

0

嘗試這樣:

$sql = "SELECT userID, userName FROM users WHERE userName = '".$usersName."'"; 
0

您需要使用您的周圍$ USERNAME報價。

$sql = "SELECT userID, userName FROM users WHERE userName = '$usersName'"; 

但要清楚,你應該逃避你的用戶輸入至少有mysqli_real_escape_string($conn, $userName);

0

最好的辦法是:

$sql = "SELECT userID, userName FROM users WHERE userName ='".mysqli_real_escape_string($conn, $usersName)."'"; 

在這裏,因爲你是通過純文本就不是那麼適用。但是,從html頁面獲取數據時,應該採用這種方式。