0

Hi I have a question about my writing to my database:

I'm new to the mysql_escape_string because a friend told me. Since I use mysql_escape_string it doesn't write to my db anymore.

Here is the code:

////////////////////////////////////////////////////////////////
 $iets = $_POST['aantal'] + $_POST['begin'];

 for ($i = $_POST['begin'] ; $i < $iets ; $i++){
     $rows = $rows.'a'.$i.', ';
 }

 $rows = mysql_escape_string(trim($rows, ', '));
/////////////////////////////////////////////////////////////////////
 $iets = $_POST['aantal'] + $_POST['begin'];

 for ($i = $_POST['begin'] ; $i < $iets ; $i++){
     $r = 'a'.$i;
    $values = $values.'\''.$_POST[$r].'\', ';
 }

 $values = mysql_escape_string(trim($values, ', '));


$naam = mysql_escape_string($_POST['naam']);

mysql_query("INSERT INTO $naam
(
$rows
)
VALUES 
(
$values
)");
mysql_close($con);


printf("%s<br />%s", $values, $rows);

When I have :

aantal = 3
begin = 4

The output of printf, with a4=abcdef, a5=ghijkl, a6=mnopq is:

\'abcdef\', \'ghijkl\', \'mnopq\'<br />
a1, a2, a3

I don't get it, the backlashes shouldn't have an impact right?

ShellFish
  • 4,351
  • 1
  • 20
  • 33
Dylan Westra
  • 611
  • 1
  • 5
  • 10
  • make `mysql_escape_string` the last thing you do to the values before putting them in the database. – George Dec 14 '12 at 13:54
  • 2
    Anyway, I would recommend you to forget about `mysql_query` and start making use of secure ways such as PDO: http://php.net/manual/es/book.pdo.php – Alvaro Dec 14 '12 at 13:55
  • 4
    You _should not implement_ `mysql_escape_string()`! It is long-since deprecated in favor of [`mysql_real_escape_string()`](http://php.net/manual/en/function.mysql-real-escape-string.php), which will someday be deprecated in PHP 5.5 as well. – Michael Berkowski Dec 14 '12 at 13:57
  • any good online tutorial of putting data in an DB with PDO or mysqli? – Dylan Westra Dec 14 '12 at 14:06

1 Answers1

5

The point of escaping is to stop characters with special meaning (e.g. ') from having that special meaning. Since you are escaping the fragment of SQL containing all your quoted values, you are escaping the quotes and stopping them from quoting the values.

You need to escape each value before quoting it.:

$values = $values.'\''.$_POST[$r].'\', ';
                     //^^^^^^^^^^ Escape this 

However:

Don't use mysql_escape_string it is broken has been replaced with mysql_real_escape_string, but don't even use that, don't use mysql_* at all, it is deprecated.

Pick a modern replacement and use prepared statements and bound arguments instead of escaping strings and mushing them together into SQL via string concatination.

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