I created a form to collect user data, including address and write them in a Mysql DB.
In the user table, Street is a Varchar (255).
Everything works fine, unless in the name street there's an apostrophe, in this case I have
the following SQL warning:
For example, if in the Street name I put "Francesco D'assisi 24"
Error: 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 'assisi 24',
Any idea how to avoid it?
Pass the variables via a stored procedure parameters.
Need to escape data: use function mysql_real_escape_string (or analogs in other libraries), or using PDO and parameters.
For example:
$data = <<<TXT
Francesco D'assisi 24
TXT;
$data = mysql_real_escape_string($data);
mysql_query("INSET INTO table VALUES ('$data')") or die mysql_error();
Related
I am new to MySQL and I am building a Flask project and using mysql.connector to query a MySQL Database. I know this question has been answered many times before but this is more specific to using MySQL with Flask.
I need to pass a query where I want to plug in the table name into the query, dynamically, depending on the value stored in the session variable in Flask. But the problem is, if I try to do:
Method 1:
cur.execute('SELECT * FROM %s;',(session['table_name'],))
the database throws an error stating that such a table is not found. However, the problem is mysql.connector keeps enclosing the table name with single quotes, hence the error.
Sample Error Statement:
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ''52_data'' at line 1
Here the table name should be 52_data and not '52_data'.
Only other workaround, I figured, is using:
Method 2:
cur.execute('SELECT * FROM '+session['table_name']+';')
which is working but it does not escape SQL Injection, I am guessing, since it's direct concatenation, unlike Method 1, where the cur.execute() function handles the escaping, as per this question.
The value being passed is stored in a sessions variable in Flask, which is not so secure, as per Miguel's Video. Hence, I want to escape that string, without triggering off an error.
Is it possible to implement Method 1 in a way that it does not add the quotes, or maybe escape the string using some function? Or maybe any other Python/Flask package that can handle this problem better?
Or if nothing works, is checking for SQL Injection manually using regex is a wiser option?
Thanks in advance.
Note: The package name for this mysql.connector is mysql-connector-python and not any other same sounding package.
For identifiers, you can use something like:
table_name = conn.converter.escape(session['table_name'])
cur.execute('SELECT * FROM `{}`'.format(table_name))
For values placeholders, you can use your Method 1, by using the parameters in the cur.execute() method. They will be escaped and quoted.
More details in https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
NOTE: You don't need to end the SQL statements with ;
I don't understand why is it saying 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 ''User_notifications'' on this query:
<?php
include 'constants.php';
$username=$_POST['username'];
$notiftable=$username.'_notifications';
$con=new mysqli('',databaseuser,databasepassword,database);
if($con)
{
$q="SHOW TABLES LIKE '$notiftable'";
Your table name User_notifications is getting double-escaped (i.e. it is being escaped twice). This is most likely happening because the PHP function is escaping it already, and you are doing it a second time. Try not escaping the table name yourself, i.e.:
$q = "SHOW TABLES LIKE $notiftable";
I'm trying to write sql to insert a SQL code into one of the table's columns.
The table has these three columns: email, verification code, sql.
I try this code, and variations of it, playing around with the quotes and backslashing/escaping them, etc... but something's still wrong:
INSERT INTO pre_registration(email, verification_code, sql) VALUES('myemail#gmail.com', '8efb100a295c0c690931222ff4467bb8', '"INSERT INTO customer(title) VALUES(\'Mr.\')"')
It tells me there's an error in the SQL syntax:
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 'sql) VALUES('myemail#gmail.com', '89f0fd5c927d466d6ec9a21b9ac34ffa', "INSER' at line 1
How to do it? I'm using PHP/MySQL.
MySQL considers sql as a keyword. You have to quote it:
INSERT INTO pre_registration(email, verification_code, `sql`) VALUES('myemail#gmail.com', '8efb100a295c0c690931222ff4467bb8', '"INSERT INTO customer(title) VALUES(\'Mr.\')"')
By the way double the quotes to escape them instead of using bakslashes. This is more SQL friendly.
INSERT INTO pre_registration(email, verification_code, `sql`) VALUES('myemail#gmail.com', '8efb100a295c0c690931222ff4467bb8', '"INSERT INTO customer(title) VALUES(''Mr.'')"')
Some insight into the exact SQL error would help. At first glance I'd say you need to apply spaces between the table name and the open parentheses and between values and the open parentheses.
Also, the Single quotes around the double quotes for the SQL portion may be creating an error though I am not certain. Whatever is between the single quotes is interpreted literally which should make the escape characters actually be slashes inside the stored data.
Also, sql is a reserved word that must be quoted for use.
Finally, depending on your situation there may be a more secure method of data entry using prepare and bound parameters:
try
{
$conn = new PDO ( "sqlsrv:server = $serverstringname; Database = $logindatabase", "$loginusername", "$loginpassword");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch ( PDOException $e )
{
print( "Error connecting to SQL Server." );
die(print_r($e));
}
$email = 'myemail#gmail.com' //or some other way of setting the variable like $_POST
$verification_code = '#####' //or $_Post method
$sql = 'Put Query Here' //probably have to declare this explicitly
$sql_insert = "INSERT INTO pre_registration_info (email, verification_code, 'sql') VALUES (?,?,?)";
$stmt = $conn->prepare($sql_insert);
$stmt->bindValue(1, $email);
$stmt->bindValue(2, $verification_code);
$stmt->bindValue(3, $sql);
$stmt->execute();
This precise code was working before on my old machine, but I'm getting this error spat back at me (on Mac OSX 10.7).
The C code is:
printf("%s\n",query);
if (mysql_query(conn,query)){
fprintf(stderr, "%s\n", mysql_error(conn));
}
The output is:
INSERT INTO comment (unum,cat_subject,cat_major,cat_minor,unmod)
VALUES (1,1,1,0,'The cat was lazy.')
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 ','The cat was lazy.')' at line 1
The original printf statements creates two lines of text, but I've wrapped them for readability.
It all looks fine to me! The following works in PHP for the same table (with the correct bindParam statements):
$STH=$DBH->prepare("INSERT INTO comment (unum,cat_subject,cat_major,cat_minor,unmod) VALUES (:u,:s,:ma,:mi,:t)");
What's wrong?
(BTW: I tried it with " instead of ' but that made no difference.)
(Upgrading to an answer)
It appears that you may have non-printable characters in query, probably after the 0 character. Try hexdumping the string's bytes to see if anything is suspicious:
char* c;
for (c=query; *c; c++) printf("%02x",*c);
Should you be concatenating into your SQL the unknown contents of variables, I'd strongly recommend using MySQL's prepared statement API to pass your variables to MySQL as parameters in order to avoid SQL injection; this will also perform basic type-conversion of such parameters to the destination column types - if you need more control over the cleansing of your variables, you will need to perform such in your application prior to passing the parameters to MySQL.
I am using EDMX with MySql 5.1. It is working fine except When I try to execute the lambda expression, it shows me the following error :-
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 '[XYZ].[UserID] AS [UserID], [XYZ].[FirstName] A' at line 17
where [XYZ] is the table name and [UserID], [FirstName] are the columns of that table. Following is the statement, that I want to execute -
_context.XYZSet.Where(org => org.ACDID == sbuID || !(org.ACDID.HasValue)).ToList();
Please help..
I do not know anything about EDMX, but from that error it looks like it's using MS SQL Server syntax to escape table and column names, which is not supported by MySQL. MySQL uses backticks for that, not square brackets.
If you could get EDMX to stop escaping the table and columns names then you might be okay, assuming none of the table/column names are reserved words.