tags:

views:

44

answers:

3

I dont know where my error is in this mysql query

$sql = "INSERT INTO `events` ( `owner` ,  `title` ,  `tagline` ,  `location` ,  `street` ,  `citytown` ,  `startdate` ,  `enddate` ,  `active`  ) VALUES(  '{$username}' ,  '{$data[title]}' ,  '{$data['tagline']}' ,  '{$data['location']}' ,  '{$data['street']}' ,  '{$data['citytown']}' ,  '{$data['startdate']}' ,  '{$data['enddate']}' ,  '{$data['active']}'  ) "; 
mysql_query($sql) or die(mysql_error());

It tells my i have an error in the syntax near... and then outputs part of my data where i have apostrophes

(example: title = Dave's Party)

+2  A: 

You want to escape single quotes in your strings before you insert them into the database.

You'll probably want to use mysql_real_escape_string on each element of your $data array.

For example:

$escaped_data = array();

foreach ($data as $key => $val) {
    $escaped_data[$key] = mysql_real_escape_string($val);
}

$sql = "INSERT INTO `events` ( `owner` ,  `title` ,  `tagline` ,  `location` ,  `street` ,  `citytown` ,  `startdate` ,  `enddate` ,  `active`  ) VALUES(  '{$username}' ,  '{$escaped_data[title]}' ,  '{$escaped_data['tagline']}' ,  '{$escaped_data['location']}' ,  '{$escaped_data['street']}' ,  '{$escaped_data['citytown']}' ,  '{$escaped_data['startdate']}' ,  '{$escaped_data['enddate']}' ,  '{$escaped_data['active']}'  ) "; 
mysql_query($sql) or die(mysql_error());

As an aside, take a look at the PHP documentation for SQL injection.

Dominic Rodger
+1  A: 

Be sure that you have all values properly escaped.

mysql_real_escape_string

Keiji
+1  A: 
mysql_escape_string($data['title']);

or

mysql_real_escape_string($data['title'], $dbconn);
Trevor