Proper mySQL command for adding URLs - php

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.

Related

codeigniter query binding and escate_str not sufficient

I'm developing an web app with codeigniter and I am struggling with escape issues..
I send my parameter(json with lots of text) like
$this->Upload_model->upload(array($this->db->escape_str($myjson),$this->db->escape_str($myjson1),$this->db->escape_str($myjson2)));
and in upload, I use querybindings like
$query = $this->db->query("insert into qwerty (_title, _desid, _short,_options, _status, _current) values (?,".$did.",?,?,1,0)", $datain);
but these techniques do not seem to properly escape single quotes
querybindings actually do nothing to the sql queries and escape_str adds // infront of 's but they do not seem to work.
it seems that this is because of json+mysql but I cannot come up with my own solution
can anyone help me out
//error log : theres a single quote in front of that t in the lorem ipsum
Error Number: 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 't look even slightly believable. If you are going to use a passage of Lorem Ipsu' at line 1
The benefit of using binds is that the values are automatically escaped, producing safer queries. You don’t have to remember to manually escape data; the engine does it automatically for you.
So don't need to escaping queries input.
Refer https://www.codeigniter.com/userguide3/database/queries.html#query-bindings

Mysql Syntax Error (I cant find what the error is!)

I have the following mysql query:
REPLACE INTO application (export_date,application_id,title,recommended_age,artist_name,seller_name,company_url,support_url) VALUES (1362564068339,564783832,Eyelashes,4+,Char Room,Char Room,http://,http://ios.charroom.net/,http://itunes.apple.com/app/)
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 'Char Room,Char Room,http://,http://ios.charroom.net/,http://itunes.apple.com/app' at line 1
I cant seem to see where the error is. Can someone help me out?
You must know that the above is an echo of the actual query. All the parameters in this query went through mysql_real_escape_string before being to the query.
Well, firstly you shouldn't be using mysql_real_escape_string:
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
Secondly, you still need to put the quotes around the strings. mysql_real_escape_string will escape quotes within the string, but it doesn't add the quotes to the start and end.
You have to put quotes around data you are inserting in your database.

I have a SQL Syntax error on my php page

Here is the mysql insert the I am running in php. I have removed the part giving the error but then I get a error on the next piece. I am not seeing what is diffrent to cause the error.
$fields="adv_exchange SET synum='".$synum."', worknum='".$_POST['worknum']."', user_id='".$current_user->ID."', f_name='".$current_user->user_firstname."', l_name='".$current_user->user_lastname."', email='".$current_user->user_email."', regnum=".$_POST['regnum'].", item='".$item."', qsver='".$_POST['qsver']."', flashrom='".$_POST['flashrom']."',expansion='".$_POST['board']."', rdisplay='". $_POST['rdisplay']."', screen_model='".$_POST['screen_model']."', p_hardware='".$_POST['cable']."', pcolor='".$_POST['pcolor']."', pname='".$_POST['pname']."', kboard='".$_POST['kboard']."', ip='".$_POST['ip']."', reg_name='".$_POST['reg_name']."', mem=".$_POST['mem'].", dt_server='".$_POST['dt_server']."', alert='".$_POST['alert']."', ows='".$_POST['ows']."', w_date='".$_POST['w_date']."', flashromver='".$_POST['flashromver']."', s_size='".$_POST['s_size']."', mag='".$_POST['mag']."', rcard='".$_POST['rcard']."', kvsid=".$_POST['kvsid'].", finger='".$_POST['finger']."', stand_alone='".$_POST['stand_alone']."', standards='".$_POST['standards']."', profile='".$_POST['profile']."', man_date='".$_POST['man_date']."', l_sn='".$_POST['l_sn']."', misc='".$_POST['misc']."', problem='".$_POST['problem']."'";
then $query = "insert into $fields";
I receive back
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 ' item='JS900CV', qsver='', flashrom='',expansion='', rdisplay='', screen_model='' at line 1
Blockquote
if I echo the $query I get this:
insert into adv_exchange SET synum='SY5135', worknum='123456', user_id='2', f_name='REMOVED', l_name='REMOVED', email='REMOVED', regnum=, item='JS900CV', qsver='', flashrom='',expansion='', rdisplay='', screen_model='', p_hardware='', pcolor='', pname='', kboard='', ip='192.168.1.16', reg_name='', mem=, dt_server='', alert='', ows='', w_date='', flashromver='', s_size='', mag='', rcard='', kvsid=3, finger='', stand_alone='', standards='', profile='', man_date='', l_sn='', misc='misc test\r\n', problem='gen test'
Depending on what I enter in the error is changing spots in my statement. Not all fields are used the form is dynamic that is supplying the data so the fields are dependent on what options are selected. On a side note in case of concern about using $_POST to insert directly into mysql, I sanitize the array first. Any help would be greatly appreciated.
Look at regnum=,. You don't provide a value for regnum. Either leave it out entirely or set it to an appropriate value.
You're using a very, very bad approach to MySQL databases: manually creating the queries. You should really use prepared statements instead: this issue will be resolved as well.
Don't use mysql_* functions, use PDO instead.
Your code would look like this (simplified):
// This holds the query
$statement = $pdo->prepare('INSERT INTO adv_exchange SET synum=?, worknum=?, etc=?, problem=?');
// This executes it with the given arguments. It's 100% injection-proof and safe. In fact, it's also faster.
$statement->execute(array($synum, $_POST['worknum'], $_POST['therest'], $_POST['problem']));
regnum=".$_POST['regnum']." is causing the problem. When it is undefined, you get regnum=, in the SQL query
A bigger concern is that you are not escaping your inputs. Either use mysql_real_escape_string around them, or better, use prepared statements.
You need to SET regnum=SOMETHING.
Currently it's empty.

mysql_real_escape_string not good enough?

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

What characters ARE allowed when querying a mysql database?

I have a textarea in a form, when I enter special characters in it, I get an error in mysql. (when submitting the form to a php-file which does the work of inserting into mysql)
I need to know exactly what characters that aren't allowed, or easier would be, exactly what characters thar ARE allowed, so that I could validate the textarea before submitting.
Does anybody know?
I have tried mysql_real_escape_string() but didn't help...
NOTE: In the textarea, users are supposed to enter some special chars like these:
+ , . ; : - _ space & % ! ? = # * ½ # / \ [ ] ' " < > £ $ €
Probably got them all...
how can I do this?
Thanks
UDPATE
My mysql_query :
mysql_query("INSERT INTO cars_db (description) VALUES ('$ad_text')");
UPDATE
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 'a"a!a?aa+a-a_a
a/a\a[a]a}a{a&a%a#a#a¨a^a*a*aa,a.a:a;a|a½a
§a' at line 1
A database column can technically hold any of those characters. The problem is that you are not escaping them properly in your query.
One way way to do this using mysql_real_escape_string is as follows:
$sql=sprintf("insert into cars_db (description) values ('%s')",
mysql_real_escape_string($_POST['description']) );
//execute query and show errors that result...
$result = mysql_query($sql);
if (!$result) {
die("Oops:<br>$sql<br>".mysql_error());
}
Another way is to use a library like PDO or ADODb which makes it easier to use prepared statements with placeholders. Such libraries ensure that data injected into queries is properly escaped.
This is good practice not only because it solves your problem, but it also improves the security of your code, since it becomes harder to perform SQL injection attacks.
Another way would be to use prepared statements. This makes sure SQL injection isn't possible.
Instead of escaping characters so as not to trip up your query, why not create a stored procedure with an incoming String parameter. Just pass the form variable's value (or save it to a string) and pass that to the stored procedure.
Do this:
$ad_text = mysql_real_escape_string($ad_text);
mysql_query("INSERT INTO cars_db (description) VALUES ('$ad_text')");
Read up on mysql_real_escape_string and SQL injection. This is a massive security hole in your application.
http://us.php.net/mysql_real_escape_string

Categories