How to use mysql_real_escape_string function in PHP
Asked Answered
H

6

5

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?

Hanway answered 17/4, 2011 at 4:30 Comment(6)
I dont understand entering part... Are you grabbing entire query from user input or just some data to use later to generate query? I hope, that's not first case or you have serious problem with security.Tumbrel
Try this tutorial net.tutsplus.com/tutorials/php/…Impertinence
Chang: echo "Invalid Input"; To this: die('Invalid Input: ' . mysql_error()); To see if you get a mysql error.Wineshop
You might consider the option of using the mysqli interface with parameterized queries and avoiding the whole issue. It's what mysql recommends.Tody
Wh1T3h4Ck5: I probably should have specified that this is just a small project for a course I'm taking. It's true that I'm grabbing as input the entire query. Don't worry, I'm not asking you guys to do my homework. This error is obviously a minor part of my actual project.Hanway
If the old mysql extension is a part of the curriculum, then the course is dangerously out of date.Doublefaced
H
13

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);
Hebrews answered 17/4, 2011 at 4:32 Comment(0)
D
1

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".

Doublefaced answered 17/4, 2011 at 4:37 Comment(0)
T
1

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

Tetherball answered 17/4, 2011 at 4:39 Comment(0)
P
0

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);
Parental answered 17/4, 2011 at 4:34 Comment(0)
T
0

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.

Tumbrel answered 17/4, 2011 at 4:34 Comment(0)
P
0

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"); 
?>
Putter answered 18/7, 2015 at 19:14 Comment(1)
you swapped the elements in VALUES()Overstretch

© 2022 - 2024 — McMap. All rights reserved.