2017-08-08 93 views
-4

我的問題是我的函數返回空值,並且不執行我的查詢返回NULL THST執行查詢

function getUsers($username,$fields = '*') 
{ 
    $db_host = "localhost"; 
    $db_user = "root"; 
    $db_pass = ""; 
    $db_name = 'filemanagerusers'; 
    $connection = new mysqli($db_host,$db_user,$db_pass,$db_name); 
    //////////////////////////////////////////////////////////////// 
    $query = "select $fields from users where username=".$username; 
    $result = $connection->query($query); 
    $customers = mysqli_fetch_assoc($result);//etelaate user dar ghalebe yek array be ma barmigarde 
    return $customers; 
} 
+1

你確定你的'用戶名是一個整數?如果未包含在引號內 – Thamilan

+0

開始檢查失敗查詢時的錯誤。 – deceze

+0

你有什麼錯誤嗎? –

回答

2

快速不安全修復你(但不最好由於SQL注入): -

$query = "select $fields from users where username= '$username'"; 

注意: - 用引號括起$username使其成爲字符串。

的首選方法: -

始終使用prepared statementsmysqli_*防止SQL Injection象下面這樣: -

function getUsers($username,$fields = '*') 
{ 
    $db_host = "localhost"; 
    $db_user = "root"; 
    $db_pass = ""; 
    $db_name = 'filemanagerusers'; 
    $connection = mysqli_connect(($db_host,$db_user,$db_pass,$db_name); 
    /* check connection */ 
    if (mysqli_connect_errno()) { 
     printf("Connect failed: %s\n", mysqli_connect_error()); 
     exit(); 
    } 
    if ($stmt = mysqli_prepare($connection, "SELECT $fields FROM users where username=?")) { 

     /* bind parameters for markers */ 
     mysqli_stmt_bind_param($stmt, "s", $username); 

     /* execute query */ 
     mysqli_stmt_execute($stmt); 

     /* bind result variables */ 
     mysqli_stmt_bind_result($stmt, $customers); 


     /* close statement */ 
     mysqli_stmt_close($stmt); 

     /* return result*/ 

     return $customers; 
    } 
} 
+2

第二個剪輯應該是唯一提供的解決方案。另外,必須確保'$ fields'不是用戶控制的。 – 2017-08-08 13:29:31