phpnoobie
phpnoobie

Reputation: 71

How to properly use mysqli_real_escape_string

I am having a problem that I just can not wrap my head around.

When saving a name to mysql database if the name contains an apostrophy (single quote) I am getting unexpected results.

I have saved the name using $name = mysqli_real_escape_string($con, $name);where $con is the connection string and $name is the name. However instead of $name coming back as Peter O'Toole, what I am getting is Peter O\

Can someone please tell me where I am going wrong here?

Upvotes: 0

Views: 1794

Answers (1)

rray
rray

Reputation: 2556

When you change mysql_* to mysqli does not need use the same style, use prepared statements.

Old style

$name = mysqli_real_escape_string($_POST['name']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);

$sql = "INSERT INTO `user`(name, email, password) VALUES('$name', '$email', '$password'));

$mysql_query($sql) or die(mysql_error());

at bind_param() inform the type of date:

s => string
i => integer
d => double
b => blob

Prepared stamentes style

$db = new mysqli(...);
$sql = "INSERT INTO `user`(name, email, password) VALUES(?,?,?)";
$stmt = $db->prepare($sql);
$stmt->bind_param('sss', $name, $email, $password);

if(!$stmt->execute()){
    echo $db->error;
}

Upvotes: 2

Related Questions