简体   繁体   中英

Loop through every row in a database table in php

I am new to php.

I am doing login for user, then I would like to compare the username and password of the person when he/she login to every rows in my database table.

For this case, assume user= michael, pssword =1234

I got this:

    $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'];

   }

However, this only compare to the last row of data in my database table.

For example, if username=michael n password=1234 is located in the last row of my database table, then login success, if it does not located at the last row, login failed.

Anyone can help?

If you want to check if a user's credential are valid, you should count the number of rows where they match ; if this is less than one, the credentials provided are invalid. SQL query :

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

Note that you should prevent your code from SQL injections , and you may want to store hashed passwords in your database to avoid stocking them in cleartext.

You should modify your code as:

$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'];

This should work like a charm. However a better version of this would be:

$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.";
}

give this a go:

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";
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM