Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysqli_real_escape_string() returns empty string

Tags:

php

mysql

I'm using mysqli_real_escape_string() on an email address, and it returns an empty string. It does this with any email address.

<?php
//from previous page - submitted by user.
$_POST['email']="[email protected]";
$_POST['password']='mypass1234';




//Link, I can verify it works.
$mysql_info=array(
     "url"=>"url",
     "username"=>"username",
     "password"=>"password",
     "database"=>"database"
);
$link=mysqli_connect($mysql_info['url'],$mysql_info['username'],$mysql_info['password'],$mysql_info['database']);


//Now I attempt to sanitize the user input.
$email=mysqli_real_escape_string($link,$_POST['email']);
$password=sha1(mysqli_real_escape_string($link,$_POST['password']));
var_dump($email);
var_dump($password);?>

My table's collation is "latin1_swedish_ci".

like image 748
Aehmlo Avatar asked Mar 04 '13 03:03

Aehmlo


People also ask

What is the use of Mysqli_real_escape_string () function?

The mysqli_real_escape_string() function is an inbuilt function in PHP which is used to escape all special characters for use in an SQL query. It is used before inserting a string in a database, as it removes any special characters that may interfere with the query operations.

When should I use Mysqli_real_escape_string?

You should use real_escape_string on any parameter you're mixing as a string literal into the sql statement. And only on those string literal values.

Why does Mysql_real_escape_string need a connection?

mysql_real_escape_string() and prepared statements need a connection to the database so that they can escape the string using the appropriate character set - otherwise SQL injection attacks are still possible using multi-byte characters.

Is Mysql_real_escape_string deprecated?

This extension was deprecated in PHP 5.5. 0, and it was removed in PHP 7.0.


1 Answers

If your connection is empty ($link), it will return an empty string. I tested this and it worked fine. I would recommend that you add error handling to your connection and enable error reporting.

<?php
$link = mysqli_connect("localhost", "root", "root", "test");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$_POST['email'] = "[email protected]";

$email = mysqli_real_escape_string($link, $_POST['email']);

var_dump($email);

mysqli_close($link);
?>

Result

string(17) "[email protected]"
like image 152
Kermit Avatar answered Oct 01 '22 20:10

Kermit