How would you enter special characters into MySQL from PHP? - php

Effectively, what I am attempting to do is enter a string similar to this string
into MySQL (it's one line, made into two for readability)
fill:#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;
stroke-linecap:butt;stroke- linejoin:miter;stroke-opacity:1
MySQL allows me to INSERT the string into the field using phpMyAdmin and phpMyAdmin adds the field as (again one line, made into two for readability):
('fill:#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-
linecap:butt;stroke-linejoin:miter;stroke-opacity:1'' in ''field list')
With my PHP code I attempted to add the in field list part to my code as follows
$rectangle_array[$rstyle] = $rectangle_array[$rstyle] . "' in ''field list'";
$mysql_rectangle_table_entry = "INSERT INTO $mysql_table VALUES
($rectangle_array[$rstyle], 'rect',
$rectangle_array[$rid], $rectangle_array[$rwidth],
$rectangle_array[$rheight], $rectangle_array[$rx],
$rectangle_array[$ry])";
$run = mysql_query($mysql_rectangle_table_entry) or die(mysql_error());
And upon running the code I receive 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 ':#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;s' at line 1
What can I do to make this work?

As noted in the comments…
You could use mysql_real_escape_string() to escape any MySQL special characters before insertion.
For example:
$sql = "INSERT INTO my_table (string_column) VALUES ('" . mysql_real_escape_string($string) . "')";
Another option is to use Prepared Statements with PHP's MySQLi or PDO.

You might want to have a look either at prepared statements or mysql_real_escape_string to escape special characters that might break your INSERT.

Related

MYSQL, PHP: Insert records from one database to another

I have a necessity to insert some record from one table1 in database1 to another table2 in database2.
So far I have this..
$records_r = mysqli_fetch_assoc(mysqli_query($conn_r, "SELECT * FROM `export` WHERE ID < 100"));
$columns_r = implode(",",array_keys($records_r));
$values_r = implode(",",array_values($records_r));
$import = mysqli_query($conn_i,"INSERT INTO NOTimport ($columns_r) values ($values_r)");
if (!$import) {
printf("Error: %s\n", mysqli_error($conn_i));
exit();}
It gives me the error:
Error: You have an error in your SQL syntax;
This is how the syntax looks:
INSERT INTO `NOTimport` ('xx,xx,xx,xx,xx,xx,xx,xx') values ('11,'11,E,2079,1931,xx,xx,x')
I am 99% sure that single quotes are causing the error, but why are there?
As per your original post https://stackoverflow.com/revisions/31116693/1 and completely overwriting your original post without marking it as an edit:
You're using the MySQL import reserved word
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
It needs to be wrapped in ticks
INSERT INTO `import` ($columns_r) values ($values_r)
or rename that table to something other than a reserved word.
Plus, $values_r may require to be quoted and depending on what's being passed through $columns_r, you may need to use ticks around that.
I.e.:
INSERT INTO `import` (`$columns_r`) values ('".$values_r."')
Even then, that is open to SQL injection.
So, as per your edit with these values values ('11,'11,E,2079,1931,xx,xx,x'), just quote the values since you have some strings in there. MySQL will differentiate between those values.
Escape your values:
$values_r = implode(",",array_values($records_r));
$values_r = mysqli_real_escape_string($conn_r, $values_r);
or $conn_i I'm getting confused as to which variable is which here. Be consistent if you're using the same db.
Edit:
As stated in comments by chris85, use prepared statements and be done with it.
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
import is a reserved word in MYSQL. So, you need to use backticks (``) around it in your query.
So rewrite as follows:
$import = mysqli_query($conn_i,"INSERT INTO `import` ($columns_r) values ($values_r)");
Without Using PHP you can use MySql Query Which Will Perform Insert Operation As:-
$columns_r='`name`,`class`';
mysqli_query($conn_i,"INSERT INTO `import` ({$columns_r}) select {$columns_r} from `export`");

Proper mySQL command for adding URLs

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.

unable to insert record in database

my basic insert query is not working.. i know its a very basic, raw sort of question to ask but m unable to sort out
my code
$a="nvsdjkvn";
$b="bhjxcbncj";
mysql_select_db("vas1",$con);
$s = "insert into updates(update,dates) values ('$b','$a')";
$re = mysql_query($s);
i got 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 'update,dates) values ('nvsdjkvn','bhjxcbncj')' at line 1
my table name is: updates with two columns 'update' and 'dates' both of type 'varchar'
update is a reserved word in SQL and must therefore be enclosed in backticks if not used as a reserved word:
$s = "insert into updates(`update`,dates) values ('$b','$a')";
UPDATE is a reserved word in MySQL. To use in your query, you should properly escape it.
Here is a complete list of MySQL reserved words.
Change -
$s = "insert into updates(update,dates) values ('$b','$a')";
To
$s = "insert into updates(`update`,`dates`) values ('".$b."','".$a."')";
Mysql extension is deprecated as of PHP 5.5.0, and is not recommended
for writing new code as it will be removed in the future. Instead,
either the mysqli or PDO_MySQL extension should be used. See also the
MySQL API Overview for further help while choosing a MySQL API.
I'm afraid to say so but we are not allowed to name a table just like a keyword.
Please go through the rule set for naming conventions
http://www.isbe.state.il.us/ILDS/pdf/SQL_server_standards.pdf‎

MySql error while string is escaped already?

Why this:
$query = "SET NAMES 'utf8'";
$query = str_replace("'", "\'", $query);
$pdo->query($query);
Would cause problem?
I'm currently getting 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 '\'utf8\''
If I don't escape it, everything's fine, but the problem exists with further queries!
The sql you are trying to run is perfectly safe as is, it contains no user input and as such can be run without escaping.
Also you are actually escaping the delimiters of a string, not the value of the string itself.
You don't have to escape every single quote in a query, some are valid such as:
UPDATE table SET field='blah' WHERE id=10
Where field would be a varchar or similar. You would escape the quotes if they need to be part of the value of the field, such as:
UPDATE table SET field='This \'value\' uses quotes.' WHERE id=10
Hope that makes sense.

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