Escaping quotes while inserting JSON into MySQL table [duplicate] - php

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 4 years ago.
i have this JSON string, which i want to insert into table. Here is my insert query:
$insert_sql = 'INSERT INTO yun_postmeta (post_id, meta_key, meta_value)
VALUES (5054, "_wc_free_gift_coupon_free_shipping", "a:1:{i:6;a:3:{s:10:"product_id";i:6;s:12:"variation_id";i:0;s:8:"quantity";i:1;}}");';
Of course, the query breaks because of the quotes ("). When i add backslash () in front of them, to escape, the query works and string gets inserted into the table, but for some reason my system doesn't work properly.
However, if i copy the JSON string and insert it manually into table, using phpmyadmin, system works normally.
Any idea what could be the problem here?
This sounds like encoding problem, but i don't have a clue what to do to solve it.
Thank you!

The SQL query should only use single quotes around values ie:
VALUES (5054, '_wc_free_gift_coupon_free_shipping', ...
So in PHP the string should be defined in double quotes to limit the amount of escaping you do as well as allowing variables to be added:
$insert_sql = "INSERT INTO yun_postmeta (post_id, meta_key, meta_value)
VALUES (5054, '_wc_free_gift_coupon_free_shipping', ... )";
As far as your values you should use mysqli_real_escape_string to handle escaping the double quotes:
http://php.net/manual/en/mysqli.real-escape-string.php
$escaped_json = mysqli_real_escape_string($con, 'a:1:{i:6;a:3:{s:10:"product_id";i:6;s:12:"variation_id";i:0;s:8:"quantity";i:1;}}');
$insert_sql = "INSERT INTO ... VALUES ( 5054, '_wc_free_gift_coupon_free_shipping', $escaped_json ...

Related

How to escape php mysqli query? [duplicate]

This question already has answers here:
Escaping single quote in PHP when inserting into MySQL [duplicate]
(8 answers)
Closed 7 years ago.
I am passing data from AJAX to my PHP. I just run a for loop to make my query. Problem with my data is that it contains single quote.
I am using single quote to enclose my parameters in the query. Query is something like
INSERT INTO myTable (column1.column2) VALUES('value1', 'value2'),
('value'1', 'value2');
I want to escape like
INSERT INTO myTable (column1.column2) VALUES('value1', 'value2'),
('value\'1', 'value2');
I just tried mysqli_real_Escape_String. It returns something like
INSERT INTO myTable (column1.column2) VALUES(\'value1\', \'value2\'),
(\'value\'1\', \'value2\');
So Query execution fails.
I don't think using htmlspeciachars is the right way for this.
Any suggestions?
You should definitely be using prepared statements. They're not that tricky.
However, if you're not going to make that jump then you just need to use mysqli_real_escape_string properly.
From the result you got, I'm guessing you wrapped the whole query in the mysqli_real_escape_string function. However you should just wrap the value in it.
i.e.
"INSERT INTO myTable (column1, column2) VALUES('value1', 'value2'),
('" . mysql_real_escape_string("value'1") . "', 'value2')";
Thats a pretty contrived way of doing things. But the idea is: only wrap the value in mysqli_real_escape_string().

SQL Insert doesn't work for some reason [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
When I remove '$user' and by this works perfectly
$query = $db -> query("INSERT INTO posts (title, body, tags, published, date, by) VALUES
('$title', '$body', '$tags', '$published', '$date', '$user')");
User is varchar(11)
when I print_r $user I get the value I want
I am not sure what is going on, by is at the end of the table.
Sorry if this question is stupid.
peace
Because BY is a Reserved keyword and happens to be the name of the column. In order to avoid syntax error, you need to escape it using backtick,
INSERT INTO posts (title, body, tags, published, date, `by`) VALUES (...)
MySQL Reserved Keywords List
I rather change the column name to avoid problem from getting back again :D
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
And addition, you can also put a backtick on the "date" column since it is also a reserved word..
INSERT INTO posts (title, body, tags, published, `date`, `by`) VALUES (...)
Well in my case I really don't prefer using backtick but it's really helpful in avoiding syntax errors..

How to ignore or detect a symbol in a variable?

I have a query that looks at a list of files inside a folder and enters the names of everything into a database so I can control the sort when showing the images.
Now I had an image today which had a name of image123('2).jpg. The single quote caused my query from crashing so how can I get around this? To make things simpler I have made example scenario
I have list of 4 variables which have the following strings
$myVAR1 -- "MyName IS Leo";
$myVAR2 -- "MyName IS 'Tiger";
I am running a SQL query to enter them into a database
$sql = "INSERT INTO `names` (`StringID`, `StringValue`) VALUES (NULL, ' $myVAR1');";
$sql2 = "INSERT INTO `names` (`StringID`, `StringValue`) VALUES (NULL, ' $myVAR2');";
So how can I detect that the single quote is inside the string $myVar2 and how can I ignore it when entrying into the database?
You need to escape your data. Use prepared queries with PDO so you don't have to worry about this.
You are currently wide open to SQL injection.
At a minimum, use mysql_real_escape_string(), assuming you are using the standard MySQL library in PHP. It takes care of quotes, among many other things, escaping them properly so they will be inserted into your database.

Insert ' and " into mysql using php [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Best way to stop SQL Injection in PHP
I am trying to insert ' sign and " in a mysql table using php. But the content has this two signs I get a mysql error.
$comment="I like '''' it so ""much"" Jaan";
mysql_query("INSERT INTO `comments` (`id` ,`name` ,`date` ,`comment`) VALUES ('', '$name', '$date', '$comment')");
above one is an example. Whenever an user insert ' or " in his comment the problem begins. I know about mysql_real_escape_string() but i dont want to use this. Bcz My comments are already filtered. Please tell me how I can Insert comment with those syntax. every suggestions are welcome.
Escape every string variable with mysql_real_escape_string().

What is the problem with this php script? [duplicate]

This question already has answers here:
How can I write SQL for a table that shares the same name as a protected keyword in MySql? [duplicate]
(3 answers)
Closed 9 years ago.
I keep getting error 1064 in this line:
$sqlquery = "INSERT INTO user
(username, password, email, key)
VALUES
('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."','".$activation."')";`
key is a reserved word which you're using in your query, this must be escaped with backticks. Reserved word error is 1064.
You should also consider learning some security theory particularly with regards to using unescaped values in a query (straight from a user).
The below code is both secure and fixed:
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
$sqlquery = "INSERT INTO `user` (`username`, `password`, `email`, `key`) VALUES ('{$username}','{$password}','{$email}','{$activation}')";
A simple rule when it comes to queries (well, anything) is to never trust user input. By using mysql_real_escape_string you're escaping the variables so that they're safe for insertion into the database. Without it, you could allow the user to run any query that they wanted to.
For future reference, here is a complete list of MySQL Reserved Words.
MySQL error 1064 generally means a SQL syntax error. Take a look at your SQL statement to make sure it's valid.
A good way to debug those kinds of errors is to print out the SQL, then try to execute it manually in MySQL.
Do you still get errors if you use this instead:
$query = sprintf("INSERT INTO user
(username, password, email, `key`)
VALUES
('%s','%s','%s','%s')",
mysql_real_escape_string($_POST["username"]),
mysql_real_escape_string($_POST["password"]),
mysql_real_escape_string($_POST["email"]),
mysql_real_escape_string($_POST["activation"]));
$result = mysql_query($query);
KEY is a MySQL reserved word -- it needs to be enclosed in backticks to escape its use in queries. Backticks are not necessary if not using reserved words...
Try surrounding each variable $var with mysql_real_escape_string(), such as
instead of $_POST["password"]
use mysql_real_escape_string($_POST["password"])!
Taking user-defined values directly from the HTTP Request and concatenating them into an SQL query is B-A-D, and likely the source of your syntax error. Make sure you escape all values.

Categories