DanyBv DanyBv - 1 year ago 192
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

If I use it, the function returns

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):

$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:

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($_POST['action'] == 'login')
$username = escapeInput($_POST['username']);
$password = escapeInput($_POST['password']);
$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");
else echo '<div class="alert alert-danger" role="alert">Incorrect username and/or password.</div>';

Answer Source

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


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

Prepared Statements

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download