0

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)

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Be sure that you have all values properly escaped.

mysql_real_escape_string

Comments

1
mysql_escape_string($data['title']);

or

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.