2017-08-26 150 views
-2

我是新手PHP開發人員,我想學習如何創建一個簡單的登錄之前,我與會話的那些和餅乾PHP的警告:mysqli_num_rows()預計參數1被mysqli_result,布爾給

放棄

我的第一個代碼的作品,但我想稍微減少代碼,所以我嘗試了其他的東西,這個錯誤出現,我很好奇爲什麼其他代碼不起作用,而他們似乎並沒有那麼不同

<?php 
//The code that works 
include("connection.php"); 

$connection = mysqli_connect(Server,Uid,Pwd,Database); 
if(!$connection){ 
    die("Connection failed!" . mysqli_error($connection)); 
} 

if(isset($_POST['submit'])){ 
    $username = mysqli_real_escape_string($connection,$_POST['username']); 
    $password = mysqli_real_escape_string($connection,$_POST['password']); 
    //$query = "SELECT * FROM 'user' WHERE Username = $username AND Password = $password"; 
    $query = "SELECT * FROM user WHERE Username= '". mysqli_real_escape_string($connection,$username) ."' AND Password = '". mysqli_real_escape_string($connection,$password) ."'" ; 
    $result = mysqli_query($connection,$query); 
    $count = mysqli_num_rows($result); 
    if ($count == 1){ 
     echo "Logged In Successfully! "; 
     } 
     else{ 
     echo "Log In Failed! Invalid Username or Password! "; 
     } 
} 

?> 



<?php 
//The code that doesn't work 
include("connection.php"); 

$connection = mysqli_connect(Server,Uid,Pwd,Database); 
if(!$connection){ 
    die("Connection failed!" . mysqli_error($connection)); 
} 

if(isset($_POST['submit'])){ 
    $username = mysqli_real_escape_string($connection,$_POST['username']); 
    $password = mysqli_real_escape_string($connection,$_POST['password']); 
    $query = "SELECT * FROM 'user' WHERE Username = $username AND Password = $password"; 
    $result = mysqli_query($connection,$query); 
    $count = mysqli_num_rows($result); 
    if ($count == 1){ 
     echo "Logged In Successfully! "; 
     } 
     else{ 
     echo "Log In Failed! Invalid Username or Password! "; 
     } 
} 

?> 

它們不應該只是相同的,因爲在代碼的第二個版本中,我只是將mysqli_real_escape_string放在變量的值中,所以如何來調用$ username和包含mysqli_real_escape_string的$ password變量會產生這個錯誤?那麼它總是必須像這樣每個查詢?

+0

爲什麼你加倍轉義字符串的用戶名和密碼?你也應該檢查是否沒有錯誤您運行查詢,然後嘗試計算行NUMS –

+0

變化'SELECT * FROM「用戶」 ...''到SELECT * FROM user'。單引號不允許用於封閉表名或列名。相反,使用反引號。 –

回答

0

1)變化SELECT * FROM 'user'..變爲SELECT * FROM user..。單引號不允許包含表或列名稱。相反,使用反向。

2)使用PHP Prepared Statements

3)如果DB存儲明文口令,然後將其保存到表之前對其進行加密。

<?php 
include("connection.php"); 

$connection = mysqli_connect(Server, Uid, Pwd, Database); 
if (!$connection) { 
    die("Connection failed!" . mysqli_error($connection)); 
} 

if (isset($_POST['submit'])) { 
    $stmt = mysqli_prepare($connection, "SELECT * FROM `user` WHERE Username = ? AND Password = ?"); 
    mysqli_stmt_bind_param($stmt, "ss", $_POST['username'], $_POST['password']); 
    mysqli_stmt_execute($stmt); 
    mysqli_stmt_store_result($stmt); 
    $count = mysqli_stmt_num_rows($stmt); 
    if ($count == 1) { 
    echo "Logged In Successfully! "; 
    } else { 
    echo "Log In Failed! Invalid Username or Password! "; 
    } 
} 
?> 
相關問題