简体   繁体   中英

Use a function which mimics the original mysql_real_escape_string

I try to extract some information from one table and insert it to another. I'm using the following function from https://php.net/mysql_real_escape_string to handle the escape characters.

<?php 
function mysql_escape_mimic($inp) { 
    if(is_array($inp)) 
        return array_map(__METHOD__, $inp); 

    if(!empty($inp) && is_string($inp)) { 
        return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp); 
    } 

    return $inp; 
} 
?>

The string I deal with is in html form with double and single quotes like

<input type="radio" value="choice_3" checked="true"/> Eat pig's belly and swine's matrix

I have to use string concatenation to write queries because column names and table names are dynamic.

$query .= "'".mysql_escape_mimic($string)."', ";

I know there is some kind of syntax error but I don't know how to fix it. Can anyone help me with it? Thanks.

I suspect your problem is with this line:

$query .= "'".mysql_escape_mimic($string)."', ";

That concatenation will leave a trailing comma, which almost certainly is causing a syntax error in your SQL. In SQL, any set of terms that are to be separated by commas must not have a trailing comma at the end of that set.

You can use a PHP trimming function to trim off the trailing ", " after you are done building the concatenated string.


I would also like to note that you can accomplish what your stated goal is ("extract some information from one table and insert it to another") entirely within the database. That is, you don't need to SELECT it into your application and then re-INSERT into the other table, thus avoiding this problem entirely.

If the two tables have identical columns, then something like this should work:

INSERT INTO table2 SELECT * FROM table1 WHERE condition;

If the two tables do not have identical columns, then something like this should work:

INSERT INTO table2 (column1, column2, column3, ...)
SELECT columnA, columnB, columnC, ...
FROM table1
WHERE condition;

I cribbed these directly from w3schools.com . You can search for many such examples using the search string "mysql select from one table into another".

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