Jump to content

[SOLVED] help with mysql_escape_string


micah1701

Recommended Posts

I don't have magic_quotes on and I can't use addslashes to every variable when the data is posted (because it goes into a session array and is used on a bunch of pages before it ever gets to the point where it needs to be stuffed in a MySQL statement)

 

so the question is: is there a better way to addslashes to all the variables going into my query statement?

 

<?php

$var1 = "here's a string";
$var2 = "here's another string"
$query = "INSERT INTO table (col1,col2) VALUES ('$var1','$var2')";

echo $query; // returns: ...VALUES ('here's a string','here's another string')  <- no good.

echo mysql_escape_string($query); // returns: ...VALUES (\'here\'s a string\',\'here\'s another string\')  <- also no good.

// is there any existing function to get a return of: ...VALUES ('here\'s a string','here\'s another string')

?>

i know i could just use addslahses($var1); addslahses($var2);  but I have a LOT of variables in the query and I don't want to addslashes to them because I later need to strip the slashes.

 

Thoughts?

 

 

Link to comment
https://forums.phpfreaks.com/topic/72329-solved-help-with-mysql_escape_string/
Share on other sites

Create an array called $sqldata.  Make it a practice to only add escaped data to that array.  Also make it a practice to only use $sqldata when building queries.

 

Like so.

 

<?php

$var1 = "here's a string";
$var2 = "here's another string"

// don't use mysql_escape_string.  it is deprecated.
// use mysql_real_escape_string instead.
$sqldata['var1'] = mysql_real_escape_string($var1);
$sqldata['var2'] = mysql_real_escape_string($var2);

$query = "INSERT INTO table (col1,col2) VALUES ('$sqldata[var1]','$sqldata[var2]')";


?>

Use an array and a loop:

<?php
$vars = array('colname' => 'varname','colname1' => 'varname1','colname2' => 'varname2','colname3' =>'varname3');
$qtmp = array();
foreach ($vars as $col => $name)
  $qtmp = $col . " = '" . mysql_real_escape_string($$name) . "'";
$q = "insert into tablename set " . implode(', ',$qtmp);
?>

 

This uses the alternate insert syntax that looks like the update syntax.

 

If the values are coming from a form, just loop through the $_POST or $_GET array.

 

Ken

I like both these ideas.

 

most the variables are in a $_SESSION array so I think i'll do a foreach loop through it to create a duplicate array called $SQL_DATA that contains the same information, only escaped with mysql_real_escape_string.

 

Thanks!

 

(i'll leave this "unsolved" for a little bit longer in case someone else wants to share :-) )

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.