SQL syntax error in mysql - php

I'm inserting value to my MySQL table from php as:
$journey = $_POST['way'];
$from = $_POST['from'];
$to = $_POST['to'];
$dpdt = $_POST['dp_date'];
$rtdt = $_POST['rt_date'];
$fare = $_POST['fare'];
$sql = "insert into tours set " .
"journey='$journey', from='$from', to='$to', dp_date=CAST('$dpdt' AS DATE), " .
"rt_date=CAST('$rtdt' AS DATE), fare='$fare'";
on trying echo for $sql I'm getting output as:
insert into tours set journey='round', from='Aurangabad', to='Kashmir', dp_date=CAST('27-08-2013' AS DATE), rt_date=CAST('21-08-2013' AS DATE), fare='2500'
but I'm continuously getting the same error message:
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 'from=Aurangabad, to='Kashmir', dp_date=CAST('27-08-2013' AS DATE), rt_date=CAST(' at line 1
even if I try to remove ' around the values of column names.
I'm using the same syntax for inserting data and that's working fine.
What's wrong with this?
Why MySQL does not give a proper error for such terrible mistake?

`from`='$from', `to`='$to'
FROM is reserved word use backtick around it.

FROM is reserved keyword and you should not use it. Refer Here

'from' and 'to' are reserve words
Try to do like this
[from] = 'Aurangabad', [to] ='Kashmir'

FROM is a SQL-Keyword. You must not use that without delimiters as a column name.

Related

Wordpress php get result from sql where special character

I have this code
$ntimes = $wpdb->get_var("SELECT Count(*) FROM wp_comp_review_list where email = $key->email");
What I was trying to do is count the number of emails where email = "sample#gmail.com". Wherein the email to compare is generated from another foreach loop.
I am having the following error:
"WordPress database 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 '#gmail.com' at line 1]"
I tried the by comparing names that has spaces. I got the same error because of the space.
Any tips on how to use WHERE with special characters?
An email is a string so you should use quotes, where email = '$key->email' though you're also open to SQL injection, if not it's better safe then hacked..
So you should use prepared statements instead using prepare().
<?php
$results = $wpdb->get_results(
$wpdb->prepare('
SELECT Count(*)
FROM wp_comp_review_list
WHERE email = %s',
[
$key->email
]
)
);
This should also work using esc_sql(), though avoid when you can:
<?php
$email = esc_sql($key->email);
$wpdb->get_var("
SELECT Count(*)
FROM wp_comp_review_list
WHERE email = '{$email}'"
);
?>
Use this :
$ntimes = $wpdb->get_var("SELECT Count(*) FROM wp_comp_review_list where email = '$key->email'");
Since your $key->email has space, it is no more a single word and next thing after space is considered as SQL command (which is it not)
You miss quote '' from the condition:
$ntimes = $wpdb->get_var("SELECT Count(*) FROM wp_comp_review_list where email = '$key->email'");

Proper insert of date in MySql date field

I am posting data for event in this format via ajax:
doctor=100&date=2015-04-30&rCheck=1&rDate=2015-05-12&fromTime=21%3A35&toTime=22%3A40&status=open
I am getting it like this with php
$date = $_POST['date'];
$fromHours = $_POST['fromHours'];
$fromMinutes = $_POST['fromMinutes'];
$toHours = $_POST['toHours'];
$toMinutes = $_POST['toMinutes'];
$fromTime = $_POST['fromTime'];
$toTime = $_POST['toTime'];
$start = $date.' '.$fromTime.':00';
$end = $date.' '.$toTime.':00';
$status = $_POST['status'];
$doctor = $_POST['doctor'];
if($_POST['rCheck']==1){
$repeat = $_POST['rDate'];
}else{
$repeat = '0000-00-00';
}
When I echo any of that variables I get correct result.
I am inserting data in database like this:
$query = 'INSERT INTO events (start,end,doctor,status,repeat) VALUES ("'.$start.'","'.$end.'","'.$doctor.'","'.$status.'","'.$repeat.'")';
$result = mysqli_query($db, $query) or die (mysqli_error($db));
Now main problem is $repeat because without it everything is inserted without problem but with $repeat 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 'repeat) VALUES ("2015-04-30 21:35:00","2015-04-30 22:40:00","100","offen","2015-' at line 1
Insert stops after fifth '-' character. Even if $repeat is 0000-00-00
Field for that in database is date field in format 0000-00-00
I really don't know where problem is.
Thank you for helping.
repeat is a MySQL reserved word
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
Either rename it to something else; for example "repeats", or use ticks around it
(start,end,doctor,status,`repeat`)
Look at what MySQL is telling you; it's pointing it out where it starts:
...for the right syntax to use near 'repeat
^
Sidenote:
If you're still having problems inserting data into your table, you can sanitize your input(s) using mysqli_real_escape_string() or using prepared statements as stated below.
I need to point out though, that your present code is open to SQL injection.
Use prepared statements, or PDO with prepared statements, they're much safer.

Insert, Update, Create Table, queries not working in wampserver

I've been using wampserver for a php project, but DML queries are not working for me. Here is some test code I've been using
$query='insert into register(first_name) values("swagmaster")';
echo($query);
$query = mysqli_real_escape_string($connection,$query);
echo"<br>$query";
if(mysqli_real_query($connection,"'".$query."'")===TRUE)
{
echo"woohoo!";
}
else
{
echo"query failed";
}
echo(mysqli_error($connection));
I get the following output when i run this:
insert into register(first_name) values("swagmaster")
insert into register(first_name) values(\"swagmaster\") query failed
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 ''insert into register(first_name) values(\"swagmaster\")'' at line 1
However, a select statement works fine. I suspect the issue is in mysql settings. Any suggestions?
UPDATE:
Using a combination of your tips, the query is now working. Thank you all!
Please try this query
$query = "INSERT INTO `register` SET `fieldname`='{$vaue}',`field2`='{$value2}'";
Change the query from
$query='insert into register(first_name) values("swagmaster")';
to
$query="insert into register(first_name) values('swagmaster')";
Also as Fred-ii said you dont need to add ' here
if(mysqli_real_query($connection,"'".$query."'")===TRUE)
change to
if(mysqli_real_query($connection,$query)===TRUE)
You used
$query = mysqli_real_escape_string($connection,$query);
But this escaped all quotes in query. This is incorrect. For protected fro SQL injection you should use escape function only to value instead query.
For your example you not need this string.
But if you use variables then you should use it
$value = "swagmaster";
$value = mysqli_real_escape_string($value);
$query='insert into register(first_name) values("' . $value . '")';
In $query is already correct query. And add quotes is incorrect. Just use
if(mysqli_real_query($connection, $query)===TRUE)

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).

How to insert html code in mysql database?

I have copies text from many html files into one text file/variable and I wants to insert this data(basically html code) into mysql database. I have tried mysql_real_escape_string. But it is still no working. This is what I am doing :
$contentFromHtmlFile=file_get_contents($file);
$all_html_content.=$contentFromHtmlFile;
$all_html_content=mysql_real_escape_string($all_html_content);
$insert_query = "insert into $databasetable (pdf_id,pdf_text_data) values (190,$all_html_content);";
mysql_query($insert_query) or die(mysql_error());
This is the 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 '<meta charset=\"utf-8\" />\n\n<div id=\"jpedal\" style=\&quo' at line 1
Here link of text I wants to insert: http://pastebin.com/F3BD745h
You have put string values inside single quotes:
$insert_query = "insert into $databasetable(pdf_id,pdf_text_data)values(190,'$all_html_content');";
P.S:mysql_ function are depricared , don't use them. Use mysqli or PDO.
Wrap your variable around single quotes to signify that it's a string (in this case):
$insert_query = "INSERT INTO $databasetable(pdf_id, pdf_text_data)
VALUES(190, '$all_html_content');";
^ ^
Also, if you do not need to use the string for searching or any similar operations, I'd recommend converting it an ordinary string with base64_encode():
$contentFromHtmlFile = file_get_contents($file);
$all_html_content .= $contentFromHtmlFile;
$all_html_content = base64_encode($all_html_content);
$all_html_content = mysql_real_escape_string($all_html_content);

Categories