1

How to correct syntax error when inserting into a table?

"Insert Into " . $tableName . " (location_address) Values ('$location_address')"

In this code, when the value of the variable has French characters, such as ', give an error, I cannot fix it.

Message: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Université, Quebec City, QC, Canada')' at line 1, query was: Insert Into addresses_store_location (location_address) Values ('Université Laval, Pavillon Alphonse-Desjardins, Rue de l'Université, Quebec City, QC, Canada')

Who can help me? thanks

Robinio
  • 131
  • 9
  • The error is due to the single quote in the `l'Université`, you need to escape the char `'` to `\'` as to fix the issue. Please refer this [answer](https://stackoverflow.com/a/9596819/2451726) – Arulkumar May 22 '19 at 15:03
  • Use a prepared statement and bind your values, and you won't have this issue. – Qirel May 22 '19 at 15:06
  • 1
    Possible duplicate of [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Qirel May 22 '19 at 15:07

2 Answers2

2

Before insert your variable in query you should escape quotes:

$location_address = addslashes($location_address);

You will get the following string:

l\'Université

Sergei Kuraksin
  • 772
  • 9
  • 10
  • Why not use a prepared statement instead? That would be better... This is not really a good solution to the problem! – Qirel May 22 '19 at 15:22
  • I agree with @Qirel. This is not a good solution. Use prepared statement with bind variables. Read more: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Kamal Nayan May 22 '19 at 15:25
0

Your error is due to your single quote at l'université you can escape it with \'

Hope this can help

Gustin Tang
  • 85
  • 1
  • 1
  • 12