Forum Moderators: coopster

Message Too Old, No Replies

mysql real escape string() in Conditional Statements

         

HoboTraveler

4:44 am on Jun 26, 2007 (gmt 0)

10+ Year Member



Hi All,

I created the following bit of code that allows me to pass a MySQL conditional statement to a function.

I am trying to figure out where and how would I go about incorporating the mysql_real_escape_string() function?

Is there a way to call the mysql_real_escape_string() in the function itself?

// Vars
$name = "foobar";
$conditional_statement = "WHERE name=\"$name\"";

// Call function
$select_record = select_record($conditional_statement);
$coName = $select_record['email'];

// Function
function select_record($conditional_statement)
{
$SqlSelectQuery = sprintf
("
SELECT
name,
email
FROM
table
$conditional_statement
"

);
}

tomda

5:42 am on Jun 26, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi,

mysql_real_escape_string is used agains MySQL injection, it is often used to make any variables or user inputs safe for running the SQL queries.

Let me drop the function I often use

function mysql_safe($var) {
$var=rtrim($var); // RIGHT TRIM
$var=ltrim($var); // LEFT TRIM
$var=strip_tags($var); // STRIP HTML TAGS
if (get_magic_quotes_gpc()) {
$var = stripslashes($var);
} // STRIP SLASHES IF MAGIC QUOTES IS ON IN INI SETTINGS
$var = mysql_escape_string($var); // THE ESCAPE STRING FUNCTION
return $var;}

Note that I use mysql_escape_string and not mysql_real_escape_string. I have no time to search for differences between the two, but I am sure someone else will drop an explanation.

Then, you just do the following, that is used the mysql_safe function you just created to make any user input safe. Here, you only have one which is $name.

// Vars
$name = mysql_safe("foobar");
$conditional_statement = "WHERE name=\"$name\"";

Hope it helps.
Please, report back

Tomda

phranque

8:23 am on Jun 26, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



according to the php.net mysql-escape-string page [us.php.net]:
This function is deprecated.

This function is identical to mysql_real_escape_string() except that mysql_real_escape_string() takes a connection handler and escapes the string according to the current character set.

HoboTraveler

9:13 am on Jun 26, 2007 (gmt 0)

10+ Year Member



Hello,

The PHP manual recommends the "Best Practice" query as calling the mysql_real_escape_string() in the SQL statement itself.

I think calling mysql_real_escape_string() outside the SQL statement may not be most secure way..?

tomda

10:28 am on Jun 26, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I think it is just the same since you SQL query is creating by putting pieces of PHP variables together.

What I gave you above should be just as safe as your last assumption.

Tomda