I'm working on an existing website trying to prevent SQL injections. Before $_GET['ID'] was unsanitized.
$ID=mysql_real_escape_string($_GET['ID']);
$sQuery=mysql_query("select * from tbl_mini_website as s1, tbl_actor_merchant as me where s1.MERCHANT_ID=$ID AND s1.MERCHANT_ID=me.MERCHANT_ID");
If I put a ' at the end of the url, with mysql_real_escape_string() I get this from mysql_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 '\\' AND s1.MERCHANT_ID=me.MERCHANT_ID' at line 1
with out mysql_real_escape_string() I get:
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 '\' AND s1.MERCHANT_ID=me.MERCHANT_ID' at line 1
I'm not sure whats up with it? Any help would be greatly appreciated.
If it is an id, numerical I assume, why don't you just cast it to an integer?
$ID = (int) $_GET['ID'];
The best advice I can give you is to check out PDO and use bound parameters.
mysql_real_escape_string escapes, but doesn't quote.
Try:
$sQuery=mysql_query("select * from tbl_mini_website as s1, tbl_actor_merchant as me where s1.MERCHANT_ID='$ID' AND s1.MERCHANT_ID=me.MERCHANT_ID");
More generally, I tend to wrap both of these in a function, like:
function quoteValue($value) {
return "'" . mysql_real_escape_string($value) . "'";
}
This is useful, because you may find down the line that you want more refined quoting behavior (especially when it comes to handling Unicode, control characters, etc.)
It's because you're not quoting the variable.
Here's your query given the following inputs
$_GET['ID'] = "1";
$ID=mysql_real_escape_string($_GET['ID']);
SELECT ... where s1.MERCHANT_ID=1 ...
$_GET['ID'] = "1'"
$ID=mysql_real_escape_string($_GET['ID']);
SELECT ... where s1.MERCHANT_ID=1\' ...
$_GET['ID'] = "1'"
SELECT ... where s1.MERCHANT_ID=1' ...
Phil Brown is right, but you shoul forget about old fashioned mysql_real_escape_string or mysql_connect() as they are very old and move to php`s PDO() where you cand use prepared statements, binds, fetch object any many many more functions.
I suggest read PDO documentation at http://php.net/manual/en/book.pdo.php if you want next generation dabatase manipulation and security from SQL Injection .
Related
I am trying to insert a ' symbol into my database and have the below code.
$actionurl =$_POST['actionurl'];
$newtitle = $_POST['newtitle'];
$newtitle = mysql_real_escape_string($newtitle);
$result2 = mysql_query("UPDATE links SET title='$newtitle' WHERE url='$actionurl'")
or die(mysql_error());
And I get this 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 's to start up a sample library (forum thread)'' at line 1
Why am I getting an error if I'm using mysql_real_escape_string on the $newtitle variable?
I suspect that it's actionurl that is causing the error, not $newtitle.
To debug this, echo or print the SQL statement to be executed.
You can do something like this:
$sql = "UPDATE links SET title='$newtitle' WHERE url='$actionurl'";
// for debugging, output contents of the $sql string
echo "SQL=" . $sql ;
mysql_query($sql) or die(mysql_error();
As others have already suggested, the mysql_ interface is deprecated. New development should use either mysqli or PDO. And use prepared statements with bind placeholders. It just seems nonsensical to be struggling with mysql_real_escape_string in 2016.
Are magic quotes on in your php.ini? If yes, disabling it should solve your issue. (It could be enabled by default)
I'm having a problem when trying to add a URL to a mySQL database.
The string is a URL:
http://pbs.twimg.com/profile_images/1708867059/405000_10150426314376065_707061064_8645107_703731598_n_normal.jpg
The error I get is:
Error description: 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 '://pbs.twimg.com/profile_images/1708867059/405000_10150426314376065_707061064_86' at line 1
It seems as though it won't allow me to add a URL, I presume there is something wrong with some of the characters but I don't know what?
My SQL is:
INSERT INTO accounts (name,consumerkey,consumersecret,pic_url) VALUES ($twitterID,$consumerkey,$consumersecret,$picture_url)"
You cannot truly solve this kind of problem by adding a few characters (like ' or ") to your bespoke sql string!
Instead, get to know the real way to write sql in php (it's like a very badly kept secret), which is to use PDO statements. This will allow you to use placehoders like (:twitterID, :consumerKey, :consumerSecret, :pictureUrl) which will accept complex variables such as urls and any of the crap users send in much more gracefully.
In the long run, this will save you a lot of trouble and time.
You need to quote string values and any other character that SQL will complain about, in this case it's the colon; see further down below.
($twitterID,$consumerkey,$consumersecret,'$picture_url')
or
('".$twitterID."','".$consumerkey."','".$consumersecret."','".$picture_url."')
if you wish to quote all the values.
Sidenote: You can remove the quotes around the variables that are integers.
I.e.:
This based on, and without seeing how the rest of your code looks like:
$picture_url = "http://pbs.twimg.com/profile_images/1708867059/405000_10150426314376065_707061064_8645107_703731598_n_normal.jpg";
The error states that it is near : - near being just that, the colon.
...right syntax to use near '://pbs.twimg.com
^ right there
You can also use:
VALUES ($twitterID, $consumerkey, $consumersecret, '" .$dbcon->real_escape_string($picture_url) . "')";
$dbcon is an example of a DB connection variable and based on mysqli_ syntax.
Something you haven't stated as to which MySQL API you are using.
Plus, your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements.
Why do I get an error when I add ' to the end of a URL? For example : http://mywebsite.com/singel?id=24'
I get 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 '\' LIMIT 1' at line 1
This is shown everywhere if I put ' after any id in the query string.
What is wrong, and how it can be fixed?
Thank you.
You are inserting a non-escaped variable in an SQL query. And if this variable happens to contain SQL special chars, this can cause SQL syntax errors or worse.
You need to escape your variables before inserting them in your SQL queries.
Example:
$query = "SELECT * FROM users WHERE id = " . mysql_real_escape_string($id);
Instead of (this is WRONG, don't do this):
$query = "SELECT * FROM users WHERE id = $id LIMIT 1";
If $id is 24', the query becomes:
$query = "SELECT * FROM users WHERE id = 24' LIMIT 1";
As you can see, there is a ' after 24, which is a syntax error.
if a ' kills your query, you very obviously have an sql injection vulnerability. Read up on mysql_real_escape_string(), bobby-tables, and consider switching to PDO prepared statements.
Look here
http://www.codeproject.com/KB/database/SqlInjectionAttacks.aspx
You should learn something about SQL injection. Your Script is injectable now
This error usually means you are open to sql injections. This function is a bit more complicated than mysql_real_escape_string(), because it also does a PHP configuration test, to make sure you do not escape the data twice and to add Various PHP version support! (as per PHP Manual 1)
Just run this little nifty function on each of the submitted items, for inserts, updates or where statements:
function sql_injection($value){
$value = trim($value);
if(get_magic_quotes_gpc())
$value = stripslashes($value);
if(function_exists("mysql_real_escape_string")){
$value = mysql_real_escape_string($value);
}else
$value = addslashes($value);
return $value;
}
Ex:
$q = 'SELECT `blah` FROM `users` WHERE `id`='.sql_injection($_POST['id']);
This function does NOT replace server side validation, and everything should be validated before using it, always assume the worst :)
So using %27 you can just SQL inject even though data is sanitized with mysql_real_escape_string
%27) SQL INJECTION HERE %2F*
What to do?
Edit with example:
$sql = sprintf("SELECT *, MATCH(post) AGAINST ('%s*' IN BOOLEAN MODE) AS score FROM Posts WHERE MATCH(post) AGAINST('%s*' IN BOOLEAN MODE)",
mysql_real_escape_string($_GET['searchterm']),
mysql_real_escape_string($_GET['searchterm']));
$results = $db->queryAsArray($sql);
If you pass in %27) SQL INJECTION HERE %2F* to the searchterm querystring, I get outputted on the page:
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 'BOOLEAN
MODE)' at line 1
Thanks everyone for finding the problem in the db class..
Reasoning from the method name queryAsArray, it seems that you’re using this DbBase class from the comments of the MySQL functions manual page. If so, it’s the query method that removes the escape character from the escaped quotation marks:
function query($sql, &$records = null){
$sql = str_replace(array('\\"', "\\'"), array('"', "'"), $sql);
// …
}
Then it’s not a miracle that your example works (I simplified it):
$input = "', BAD SQL INJECTION --";
$sql = "SELECT '".mysql_real_escape_string($input)."'";
var_dump($sql); // string(33) "SELECT '\', BAD SQL INJECTION --'"
// everything’s OK ↑
$sql = str_replace(array('\\"', "\\'"), array('"', "'"), $sql);
var_dump($sql); // string(32) "SELECT '', BAD SQL INJECTION --'"
// Oops! ↑
The note mentioned in our manual has been marked for deletion. Once it propagates across all of the mirrors in our network, it will no longer appear attached to the official documentation.
~ Daniel P. Brown
Network Infrastructure Manager
http://php.net/
It's best to not to build statements like this at all, and instead use queries with parameters using mysqli or PDO. This will deal with the problem of MySQL injection and one day (not yet, unfortunately) it will perform better too, because the queries are cached without parameters, meaning you only got one query in the cache instead of dozens of different queries because of a single input value changing all the time. Other databases make use of this since long, but MySQL just managed not to make parameterized queries slower since the latest version.
It doesn't look plausible that %27 will actually terminate the string. It seems more like a possibility to embed quotes inside a string, but I'm not sure.
To be sure, I decided to sacrificed my server and test this. When I enter %27 in an input field and textarea that are escaped using mysql_real_escape_string and are then inserted in the database, I get no errors. The text %27 is just inserted. So no problem at all.
You are wrong. No injection possible here.
By following these three simple rules
Client's encoding properly set by mysql_set_charset()
Data being escaped using mysql_real_escape_string()
And enclosed in quotes
you can be sure that no injection possible
I storing articles in database that contains special characters like ", ', etc. but it gives error while saving in MySQL:
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 's and Moral Science's books in school. I clearly remember the picture of a Hindu' at line 1
mysql_real_escape_string everything you put into a query. Always. No exceptions.
Alternatively, use prepared statements.
use mysql_real_escape_string