-1

If I run this with the query

"SELECT * FROM users"; 

It returns my result. But as soon as I run this

$username = $_POST['username'];
$password = $_POST['password'];

$login = "SELECT * FROM users WHERE name= ".$username." AND password= ".$password."";

it doesn't.

If I run it in Mysql workbench without the variables it works. If I run echo the $_POST values they come through correctly. I am stumped as to what I'm doing wrong PLEASE!! help me. I also ran my code through https://phpcodechecker.com/ and it cant see any errors in my code. This is the full function.

function login($username,$password){
global $db_conn;
$conn = new mysqli($db_conn['servername'], $db_conn['username'], $db_conn['password'], $db_conn['dbname']);
$username = $_POST['username'];
$password = $_POST['password'];

$login = "SELECT * FROM users WHERE name= ".$username." AND password= ".$password."";
    $login_result = $conn->query($login);

    if ($login_result->num_rows > 0) {

        $output = array();
        while($row = $login_result->fetch_assoc()) {
            $output[] = $row;
            echo "".$row['name']."-".$row['password']."<br>";
        }
        } else {
            echo "Invaild Login Details!"."<br>" ;
            $conn->close();
            return false;
        }
}

Every time it says "Invalid Login Details!" But I know their is one result that gets returned.

What am I doing wrong?


Inserting variables into your SQL directly is a major source of SQL Injection Attacks. Use PDO for security. https://www.php.net/manual/en/book.pdo.php#114974

E_net4
  • 27,810
  • 13
  • 101
  • 139
13garth
  • 655
  • 1
  • 8
  • 22

5 Answers5

2

change the query like this

$login = "SELECT * FROM users WHERE name= '$username' AND password= '$password'";

note: this method is prone to sql injection attacks. try prepared statements to avoid it

Anandhu Nadesh
  • 672
  • 2
  • 11
  • 20
0

try with ''(single quote) for comparing name and password

"SELECT * FROM users WHERE name= '".$username."' AND password= '".$password."'";
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
-1
$login = "SELECT * FROM users WHERE name = '{$username}' AND password = 
'{$password}' ";
cmprogram
  • 1,854
  • 2
  • 13
  • 25
-1

You can simply specify the variables no need to go for string append to construct query in php

Eg :

Query = "SELECT * FROM `users` where username = '$username' AND  password = '$password' " ;
Naresh Kumar
  • 1,706
  • 1
  • 14
  • 26
-1

try following code

$login = "SELECT * FROM users WHERE name= '".$username."' AND password= '".$password."'";
romal tandel
  • 481
  • 12
  • 19