mysql_real_escape_string in php – mysql_real_escape_string example

mysql_real_escape_string in php, The mysqli_real_escape_string() function is an inbuilt function in PHP Example.

PHP mysqli real_escape_string() Function

The mysql_real_escape_string() function escapes special characters in a string for use in an SQL statement.

The following characters are affected:

  • \x00
  • \n
  • \r
  • \
  • \x1a

mysql_real_escape_string in php

function retriveTxtVal($key)
{
    $value = (isset($_REQUEST[$key])) ? $_REQUEST[$key] : "";
    return mysql_real_escape_string(trim($value));
}

Example #1 Simple mysql_real_escape_string() example

<?php
// Connect
$connect = mysql_connect('mysql_host', 'atmiys42', '[email protected]#542121')
    OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM members WHERE member='%s' AND member_pass='%s'",
            mysql_real_escape_string($member),
            mysql_real_escape_string($memberPass));
?>

mysqli real escape string php

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "atmiys42", "[email protected]#542121", "pakainfo_v1");

$mcode = "'s-Pakainfo45242f454d";

/* this query with escaped $mcode will work */
$sql_qq= sprintf("SELECT members FROM mcode WHERE name='%s'",
    mysqli_real_escape_string($mysqli, $city));
$data_v1= mysqli_query($mysqli, $sql_qq);
printf("Select returned %d rows.\n", mysqli_num_rows($data_v1));

/* this sql_qq will fail, because we didn't escape $mcode*/
$sql_qq = sprintf("SELECT members FROM mcode WHERE name='%s'", $mcode);
$data_v1 = mysqli_query($mysqli, $sql_qq);

Don’t Miss : PHP MySQLi Advance Live Searching

Read Also:  PHP Laravel Store Array in Session Examples

An example SQL Injection Attack

<?php
// Query mysql database to check if there are any matching members
$sql_qq = "SELECT * FROM members WHERE member='{$_POST['membername']}' AND password='{$_POST['password']}'";
mysql_query($sql_qq);

// We didn't check $_POST['password']
$_POST['membername'] = 'admin';
$_POST['password'] = "' OR ''='";

echo $sql_qq;
?>

SELECT * FROM members WHERE member='admin' AND password='' OR ''=''

I hope you get an idea about mysql_real_escape_string in php.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.