3

I have a script that i am writing to move certain fields to a new db like

$results = mysql_query ( "SELECT body, title  FROM $source_db.Post" );
while ($row = mysql_fetch_array($results)) {
if(mysql_num_rows($users_result) > 0){
    $insert = "INSERT INTO wp_posts (`body`,`title`) VALUES ('{$row['body']}', '{$row['row']}')";
    mysql_query($insert);
    }
}

but as you can see the query will break everytime due to the single and double quotes, is there a solution to this problem like herdok or something

INSERT INTO wp_posts (`body`,`title`)
            VALUES
                ('Here are the final returns from today's ...<br /><br />he stayed home...<br />
<div class="entry-content">
<div class="entry-body">', 'something')
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321
  • 1
    http://stackoverflow.com/questions/601300/what-is-sql-injection – Pekka Jan 21 '11 at 20:37
  • 1
    possible duplicate of [Best way to stop SQL Injection in PHP](http://stackoverflow.com/questions/60174/best-way-to-stop-sql-injection-in-php) – Pekka Jan 21 '11 at 20:37

3 Answers3

8

mysql_real_escape_string is made for just this.

PHP: mysql_real_escape_string

$insert = "INSERT INTO wp_posts ('body','title') VALUES ('".mysql_real_escape_string($row['body'])."', '".mysql_real_escape_string($row['row'])."')";
Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
1

The other option is to use mysqli and prepared statements

$stmt = $this->db->prepare("insert into table (id,name,longstring) values (?,?,?));
$stmt->bind_param('iss',$row["id"],$row["name"],$row["body"]);
$stmt->execute();

mysqli will bind the assigned parameters to the ? in the prepared statement as an integer (i) or a string (s).

JKupe
  • 11
  • 2
0

The sanest approach is to use bound parameters. Bobby Tables has examples.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335