DanyBv DanyBv - 5 months ago 57
PHP Question

Why mysqli_real_escape_string() returns NULL?

I am coding a login/register page.
I want to protect the form from sql injections using

mysqli_real_escape_string()
.
If I use it, the function returns
NULL
.

And I don't know why...
I searched and I found that maybe I am not connected to the database, but I am since I can query it .

This is the code that I am using to connect to the database (db.php):

<?php
$con = mysqli_connect("localhost","user","pass","database");

// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>


The code that returns NULL:

include("includes/db.php");
function escapeInput($data) {
$data = trim($data);
$data = htmlspecialchars($data);
$data = stripslashes($data);
$data = mysqli_real_escape_string($con, $data);
return $data;
}
if (isset($_SESSION['username'])){
header("Location: home.php");
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if($_POST['action'] == 'login')
{
$username = escapeInput($_POST['username']);
$password = escapeInput($_POST['password']);
var_dump($username);
$password = sha1($password, true);
$login = "SELECT COUNT(*) FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($con,$login);
$user = mysqli_fetch_array($result, MYSQLI_NUM);
if($user[0]) {
echo '<div class="alert alert-success" role="alert">Successfuly logged in.</div>';
// Store Session Data
$_SESSION['username'] = $username; // Initializing Session with value of PHP Variable
header("Location: home.php");
die();
}
else echo '<div class="alert alert-danger" role="alert">Incorrect username and/or password.</div>';
}
}

Answer

The reality is if you want to code a login page these days you shouldn't be using deprecated code. You should look in to PDO. I made the jump and it sounded scary at first but it was one of the best things I ever did. It's as simple as this.

$Qry = $db->prepare("SELECT COUNT(username) FROM users WHERE username = :User AND password = Pass");
$Qry->execute(array(':User'=>$username, ':Pass'=>$password));

Then you can use

$Qry->rowCount();

You'll have to change your connection string but it's much more secure and future friendly

Prepared Statements