简体   繁体   中英

How to check if user exists in database using PHP

SOLUTION: The the ending " after the SQL query was in the wrong place. and also declaring the $user and $password before the SQL query helped as well. Thanks all.

I am struggling to figure out why this does not work. To me it make perfect sense.

Also, I do know my code may be using old techniques and at risk for injection, this is just for a proof of concept.

Here is my code:

<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}

$db_select = mysql_select_db("test", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}

$username = $_POST['username'];

$result=mysql_query("SELECT * FROM Dbusers (username,pass) WHERE username,pass ='$username','$pass'");
if(mysql_num_rows($result) == 1) {

        header ("location: UniHelpindex.php");
}
else
{
    echo ("Login Details Wrong");
}

?>

Anything that my help let me know.

This is a syntax error:

WHERE username,pass ='$username','$pass'

You meant this:

WHERE username = '$username' AND pass = '$pass'

Also, where do you ever define $pass ? If you don't define it, then the SQL query may just be looking for an empty string which might not match any records (I hope).


When a query is failing, the system doesn't necessarily tell you outright. (Although in this case mysql_num_rows($result) is very likely throwing an error. Turn on error reporting, check your logs, etc.) Take a look at the mysql_error() function to check for errors any time mysql_query() returns false (which it does in the event of an error).


And, yes, insert the standard disclaimer here that you're using woefully outdated libraries and wide open to SQL injection.

我不确定,但是我认为您的SQL命令中的$ pass变量未定义。

don't use mysql_ it's depreciated. Use instead mysqli_

 $db=mysqli_connect('hostname','usrname','password','dbname')or die(<h2>some html code for showing the error</h2>);
$query="SELECT * FROM Dbusers WHERE username='$username' AND password='$password'";
$result=mysqli_query($db,$query);
if($mysqli_num_rows !=0){
//user was found stuff here 
}else{
//user not found stuff here
}
**I hope it helped**

解决方案:SQL查询后的末尾“放在错误的位置。并且在SQL查询之前也声明了$ user和$ password。同样,谢谢。

use a query like

SELECT pass from Dbusers WHERE username = '$username' LIMIT 1

This is very insecure though, please clean the data before using a query like this.

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