简体   繁体   中英

How to escape string in mySQL

I am trying to construct a script (php) where I copy certain DB-fields from my old DB to a new one.

Some fields contains special characters like ' and I can't get around that the script crashes when a post includes this. I have tried with:

mysql_real_escape_string($cat2ss['name']) and mysql_real_escape_string(htmlspecialchars($cat2ss['name']))

but they both crashes.

Any ideas how to get around this?

This is a sample code:

$cat2s="SELECT * FROM o_product_description";
$cat2s_ex=mysql_query($cat2s) or die('<p>'.$cat2s.'</p>'.mysql_error());

while($cat2ss = mysql_fetch_array($cat2s_ex))
{
    $cat2sc = "INSERT INTO product_description (product_id, language_id, name, description, quality, catalog, cat_no, cat_val, cancellation, meta_description, meta_keyword, seo_keyword, catalogue, sort_order, attribut) VALUES ('".$cat2ss['product_id']."', '".$cat2ss['language_id']."', '".mysql_real_escape_string($cat2ss['name'])."', '".mysql_real_escape_string($cat2ss['description'])."', '".$cat2ss['quality']."', '".$cat2ss['catalog']."', '".$cat2ss['cat_no']."', '".$cat2ss['cat_val']."', '".$cat2ss['cancellation']."', '".$cat2ss['meta_description']."', '".$cat2ss['meta_keyword']."', '".$cat2ss['seo_keyword']."', '".$cat2ss['catalogue']."', '".$cat2ss['sort_order']."', '".$cat2ss['attribut']."')";

    $cat2sc_ex=mysql_query($cat2sc) or die('<p>'.$cat2sc.'</p>'.mysql_error());
}

Have you thought about using PDO? Without being able to give you exact code without knowing the line you want, you'd just do something like

$sql="SQL STATEMENT WITH :name"
$dbh->prepare($sql)
$dbh->execute(array(':name' => $cat2ss['name']));

I guess you're missing the database connection id. Your code should be something like:

$db = mysql_connect();
$var = mysql_real_scape_string($db, $the_string_to_scape);

Of course, you must connect to the database with the correct parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM