Casey Patton
Casey Patton

Reputation: 4091

How to use mysql_real_escape_string function in PHP

So in this program I'm writing, I actually grab a SQL query from the user using a form. I then go on to run that query on my database.

I know not to "trust" user input, so I want to do sanitization on the input. I'm trying to use mysql_real_escape_string but have been unsuccessful in getting it to work.

Here's what I'm trying, given the input: select * from Actor;

//"query" is the input string: 
$clean_string = mysql_real_escape_string($query, $db_connection); 
$rs = mysql_query($clean_string, $db_connection); 
if (!$rs) 
{ 
    echo "Invalid input!"; 
} 

This is ALWAYS giving me the

"Invalid input!"

error.

When I take out the clean_string part and just run mysql_query on query, the

"invalid input"

message is not output. Rather, when I do this:

$rs = mysql_query($query, $db_connection); 
if (!$rs) 
{ 
   echo "Invalid input!"; 
} 

It does NOT output

"invalid input".

However, I need to use the mysql_real_escape_string function. What am I doing wrong?

Update:

Given select * from Actor; as an input, I've found the following.

Using echo statements I've found that before sanitizing, the string holds the value: select * from Actor; which is correct. However, after sanitizing it holds the incorrect value of select *\r\nfrom Actor;, hence the error message. Why is mysql_real_escape_string doing this?

Upvotes: 5

Views: 41059

Answers (6)

dwolf
dwolf

Reputation: 1

This worked for me. dwolf (wtec.co)

<?php
// add data to db
require_once('../admin/connect.php');

$mysqli = new mysqli($servername, $username, $password, $dbname);

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

$post = $mysqli->real_escape_string($_POST['name']);
$title = $mysqli->real_escape_string($_POST['message']);


/* this query with escaped $post,$title will work */
if ($mysqli->query("INSERT into press (title, post) VALUES ('$post', '$title')")) {
    printf("%d Row inserted.\n", $mysqli->affected_rows);
}

$mysqli->close();


//header("location:../admin"); 
?>

Upvotes: 0

mario
mario

Reputation: 145472

mysql_real_escape_string() is the string escaping function. It does not make any input safe, just string values, not for use with LIKE clauses, and integers need to be handled differently still.

An easier and more universal example might be:

 $post = array_map("mysql_real_escape_string", $_POST);
 // cleans all input variables at once

 mysql_query("SELECT * FROM tbl WHERE id='$post[id]' 
                OR name='$post[name]' OR mtime<'$post[mtime]' ");
 // uses escaped $post rather than the raw $_POST variables

Note how each variable must still be enclosed by ' single quotes for SQL strings. (Otherwise the escaping would be pointless.)

Upvotes: 1

Wh1T3h4Ck5
Wh1T3h4Ck5

Reputation: 8509

manual mysql_real_escape_string()

Escapes special characters in a string for use in an SQL statement

So you can't escape entire query, just data... because it will escape all unsafe characters like quotes (valid parts of query).

If you try something like that (to escape entire query)

echo mysql_real_escape_string("INSERT INTO some_table VALUES ('xyz', 'abc', '123');");

Output is

INSERT INTO some_table VALUES (\'xyz\', \'abc\', \'123\');

and that is not valid query any more.

Upvotes: 0

outis
outis

Reputation: 77400

Rather than using the outdated mysql extension, switch to PDO. Prepared statement parameters aren't vulnerable to injection because they keep values separate from statements. Prepared statements and PDO have other advantages, including performance, ease of use and additional features. If you need a tutorial, try "Writing MySQL Scripts with PHP and PDO".

Upvotes: 1

Zach Rattner
Zach Rattner

Reputation: 21323

You should use mysql_real_escape_string to escape the parameters to the query, not the entire query itself.

For example, let's say you have two variables you received from a form. Then, your code would look like this:

$Query = sprintf(
    'INSERT INTO SomeTable VALUES("%s", "%s")', 
    mysql_real_escape_string($_POST['a'], $DBConnection),
    mysql_real_escape_string($_POST['b'], $DBConnection)
);

$Result = mysql_query($Query, $DBConnection);

Upvotes: 0

CrayonViolent
CrayonViolent

Reputation: 32532

use it on the actual values in your query, not the whole query string itself.

example:

$username = mysql_real_escape_string($_POST['username']);
$query = "update table set username='$username' ...";
$rs = mysql_query($query);

Upvotes: 13

Related Questions