Hudzilla.org - the homepage of Paul Hudson
Contents > Databases > Using MySQL with PHP Wish List | Report Bug | About Me ]

9.4.5     Mixing in PHP variables: mysql_escape_string()

This is NOT the latest copy of this book; click here for the latest version.

string mysql_escape_string ( string unescaped_string)

Now we come to the really fun stuff - changing the query sent to MySQL based upon user input. We have already looked at creating forms to accept user input using HTML forms, and now we're going to look at how to accept that data and use it inside our table.

Given that the parameter for mysql_query() is just a string, we can use variables as we would in any other string - if the string is double-quoted, it is simply a matter of using the variable directly inside it, as PHP will convert it to its value automatically.

Consider the following part of a script:

$result = mysql_query("SELECT ID FROM webpages WHERE Title = '$SearchCriteria';");
$numhits = mysql_num_rows($result);
print
"Your search for $SearchCriteria yielded $numhits results";

The example above shows how easy it is to modify your SQL queries to respond directly to user submission. Imagine for a moment you stored all the pages in your website in an SQL database. You'd need to create your table something like this:

CREATE TABLE webpages (ID INT AUTO_INCREMENT PRIMARY KEY, Title VARCHAR(255), Content TEXT, DateModified INT);

With that table structure, it is very easy to create a simple search engine for the site. Our first attempt above is a little too simple - it will only return pages that match the exact submission from users. However, we've already looked at both the LIKE operator and FULLTEXT indexes, so you should know that you can modify the query to be much more helpful by doing this:

ALTER TABLE webpages ADD FULLTEXT (Title);
ALTER TABLE webpages ADD FULLTEXT (Content);

With FULLTEXT indexes on the two important fields in the web pages table, it is now easy to do a proper search through the table, even allowing visitors to use boolean search techniques with the following query:

SELECT ID FROM webpages WHERE MATCH(Title, Content) AGAINST ('$SearchCriteria' IN BOOLEAN MODE);

This time visitors can search for pages and find any pages that have a matching title or even matching content, and they can use +, -, or phrase searching to get more control over the results.

It is possible to use PHP variables wherever you want inside SQL queries, as long as at the end of the day you end up with a valid SQL query, otherwise mysql_query() will return false. Consider the following function:

function simplequery($table, $field, $needle, $haystack) {
    
$result = mysql_query("SELECT $field FROM $table WHERE $haystack = $needle LIMIT 1;");

    if (
$result) {
        if (
mysql_num_rows($result)) {
            
$row = mysql_fetch_assoc($result);
            return
$row[$field];
        }
    } else {
        print
"Error in query<BR />";
    }
}

That function allows you to pass in the name of the table you want to read, the field you are interested in, and the criteria it should match, then executes the appropriate query and sends the requested value back as its return value. This function can therefore be used like this:

$firstname = simplequery("usertable", "firstname", "ID", $UserID);

The advantage to this is that you can program all sorts of error checking into simplequery() without making your scripts any more cluttered to read. You should now be able to see that you can use PHP variables throughout your SQL code if you want to, although it is not often you use it quite so much!

Although mixing PHP variables into your MySQL calls is where the real power of PHP's database systems comes into play, you must be very, very careful not to allow your users to abuse your scripts to hack into your systems. The first but by no means only defence in this fight is the function mysql_escape_string(), which is designed to make PHP variables a little more safe when used inside MySQL queries. To use this function, pass the string in that you wish to make safer, and it will return the new value. The function works by escaping all potentially dangerous characters in the string you pass in, including single quotes - be wary about using this function in combination with addslashes().





<< 9.4.4 Reading in data: mysql_fetch_assoc()   9.4.6 Results within results >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 29 Aug 2008

Th3_Designer@ntlworld.com;

Yes you can change

ptalus - 29 Aug 2008

to: Dirk
mysql_real_escape_string() knows about different codepages, so if you use only one code page then you can use mysql_escape_string()

http://ptalus.blogspot.com

Th3_Designer@ntlworld.com - 29 Aug 2008

Could you change a SESSION value into a variable, like so:

$DiddleySquat = $_SESSION['loGinStoRe'];
$PantsDance = $_SESSION['thisISTheirPassWurd'];

OR something like that?!

Th3_Designer@ntlworld.com - 29 Aug 2008

Could you change a SESSION value into a variable, like so:

$DiddleySquat = $_SESSION['loGinStoRe'];
$PantsDance = $_SESSION['thisISTheirPassWurd'];

OR something like that?!

Dirk - 29 Aug 2008

you should ONLY use:

mysql_real_escape_string()

please note the "real" :-)
the mysql_escape_string should not be used!

micah.frost@gmail.com - 29 Aug 2008

"...be wary about using this function in combination with addslashes()."

Does this mean that you shoulduse both or only one?



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is zero plus three?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow