unable to encode url in mysql php insert - php

I am trying to insert a url to mysql(through php) column but unable to do it.
I am getting the following error
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 '%2F%2Flocalhost%2Fclient%2Fsave_file.php%3Ffilename%3D9 WHERE queryid='29'' at line 1
The code snippet :
$_POST['url1']="//localhost/client/save_file.php?filename=9";
$_POST['query_id']=29;
$var=$_POST['url1'];
$query_id=$_POST['query_id'];
// echo "$var";
$var=rawurlencode($var);
//echo "$var";
$sql1 = "UPDATE query_audio SET query_content=$var WHERE queryid='".$query_id."' ";
if (!mysql_query($sql1)) {
die('Error: ' . mysql_error($connection));
}

You have a fundamental misunderstanding of how to defend against SQL injection attacks You need to use mysql_real_escape_string(), not urlencode().
Plus, you forgot to quote your $var variable, so your query is litterally:
... SET query_content=http:%2F%2Fetc...
Without quotes around that url, mysql is free to interpret the http: portion as an (invalid) field name.
Try
$var = mysql_real_escape_string($_POST['url1']);
$query_id = mysql_real_escape_string($_POSt['query_id']);
$sql = "UDPATE ... SET query_content='$var' WHERE queryid='$query_id';";
^----^-- note these quotes.

Related

keep getting a syntax error (php / mysql)

php/mysql
I keep 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 '1' at line 1".
I'm trying hard to make this query to happen. It works, it inserts into the mysql database but this error appears every time. I've tried to use everything in the same line, changed double quotes to single quotes, removed all the whitespaces inserting everything in the samen line, changing the way I pass the variables({$variable} to '.$variable.') and everything else. I've seen a couple of stackoverflow questions related to this but with different solutions.
I know that we can't pass '' in a numeric fields.
I think I'm out of options now. Need help!
This error keeps showing but the data is correctly inserted in my table
here is the code:
$user_id = get_current_user_id();
$prescription_name = $_POST['prescription_name'];
$date_created = date('Y-m-d');
$last_updated = date('Y-m-d');
$right_eye_sphere = $_POST['right_eye_sphere'];
$left_eye_sphere = $_POST['left_eye_sphere'];
$right_eye_cylinder = $_POST['right_eye_cylinder'];
$left_eye_cylinder = $_POST['left_eye_cylinder'];
$right_eye_axis = $_POST['right_eye_axis'];
$left_eye_axis = $_POST['left_eye_axis'];
$pd = $_POST['pd'];
$date_of_birth = $_POST['date_of_birth'];
$file_path = $_POST['file_path'];
$add_query = "INSERT INTO wew_prescription (
prescription_id,
user_id,
prescription_name,
date_created,
last_updated,
right_eye_sphere,
left_eye_sphere,
right_eye_cylinder,
left_eye_cylinder,
right_eye_axis,
left_eye_axis,
pd,
date_of_birth,
file_path
) Values (
NULL,
{$user_id},
'{$prescription_name}',
'{$date_created}',
'{$last_updated}',
'{$right_eye_sphere}',
'{$left_eye_sphere}',
'{$right_eye_cylinder}',
'{$left_eye_cylinder}',
'{$right_eye_axis}',
'{$left_eye_axis}',
'{$pd}',
'{$date_of_birth}',
'{$file_path}'
)";
$sql = $dbCon->query($add_query);
if (!mysqli_query($dbCon,$sql)){
die('Error: ' . mysqli_error($dbCon));
}else{
mysqli_query($dbCon,$sql);
echo "dados atualizados!";
}
The error is coming from this line:
if (!mysqli_query($dbCon,$sql)){
$sql contains the result of
$dbCon->query($add_query);
Since that query was successful, $sql contains TRUE. mysqli_query() requires the second argument to be a string, so TRUE becomes "1", so you're effectively doing:
if (!mysqli_query($dbCon, "1")) {
That's not a valid query, so you get an error.
I think what you really meant to do was:
if (!$sql) {
die('Error: ' . $dbCon->error);
} else {
echo "dados atualizados!";
}
You don't need to keep calling mysqli_query() repeatedly.
You should also learn to code using prepared statements instead of substituting variables into the query, to prevent SQL injection.

Why does msyqli_real_escape_string() not escape multiple backslashes properly?

Given this SQL
UPDATE `mytable`
SET `mycolumn`='karla bailey-pearapppppppp\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'
WHERE `id`=5619
Why will mysqli_real_escape_string() not escape this string properly?
Trying to use this SQL query after escaping the column's value produces this mysqli 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 ''karla bailey-pearapppppppp\\\\\\\\\\\\\\\\\\\\\\\\\\\' at line 3"
Is there a limit to the number of backslashes that can be escaped?
Are you escaping the ENTIRE string? e.g.
$sql = "UPDATE .... \\\\\\\'";
$escaped = mysqli_real_escape_string($link, $sql);
If so, that's incorrect. You are trashing the string by doing that. You'll also be escaping the ' that delimit your where clause value. Escaping should be performed only VALUES that you're inserting into the string. e.g.
$name = "Miles O'Brien"; // ' in name would cause syntax error
$bad_sql = "SELECT '$name'";
$broken_sql = mysqli_real_escape_string($link, $bad_sql);
// produces: SELECT \'Miles O\'Brien\'
$ok_sql = "SELECT '" . mysqli_real_escape_string($link, $name) . "'";
// produces: SELECT 'Miles O\'Brien';
Ok, so I found the problem. The application checks for the value length > column maximum, and if the value is too great, truncates the value AFTER the escape is done - thereby breaking the escaped value (very isolated case where this would occur, this code has been in place for years).
Ergo, can't truncate a value that ends in backslashes after the value is already escaped.

inseting xml data to mysql database via php

I want to read an xml file using file_get_contents() and then insert this file to my mysql database but i have an error on my code, please see my code below:
//details ommited
$address= $_GET['address'];
$xml = file_get_contents($address);
db_connect(); // my db connection function
$query = "INSERT INTO feeds SET name = '$name' , xml_data = '$xml' ";
$result = mysql_query($query);
if(!$result)
{
echo mysql_error();
}
// end of my code
So , when i add , xml = '$xml' to my sql $query, php show this error to me:
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 OFF-state current.]]></description>\n\t\t\t</' at line 1
A few suggestions
use PDO parameter binding
escape your xml input
With how you're currently doing it, $xml may have a character that is ending your sql statement prematurly. I have no idea what character could cause this, but my suggestions should fix that.

Post data to mysql DB

I'am trying to send data from android as JSON to PHP in order to parse it and save in MySQL DB
this is the part of the PHP CODE
$JsonString = $_POST["DATA"];
$JsonData = json_decode($JsonString, TRUE);
$Add_First_Only = 0;
foreach ($JsonData['items'] as $item)
{
$Order_ID = $item['Order_ID'];
$Order_Row_Number = $item['Order_Row_Number'];
$Order_Item_ID = $item['Order_Item_ID'];
$Order_Course_ID = $item['Order_Course_ID'];
$Order_Seat_No = $item['Order_Seat_No'];
$Order_Row_Value_wo_Options = $item['Order_Row_Value_wo_Options'];
$Order_Row_Value_with_options = $item['Order_Row_Value_with_options'];
if ($Add_First_Only == 0)
{
$result = mysqli_query($con,
"INSERT INTO order_items (Order_ID,Order_Row_Number,Order_Item_ID,Order_Course_ID,Order_Seat_No,Order_Row_Value_wo_Options, Order_Row_Value_with_options)
VALUES
(['$Order_ID'],['$Order_Row_Number'],['$Order_Item_ID'],['$Order_Course_ID'],
['$Order_Seat_No'],['$Order_Row_Value_wo_Options'],['$Order_Row_Value_with_options'])"
);
$Add_First_Only = 1;
}
}
and this is the error I get on the Eclipse LogCAT
12-16 02:00:01.800: V/TAG(1841): 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 '['26'],['1'],['1'],['1'],['1'],['0'],['1'])' at line 4
As you can see from the error it self that I have values for the variables so non of them is a null value
The Question is what should I change or add to my sql syntax to fix this error ?
Remove the brackets around ['$Order_ID'] and the others
Use '$Order_ID' instead of ['$Order_ID'] etc. for your VALUES
if ($Add_First_Only == 0)
{
$result = mysqli_query($con,
"INSERT INTO order_items (Order_ID,Order_Row_Number,Order_Item_ID,Order_Course_ID,Order_Seat_No,Order_Row_Value_wo_Options, Order_Row_Value_with_options)
VALUES
('$Order_ID','$Order_Row_Number','$Order_Item_ID','$Order_Course_ID',
'$Order_Seat_No','$Order_Row_Value_wo_Options','$Order_Row_Value_with_options')"
);
$Add_First_Only = 1;
}
Don't wrap the parameters in the SQL statemenst with square brackets (example: ['$Order_ID']).
I often find it helpful to echo or error_log the SQL statement that is created and try running it in a SQL tool. This should give you better error messages, and reveal syntax errors (if the tool has syntax highlighting).
Also, look at what php.net has to say about prepared statements. SQL-statements of this type are vulnerable to SQL-injection attacks which are one of the most common ways to attack systems.
When you use Single quotes '' around the data you want to INSERT into DB you tell PHP that this data is string type and your database probably expects INTEGER data.

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 '

The code below is used when the user enters a youtube url it get the youtube id from the url. It then get the title for that video with that id. That is then inserted into a database and recalled to display the image of the video associated with that id.
if i use this youtube url http://www.youtube.com/watch?v=p64tAbP-nHE or and other youtube url. If the title of that youtube url contains a ' ie(2013 Ravens Rock Rally - Jonathan O'Callaghan & Gavin Sheehan - Stage 3) i get the error
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 'Callaghan & Gavin Sheehan - Stage 3'' at line 1
Any help would be great, thanks in advance.
Here is my code:
<?php
include 'dataconnection.php';
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
$url = $_POST['set_video'];
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
$youtube_id = $my_array_of_vars['v'];
$info = $_POST['set_desc'];
$id = $my_array_of_vars['v'];
$xmlData = simplexml_load_string(file_get_contents("http://gdata.youtube.com/feeds/api/videos/{$id}?fields=title"));
$title = (string)$xmlData->title;
$sql="INSERT INTO videodetails SET id='null',youtube_id='$youtube_id',info='$title'";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
echo "<div id='pageheader'>
1 record added<span id='logout'>Return to <a href='contributors_login.html'>Contributors Login</a></span>
</div>";
echo '<div id="setvideo"><img src="http://i4.ytimg.com/vi/'.$my_array_of_vars['v'].'/default.jpg" style="border:solid 2px white;"><p>'.$title.'</p></div>';
mysqli_close($connection);
?>
Use mysqli_real_escape_string in your INSERT INTO ... part.
You open single quotes. But the title contains also single quotes so they get closed. MySQL doesn't know this and thinks the text that follows is a MySQL keyword.
Your yourTube name has a quote in it, so the SQL line
$sql="INSERT INTO videodetails SET id='null',youtube_id='$youtube_id',info='$title'
becomes this
INSERT INTO videodetails SET id='null',
youtube_id='2013 Ravens Rock Rally - Jonathan O'Callaghan & Gavin Sheehan - Stage 3'
which MySQL sees as
INSERT INTO videodetails SET id='null',
youtube_id='2013 Ravens Rock Rally - Jonathan O',Callaghan & Gavin Sheehan - Stage 3'
and MySQL doesn't understand Callaghan & Gavin Sheehan - Stage 3'
The case of strings that contain quotes is why mysqli_real_escape_string() exists, to find those quotes and insert a \ before them so they count as literal quote characters, instead of terminating the quoted string.
. . .
$youtube_id = mysqli_real_escape_string($my_array_of_vars['v']);
$info = mysqli_real_escape_string($connection, $_POST['set_desc']);
$sql="INSERT INTO videodetails SET id='null',youtube_id='$youtube_id',info='$title'";
if (!mysqli_query($connection,$sql))
. . .
But the best practice is to use query parameters, so you don't need to worry about those embedded quotes. Any place you have a variable in your SQL string in place of a literal value, use a query parameter placeholder. These placeholders don't work in place of table names, column names, or SQL expressions or keywords -- they only work where you would normally put a single scalar value in your SQL.
$sql="INSERT INTO videodetails SET id='null',youtube_id=?,info=?";
if ($stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, 'ss', $youtube_id, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is safer, and makes your SQL more readable. Notice that the ? placeholder itself doesn't go inside quotes, even if the value you bind to it is a string.
PS: I question your use of the quoted string 'null' where you may mean the SQL keyword NULL.
Your insert query is not valid sql. The keyword "set" is used with update queries. Insert queries look like this:
insert into atable
(f1, f2, etc)
values
(val1, val2, etc)
or this
insert into atable
(f1, f2, etc)
select val1, val2, etc
from someOtherTables

Categories