0

Possible Duplicate:
Mysql Real Escape String PHP Function Adding “\” to My Field Entry

So here's the deal. I have a local server and a remote server and they both run the same php file which connects to 2 identical mysql databases. On the local server, the command

mysql_query("INSERT INTO eventtypes (name) VALUES ('".addslashes($_GET['name'])."')")

works like a charm, and does not insert the slashes into the field, only the raw value of the $_GET['name']. On the remote server however, the slashes are being inserted too. I have tried these:

mysql_query("INSERT INTO eventtypes (name) VALUES ('".str_replace("'","''",$_GET['name'])."')

This one returns false, although when I run the exact returned string on the command line of the corresponding database, it properly inserts the right amount of single quotes, which is super-weird.

mysql_query("INSERT INTO eventtypes (name) VALUES ('".mysql_real_escape_string($_GET['name'])."')")

mysql_real_escape_string() only added slashes to the single quotes, which were also inserted like with addslashes().

4

3 回答 3

2

It sounds like you have Magic Quotes enabled on the remote server. This feature is causing the inconsistency you have discovered. Turn it off.

Once you have fixed that problem, the best approach of the three you are trying is mysql_real_escape_string. However, that is a legacy approach and not recommended. Use a modern database library (such as mysqli or PDO) and bound arguments. See also Best way to prevent SQL Injection in PHP.

于 2012-09-08T08:13:22.513 回答
1

Stop using mysql_query.

Use PDO and parameterized queries.

$pdo = new PDO($dsn, $username, $password);
$statement = $pdo->prepare("INSERT INTO eventtypes (name) VALUES (:eventype)");
$statement->execute(array('eventtype' => $_GET['name']));
于 2012-09-08T08:13:13.687 回答
0

You're code is prone to SQL Injection. The best method is to use PDO or MYSQLI

Example of using PDO extension:

<?php

    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    $stmt = $dbh->prepare("INSERT INTO eventtypes (name) VALUES (?)");
    $stmt->bindParam(1, $_GET['name']);
    $stmt->execute();

?>

this will allow you to insert records with single quotes.

于 2012-09-08T08:12:41.153 回答