MySQL error when inserting data containing apostrophes (single quotes)? - php

When I an insert query contains a quote (e.g. Kellog's), it fails to insert a record.
ERROR MSG:
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','Corn Flakes 170g','$ 15.90','$ 15.90','$ 14.10','--')' at
line 1MySQL Update Error:
The first 's', should be Kellogg's.
Is there any solution?

Escape the quote with a backslash. Like 'Kellogg\'s'.
Here is your function, using mysql_real_escape_string:
function insert($database, $table, $data_array) {
// Connect to MySQL server and select database
$mysql_connect = connect_to_database();
mysql_select_db ($database, $mysql_connect);
// Create column and data values for SQL command
foreach ($data_array as $key => $value) {
$tmp_col[] = $key;
$tmp_dat[] = "'".mysql_real_escape_string($value)."'"; // <-- escape against SQL injections
}
$columns = join(',', $tmp_col);
$data = join(',', $tmp_dat);
// Create and execute SQL command
$sql = 'INSERT INTO '.$table.'('.$columns.')VALUES('. $data.')';
$result = mysql_query($sql, $mysql_connect);
// Report SQL error, if one occured, otherwise return result
if(!$result) {
echo 'MySQL Update Error: '.mysql_error($mysql_connect);
$result = '';
} else {
return $result;
}
}

Replace mysql with mysqli. Use this
mysqli_real_escape_string($connection,$_POST['Description'])

You should pass the variable or data inside mysql_real_escape_string(trim($val)), where $val is the data on which you are getting an error.
If you enter the text, i.e., "I love Kellog's", we have a ' in the string so it will break the query. To avoid it you need to store data in a variable like this $val = "I love Kellog's".
Now, this should work:
$goodval = mysql_real_escape_string(trim($val));

You can also use the addslashes() function which automatically puts \ before ' to avoid error

You need to escape the apostrophe (that is, tell SQL that the apostrophe is to be taken literally and not as the beginning or end of a string) using a \.
Add a \ before the apostrophe in Kellogg's, giving you Kellogg\'s.

In standard SQL, you use two single quotes to indicate one single quote, hence:
INSERT INTO SingleColumn(SingleChar) VALUES('''');
The first quote opens the string; the second and third are a single quote; and the fourth terminates the string. In MySQL, you may also be able to use a backslash instead:
INSERT INTO SingleColumn(SingleChar) VALUES('\'');
So, in your example, one or both of these should work:
INSERT INTO UnidentifiedTable
VALUES('Kellog''s', 'Corn Flakes 170g', '$ 15.90', '$ 15.90', '$ 14.10', '--');
INSERT INTO UnidentifiedTable
VALUES('Kellog\'s', 'Corn Flakes 170g', '$ 15.90', '$ 15.90', '$ 14.10', '--');
In PHP, there is a function to sanitize user data (mysql_real_escape_string) before you embed it into an SQL statement -- or you should use placeholders. Note that if you do not sanitize your data, you expose yourself to SQL Injection attacks.

User this one.
mysql_real_escape_string(trim($val));

Optimized for multiple versions of PHP
function mysql_prep($value){
$magic_quotes_active = get_magic_quotes_gpc();
$new_enough_php = function_exists("mysql_real_escape_string");//i.e PHP>=v4.3.0
if($new_enough_php){//php v4.3.o or higher
//undo any magic quote effects so mysql_real_escape_string( can do the work
if($magic_quotes_active){
$value = stripslashes($value);
}
$value = mysql_real_escape_string(trim($value));
}else{//before php v4.3.0
//if magic quotes arn't already on, add slashes
if(!$magic_quotes_active){
$value = addslashes($value);
//if magic quotes are already on, shashes already exists
}
}
return $value;
}
Now just use:
mysql_prep($_REQUEST['something'])

Escape it by using a helper function like:
function safeDBname($table_name)
{
$outputText=str_replace("'","",$outputText);
return strtolower($outputText);
}

i did it as below-
in my case description field contains apostrophe(').
and here is code:
$description=mysql_real_escape_string($description);
"insert into posts set name='".$name."', address='".$address."', dat='".$dt."', description='".$description."'";
it solved my problem

Related

MySQL UPDATE and INSERT both returning error message about bad syntax, but it is correct syntax when trying it on phpMyAdmin

I have a PHP program that will either INSERT a new row, or UPDATE the existing one if it's already there. When running on a browser, it returns errors.
But, the actual call runs OK on phpMySQL - no error reported and row is updated.
"Errormessage: 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 '"updated", `conditions` =" ",' at line 1.
Code to connect to mySQL and make the update or insert is very simple
require_once ('mysqli_connect.php');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error($dbcon);
exit ;
}
Then I make the actual body of the call, which produces variable $call containing this (example is for UPDATE):
UPDATE `deal` SET `deal_lotus_source` = "updated", `conditions` =" ", `termsnotes` = " ", `walkprovision` = " ", `sector` = "Application Software", `industry` = "Airconditioning", `tgt` = "Bcd", `acq` = "E", `dtstart` = "2015/03/08" , `dtclose` = "2015/03/23", `dtexdivtgt` = "2015/03/17", `dtexdivacq` = "2015/03/17", `dtexdivtgtexp` = "2015/03/17", `dtexdivacqexp` = "2015/03/17", `acq` = "E",`stat`= "Closed",`acqtype`= "Domestic",`dealtype`= "Acquisition of Private Company Cash-Stoc",`analyst`= "Fred Blogs",`tgttkr`= "ABC",`tgtx`= "C",`tgtprec`= "$",`tgtpret`= "1",`tgtshrout`= "2",`acqtkr`= "D",`acqx`= "F",`acqprec`= "$",`acqpret`= "3",`acqshrsout`= "4",`dlvalue`= "5",`eacls`= "Actual",`tgtlaw`= "",`acqlaw`= "",`tgtbank`= "",`acqbank`= "",`tgtshrsoutfd`= "6",`acqshrsoutfd`= "7",`tgtdebt`= "8",`acqdebt`= "8",`suppress`= "0",`pricingp`= "",`terminate`= " ",`divstattgt`= "",`divstatacq`= "",`divfreqtgt`= "Quarterly",`divfreqacq`= "Quarterly",`divcurrtgt`= "$",`divcurracq`= "$",`divamttgt`= "0.000",`divamtacq`= "0.000", `cos` = "", `mot` = "" WHERE deal_id =578
and the code to update (or insert) is
if (!mysqli_query($dbcon, $call)) {
printf("Errormessage: %s\n", mysqli_error($dbcon));
die;
}
Any ideas?
You have to use single quotes arround the values:
UPDATE `deal` SET `deal_lotus_source` = 'updated', `conditions` =' ', `termsnotes` = ' ', `walkprovision` = ' ', `sector` = 'Application Software', ...
Quotes in PHP can be confusing, because depending on which type of quote you use there are (different rules](http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm). The most important things (in this case) to keep in mind are these 2:
* If you have a variable ($var) inside double-quotes ("$var") then it will get substituted (your string will now contain value) whereas if it is in single-quotes ('$var') then it will NOT get substituted (it remains in your string as $var)
* If you are need single-quotes as part of your string then use double-quotes around the string. ("I don't like contractions and I can't bear to use them.") If you need double-quotes as part of your string then use single quotes to surround the string. ('He said, "Hello, Dear!" and she slapped him.')
You are using double quotes (note the values you want to compare conditions and termsnotes and etc. to) but you are going to want to change to single-quotes inside the string so you can surround the whole thing with double-quotes. This also has the advantage of allowing you to use variables inside it.
$call = "UPDATE `deal`
SET `deal_lotus_source` = 'updated',
`conditions` =' ',
`termsnotes` = ' ',
`walkprovision` = ' ',
...
`mot` = ''
WHERE deal_id =578";
Note that the only double-quotes in that whole line of code are the ones at the very beginning and ending of the string. If you want to put a double-quote inside the string then you would have to put a backslash in front of it.
One very important step when you are constructing a query in a string (especially if you are getting errors with it) is to actually look at it. Use echo "call=<pre>$call</pre><br />\n"; and then look very carefully at all your quotes and etc. You can actually copy/paste the results of this echo into phpMyAdmin and see if the actual query works in your sql tab - this is a great test.
In summary, quotes in PHP are very consistent and very powerful, but they do have the potential to change your string during the process of assigning the string to a variable. It's very important to verify that the string after assignment is the string that you expect.

Implode array & search for matches mysql php

I'm trying to take an array and implode it and than run it through a mysql query to search my database for matches. If there are matches, I wanna return the matching values. It keeps returning false and I'm not sure why. I did a vardump and can see the array is there, but doesn't seem to be getting passed to the mysql_query. If I manually put the array into the query it works no problem. Any ideas?
My Array (This comes from my Android App):
$refids = (jdu23764js84, 2746272jsjs7f, 39823874hbsjsk)
PHP script code:
public function searchList($refids) {
$refarray = array($refids);
$comma_separated = implode(',', $refarray);
$result = mysql_query("SELECT `ref_id` FROM `main` WHERE `ref_id` IN
({$comma_separated})");
if ($result == true){
$result = mysql_fetch_array($result);
return $result;
} else {
return false;
}
You've forgotten to quote the individual values inside your $refids, so you're building
... WHERE `ref_id` IN (jdu23764js84, 2746272jsjs7f, ...)
and MySQL is interpreting those as field names. In other words, you're suffering from an SQL injection attack vulnerability, and your utter lack of ANY error handling on the database code is preventing from seeing the errors mysql is trying to tell you about:
$csv = implode("','", $refarray);
^-^-- note the addition of the quotes:
$sql = "SELECT .... `ref_id` IN ('{$csv}')";
^------^--- again, note the quotes
This fixes the problem in the short term. In the long term, you need to read through http://bobby-tables.com and learn what it has to tell you.

Insert a record with an apostrophe mysql php

I want to insert a record with an apostrophe into a MySQL database using PHP. Following is my code:
$importer_name =mysql_escape_string ($objWorksheet->getCellByColumnAndRow(1,3)->getValue());
$exporter_name = $objWorksheet->getCellByColumnAndRow(1, 3)->getValue();
$prod_quantity_unit = $objWorksheet->getCellByColumnAndRow(1,6)->getValue();
$prod_fob_value = $objWorksheet->getCellByColumnAndRow(5,6)->getValue();
$prod_quantity = $objWorksheet->getCellByColumnAndRow(1,8)->getValue();
$prod_fob_unit= $objWorksheet->getCellByColumnAndRow(5,8)->getValue();
$prod_gross_waight= $objWorksheet->getCellByColumnAndRow(1,10)->getValue();
$prod_cif_value= $objWorksheet->getCellByColumnAndRow(5,10)->getValue();
$prod_net_weight= $objWorksheet->getCellByColumnAndRow(1,12)->getValue();
$prod_cif_unit_price= $objWorksheet->getCellByColumnAndRow(5,12)->getValue();
$prod_brand= $objWorksheet->getCellByColumnAndRow(5,14)->getValue();
$hs_code = $objWorksheet->getCellByColumnAndRow(1,17)->getValue();
$shipping_date = $objWorksheet->getCellByColumnAndRow(5,17)->getValue();
$customs = $objWorksheet->getCellByColumnAndRow(1,19)->getValue();
$transport_company = $objWorksheet->getCellByColumnAndRow(5,19)->getValue();
$country_of_origin = $objWorksheet->getCellByColumnAndRow(1,21)->getValue();
$transport_mode = $objWorksheet->getCellByColumnAndRow(5,21)->getValue();
$country_of_trade = $objWorksheet->getCellByColumnAndRow(1,23)->getValue();
$hs_code_description = $objWorksheet->getCellByColumnAndRow(1,26)->getValue();
$product_description = $objWorksheet->getCellByColumnAndRow(1,28)->getValue();
$insertquery="INSERT INTO tb_peru_data
(importer_name,exporter_name,product_quantity_unit,
product_fob_unit,product_quantity,product_fob_value,
product_gross_weight,product_cif_value,
product_net_weight,product_cif_unit_price,
product_brand,shipping_hs_code,shipping_date,
shipping_customs,shipping_transport_company,
shipping_country_of_origin,shipping_transport_mode,
shipping_country_of_trade,hs_code_description,
product_description)
VALUES
('$importer_name','$exporter_name','$prod_quantity_unit',
'$prod_fob_unit','$prod_quantity','$prod_fob_value',
'$prod_gross_waight','$prod_cif_value','$prod_net_weight',
'$prod_cif_unit_price','$prod_brand','$hs_code','$shipping_date',
'$customs','$transport_company','$country_of_origin',
'$transport_mode','$country_of_trade',
'$hs_code_description','$product_description')";
mysql_query($insertquery)or die('ErrorrPERU: '.mysql_error());
/*$del="DELETE * FROM tb_excel_file";
mysql_query($del);*/
?>
This does not work, and gives 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
's','12U','6','9','54',
'34.83','55.5','31.83','6.17','','7323931000','2008/04/1' at line 3
Use mysqli_real_escape_string instead of deprecated mysql_real_escape_string
This function will force you to input mysql table / database.
This way your collation will be considered while escaping
You can use real_escape_string() in PHP. You need to escape the apostrophe (that is, tell SQL that the apostrophe is to be taken literally and not as the beginning or end of a string). To add more, I'd say that you can also use PDO, but consider using addslashes($string) and stripslashes($string).

Database insert in PHP returns string not defined and notice about unknown column

I'm trying to insert into a database a field called Id_Obj and it's a VarChar but when I try to send it I get an error:
Unknown Column 'Id_Obj4' in 'field List'
The insert looks like this:
while($info=mysql_fetch_Array($data))
{
print "name :".$info['Id']." ";
$count=$info['Id'];
}
$t = "INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES(";
$t = $t."IdObj$count".",".$_GET["ns"];
$t = $t.")";
mysql_query($t);
The fields in the database are Id, Id_Obj, Num_Sides.
Couple of things:
You really want to make sure that
your values are escaped
You're missing out on your last ")"
in the query
Your strings need to be wrapped in
quotes, otherwise it thinks you're
using a table name
Your SQL can be like:
$t ="INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES('IdObj4','". $_GET["ns"]. "')";
Also, just as a side so you know the shortcut:
$t = $t . " something added"; is the same as $t .= " something added"
You need to wrap strings with single quotes in SQL.
$ns = intval($_GET('ns')); // This should sanitize $ns enough for the db.
if ($ns > 0)
{
$t="INSERT INTO Table_Faces(Id_Obj,Num_Sides)VALUES(";
$t = $t."'IdObj4'".",".$ns . ")";
mysql_query($t);
}
You also forgot the closing parenthesis.
I have modified your code to be more resistant to SQL Injection in a very simple way. If you intend to make the Id_Obj a variable as well, you should consider using mysql_real_escape_string() to escape the value for use in your SQL statement.
When you are in a situation where your insert query is so small like this, why you don't use everything in a single line? It saves you from a lot of small problems.. I think #Mark solved your problem.

Problems with space within parameters of a php function

Sorry for not formatting my code. the toolbar was gone...
I want to insert some data into a mysql db. I've wrote a function in php:
function add_ID($ID, $token) {
$add = "INSERT INTO ids (ID, token) VALUES ('$ID', '$token')";
mysql_query($add);
echo 'added successfully';
}
if(isset($_GET['addDeviceID'])) {
add_ID($_GET['ID'], $_GET['token']);
}
In the URL-Field of my Browswe I'am calling the function like that:
http://www.justanexample.com/example.php?ID=123123123&token=qwertzuiop
That works.
If I put a space into either one of the parameters for example like that:
http://www.justanexample.com/example.php?ID=123123 123&token=qwertzuiop
Nothing was added to my mysql db.
Would be great to get some help :)
Thank you!
You should validate your input before sending it to the database. Or, if validation is not possible, filter and/or escape the value.
Validation
If you expect ID to be a integer greater than zero:
if (!ctype_digit($ID)) {
// invalid ID
}
If you expect token to be an alphanumeric string:
if (!ctype_alnum($token)) {
// invalid token
}
Filtering
Filtering is removing invalid parts of the input so that it becomes valid:
if (!ctype_digit($ID)) {
$ID = preg_replace('/\D+/', '', $ID);
// $ID does now only contain digits
}
if (!ctype_alnum($token)) {
$token = preg_replace('/\D+/', '', $token);
// $token does now only contain alphanumeric characters
}
Escaping
Escaping is replacing the meta characters of a specific context some string is meant to be placed in. For MySQL queries you should use a function that escapes the meta characters of the context string declaration in MySQL. PHP has the mysql_real_escape_string function for that purpose:
$add = "INSERT INTO ids (ID, token) VALUES ('".mysql_real_escape_string($ID)."', '".mysql_real_escape_string($token)."')";
Your function is vulnerable to SQL injection. You should validate all user-received parameters before using them in an SQL query, and pass any strings through mysql_real_escape_string, because then I could just pass in something like example.php?token='; DROP DATABASE; and royally screw up your application.
In your case, you should make a check that the received parameters are in the form that you expect first, return an error to the user if they don't, and only then pass them into the SQL query.
function add_ID($ID, $token) {
$id = mysql_real_escape_string($id);
$token = mysql_real_escape_string($token);
$add = "INSERT INTO ids (ID, token) VALUES ('$ID', '$token')";
mysql_query($add);
echo 'added successfully';
}
if(isset($_GET['addDeviceID'])) {
$id = isset($_GET['id']) ? $_GET['id'] : 0; // in case no ID has been passed in
$token = isset($_GET['token']) ? $_GET['token'] : '';
if (!is_numeric($id) {
die('ID is not a number');
}
// validate token here as well
add_ID($id, $token);
}
You should also look into parametrized queries, which are an overall much better way of doing SQL queries with parameters than just using string concatenation. For that, look into using the mysqli extension instead of mysql, or at a higher level, PDO.
Remove space from them using str_replace function eg:
$ID = str_replace(' ', '', $ID);
$token= str_replace(' ', '', $token);
$add = "INSERT INTO ids (ID, token) VALUES ('$ID', '$token')";
Also, I suspect your $ID is a integer field in your table so you can run your query without specifying quotes eg:
$add = "INSERT INTO ids (ID, token) VALUES ($ID, '$token')";
Your code is assuming the query successfully completes without ever checking if there was an error. I'm guessing it'll be a syntax error due to the spaces. If your ID field is an integer type, then doing ID=123 123 will be the syntax error. Including all the SQL injection and data sanitizing advice in the other answers, you should rewrite your add_ID function as follows:
function add_ID($ID, $token) {
$query = 'blah blah blah';
mysql_query($query);
if (mysql_error()) {
echo 'ruhroh, someone set us up the bomb: ', mysql_error();
} else {
echo 'woohoo, it worked!';
}
}
At least this will tell you if the query REALLY did succeed, and what blew up if it didn't. Never assume that a database query of any sort will succeed. There's far too many ways for it to blow up (server died, transaction deadlock, connection pool exhausted, out of disk space, etc...) to NOT have even some simplistic error handling as above.
You can use str_replace to remove spaces. But it's not a good practice.
How can URL's be modified so? In normal cases it's unreal.
Contrary, you should test all input values from user(ID must be an integer, Token shouldn't contains "'" symbol and other checks). Read about sql-injections.

Categories