I have to insert some strings to MySQL database. The problem is that every time I use " ` " or " ' " it causes errors in the QSqlquery execution. How can I prevent this?
Asked
Active
Viewed 2,178 times
0
-
definitely you need to read about SQL injection. mavroprovato gave you a perfect answer. – Marek R Sep 27 '13 at 08:50
4 Answers
4
Always use bind variables when running your query and you will never have problems with special characters in SQL queries. Here is an example from the documentation:
QSqlQuery query;
query.prepare("INSERT INTO person (id, forename, surname) "
"VALUES (:id, :forename, :surname)");
query.bindValue(":id", 1001);
query.bindValue(":forename", "Bart");
query.bindValue(":surname", "Simpson");
query.exec();

mavroprovato
- 8,023
- 5
- 37
- 52
0
` and ' are comment in SQL, you have to "protect" them with a backslash \ like so
Select bla
From blo
where name = "some \`test\`"

Thomas Ayoub
- 29,063
- 15
- 95
- 142
-
-
@TimZaman you're right but my english was quite bad, feel free to edit the post :) – Thomas Ayoub Nov 06 '14 at 19:41
0
You should add escape sequence to add such type of special characters like '
, `
, \
, "
Please add them by adding \
before them.
e.g.
For '
use \'
For "
use \"
For \
use \\
For `
use \`

Parixit
- 3,829
- 3
- 37
- 61
-2
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
in php, You can use mysql_real_escape_string function: http://php.net/manual/en/function.mysql-real-escape-string.php
Hope will help you!

Trieu SQRT
- 9
- 2