循环遍历php中数据库表中的每一行

时间:2015-04-04 17:14:25

标签: php mysqli

我是php的新手。

我正在为用户登录,然后我想比较他/她登录我数据库表中每一行时的用户名和密码。

对于这种情况,假设user = michael,pssword = 1234

我明白了:

    $username= "michael";
    $password= "1234";

include("includes/connect.php"); 
$mobile_user = "select * from mobileuser" ;
$query = mysqli_query ($conn, $mobile_user);

while($results = mysqli_fetch_array ($query)){
      $user_name = $results['mobile_user_name'];
      $pass = $results['mobile_user_pass'];

   }

但是,这只与我数据库表中的最后一行数据进行比较。

例如,如果username = michael n password = 1234位于我的数据库表的最后一行,则登录成功,如果它不在最后一行,则登录失败。

任何人都可以提供帮助吗?

3 个答案:

答案 0 :(得分:0)

如果要检查用户的凭证是否有效,则应计算它们匹配的行数;如果小于1,则提供的凭据无效。 SQL查询:

SELECT COUNT(*) AS number, mobile_user_name, mobile_user_pass FROM mobileuser WHERE mobile_user_name = 'someusername' AND mobile_user_pass = 'somepass'

请注意,您应该阻止代码来自SQL injections,并且您可能希望在数据库中存储散列密码,以避免以明文形式存储它们。

答案 1 :(得分:0)

您应该将代码修改为:

$username= "michael";
$password= "1234";
include("includes/connect.php"); 

$mobile_user = "SELECT * FROM mobileuser WHERE mobile_user_name='$username' AND mobile_user_pass='$password' LIMIT 0,1";

$query = mysqli_query ($conn, $mobile_user);
$result = mysqli_fetch_array ($query);

$user_name = $result['mobile_user_name'];
$pass = $result['mobile_user_pass'];

这应该像魅力一样。然而,更好的版本是:

$username= "michael";
$password= "1234";
include("includes/connect.php"); 

$mobile_user = "SELECT count(*) as count FROM mobileuser WHERE mobile_user_name='$username' AND mobile_user_pass='$password'";

$query = mysqli_query ($conn, $mobile_user);
$result = mysqli_fetch_array ($query);

if($result['count'] > 0){
    echo "Match Found.";
}

答案 2 :(得分:0)

试一试:

require_once ('con.php');

        $q = "SELECT `password` FROM `tbl_where_user_is` WHERE `tbl_row_username` = '$username'";
        $r = mysqli_query($db_connnect, $q);
        $row = mysqli_fetch_array($r);

        $r = mysqli_query ($db_connnect, $q);   

        if(mysqli_num_rows($r)==1)
        {   
            echo $username; 
        }else{
            echo "user not found";
        }