This question already has an answer here:
I am a newbie PHP Developer and I'm trying to study how to create a simple login before I forego with the ones with session and cookies
My first code works but I want to lessen the code a bit, So i tried something else and this error appears and I'm curious why the other code doesn't work whereas they don't seem to be that different
<?php
//The code that works
include("connection.php");
$connection = mysqli_connect(Server,Uid,Pwd,Database);
if(!$connection){
die("Connection failed!" . mysqli_error($connection));
}
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($connection,$_POST['username']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
//$query = "SELECT * FROM 'user' WHERE Username = $username AND Password = $password";
$query = "SELECT * FROM user WHERE Username= '". mysqli_real_escape_string($connection,$username) ."' AND Password = '". mysqli_real_escape_string($connection,$password) ."'" ;
$result = mysqli_query($connection,$query);
$count = mysqli_num_rows($result);
if ($count == 1){
echo "Logged In Successfully! ";
}
else{
echo "Log In Failed! Invalid Username or Password! ";
}
}
?>
<?php
//The code that doesn't work
include("connection.php");
$connection = mysqli_connect(Server,Uid,Pwd,Database);
if(!$connection){
die("Connection failed!" . mysqli_error($connection));
}
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($connection,$_POST['username']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$query = "SELECT * FROM 'user' WHERE Username = $username AND Password = $password";
$result = mysqli_query($connection,$query);
$count = mysqli_num_rows($result);
if ($count == 1){
echo "Logged In Successfully! ";
}
else{
echo "Log In Failed! Invalid Username or Password! ";
}
}
?>
Shouldn't they be just the same because in the second version of the code I just placed the mysqli_real_escape_string in the value of the variable so how come calling the $username and $password variable containing mysqli_real_escape_string produces this error? So does it always have to be like this every query?
</div>