views:

77

answers:

3

I have an SQL file I created from a CSV file. It includes the names of all metropolitan areas in the United States, along with some statistics about their populations. I wrote a PHP script that takes the population data, turns it into a chart, and sticks it back in the city's row, in a different column. This script ran fine until it came to Coeur d'Alene, Idaho. I assume it's because of the apostrophe (single quote) in the city's name. Here's the code:

$query = "UPDATE population SET `$columnname`='$chart_url' WHERE name = '$cityname'";
            mysql_query($query) or die;

So it's finding the row by matching it up with the city's name. There isn't any other way to do this, because of the data. Is there a way to deal with data that already has unescaped characters in the SQL file?

+5  A: 
$escapedCityname = mysql_real_escape_string($cityname);

Escape your data! And if you can, use binding.

erenon
Correct. But this should really be: Use Binding. If you can't, try harder. If you really, *really* can't, grudgingly escape, and remember to switch to binding as soon as possible.
sleske
+2  A: 

Your data can have apostrophes - but you need to escape in your code:

// You should not use url values directly! The can be hijacked...
// You should write a safe solution here
$column_name = $chart_url;

// Replace cityname with escaped city name
$cityname = mysql_real_escape_string($cityname)
$query = "UPDATE population SET `$columnname`='$column_name' WHERE name = '$cityname'";
            mysql_query($query) or die;

Why do you use a dynamic columnname: $columnname?

Andreas Rehm
Thanks for the help on escaping characters before they go in, but my question was more about what to do with unescaped characters already in there. Should I just go through my cities and manually add the \ character before apostrophes? There are only a few, I suppose.
Dave
As I said - your data can have apostrophes. You don't need to escape them. You need to escape it in your code - otherwise the code will not run. And as I said - please di not use parameters from get/post or request url without checking them - or use pdo (there is a sql injection filter).
Andreas Rehm
+5  A: 

Use PDO with named parameters. It makes your code more maintainable, secure, faster and escapes your data by avoiding the dangers of string concatenation.

mysql_* functions are antiquated. If you must use those functions, then espace your data with mysql_real_escape_string.

webbiedave
Using PDO is a good idea!
Andreas Rehm