简体   繁体   中英

Cannot get data from MySQL table with PHP request

I'm new to PHP and MySQL and trying to get a row returned from my table matching input from a HTML form. Code as follows:

$connect = mysqli_connect('localhost', 'root', '', 'testdb') 
OR die('Could not connect to the server' . mysqli_connect_error());

$query = ("SELECT * FROM users WHERE username = '$username'");
$result = mysqli_query($connect, $query);
$hits = mysqli_affected_rows($connect);

if ($hits < 1) {
   echo "Incorrect password or username";   
   die("<br /><a href='index.php'>Try Again<a/>");
} else {
   // other not relevant code here
}

The var $hits always comes back as 0, when there is data in the table matching the query.

var_dump($result) returns:

object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=>
int(4) ["lengths"]=> NULL ["num_rows"]=> int(0) ["type"]=> int(0) } 

You have to count your result, not the affected rows:

$connect = mysqli_connect('localhost', 'root', '', 'testdb') 
OR die('Could not connect to the server' . mysqli_connect_error());

$query = ("SELECT * FROM users WHERE username = '" . mysqli_real_escape_string($username) . "'");
$result = mysqli_query($connect, $query);
$hits = mysqli_num_rows($connect);

if ($hits < 1) {
   echo "Incorrect password or username";   
   die("<br /><a href='index.php'>Try Again<a/>");
} else {
   // other not relevant code here
}

Further: Don't pass the username without sanatizing.

Using the die() function breaks your application. It's better to catch the error and pass this to de view.

Use like this :

$connect = mysqli_connect(***'localhost'***, 'root', '', 'testdb') 
OR die('Could not connect to the server' . mysqli_connect_error());

$query = ("SELECT * FROM users WHERE username = '" . mysqli_real_escape_string($username) . "'");
$result = mysqli_query($connect, $query);
***$hits = mysqli_num_rows($result);***

if ($hits < 1) {
   echo "Incorrect password or username";   
   die("<br /><a href='index.php'>Try Again<a/>");
} else {
   // other not relevant code here
}

plz post user name ... and try this code .

 $connect = mysqli_connect('localhost', 'root', '', 'testdb') 
    OR die('Could not connect to the server' . mysqli_connect_error());

    $username=$_POST['username'];

    $query = ("SELECT * FROM users WHERE username = '$username'");

    $result = mysqli_query($connect, $query);
    $hits = mysqli_num_rows($connect);

    if ($hits < 1) {
       echo "Incorrect password or username";   
       die("<br /><a href='index.php'>Try Again<a/>");
    } else {
       // other not relevant code here
    }

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