inseting xml data to mysql database via php - 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.

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.

unable to encode url in mysql php insert

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.

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.

MySQL query issue with Flex, php

I'm trying to pass a MySQL query with variables from flex to MySQL using php.
This is the Query in Flex. Everything appears to be correct.
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ("+firstName+"," +lastName+")");
When the query is passed to my server via http to be processed by PHP it returns 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 'Test_Value )' at line 1
From what I can see it is trying to include the final ")" as part of the value. I for the life of me cannot see how to stop this from happening.
Here is the php that is being used to process the query where it errors out.
$sql = $_REQUEST['sql'];
$result = mysql_query($sql);
$err = mysql_error();
$cols_count = mysql_num_fields($result) or error_log('Invalid query: ' .mysql_error());
Any help will be much appreciated
This is the function passing the query. Maybe the issue is here?
public function mysqlQuery(sql:String,fid:String):void {
var http:HTTPService = new HTTPService;
var parm:Object = new Object;
parm.sql = sql;
parm.private_key = private_key;
parm.fas_db = mysql_db;
http.url = mysql_url+"?irand="+Math.random();
http.showBusyCursor = true;
http.request = sql;
http.addEventListener(ResultEvent.RESULT, mysqlResult);
http.addEventListener(FaultEvent.FAULT, mysqlFault);
http.method = "POST";
sqlToken = http.send(parm);
sqlToken.param = fid;
}
Change this
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ("+firstName+"," +lastName+")");
to
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ('"+firstName+"','" +lastName+"')");
put ' around values
For removing \
$result = mysql_query(stripslashes($sql));
Changed into
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ("+firstName+"," +lastName+")");
to
mysqlQuery("INSERT INTO poc_note_test (first_name,last_name) VALUES ('"+firstName+"','" +lastName+"')");
IN sql , the string character are quoted in single quotes/double quotes.

"mysql_fetch_assoc()" error when data in mysql field is changed

I have a mySQL database from where I fetch some data via PHP.
This is what I've got:
if ($db_found) {
$URL_ID = $_GET["a"];
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = $URL_ID";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$firstname = $db_field['firstname'];
$surname = $db_field['surname'];
$function = $db_field['function'];
$email = $db_field['email'];
$telnr = $db_field['telnr'];
}
mysql_close($db_handle);
}
else {
print "Database not found... please try again later.";
mysql_close($db_handle);
}
The URL_ID field in my mySQL database is, for this example, 001. When I go to www.mydomain.com/index.php?a=001 it fetches all the data, puts it into a variable, and I can echo the variables without any problem.
Now, I want to change the URL_ID, and I've changed it to "62ac1175" in the mySQL database. However, when I proceed to www.mydomain.com/index.php?a=62ac1175, I get this error message:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
boolean given in
mydomain.com\db_connect.php on line 17
The field in mySQL has varchar(8) as type and utf8_general_ci as collation.
If I change the entry back to 001 and change my URL to ?a=001, it works fine again.
What's going wrong?
You are not doing any error checking in your query, so it's no wonder it breaks if the query fails. How to add proper error checking is outlined in the manual on mysql_query() or in this reference question.
Example:
$result = mysql_query($SQL);
if (!$result)
{ trigger_error("mySQL error: ".mysql_error());
die(); }
your query is breaking because you aren't wrapping the input in quotes. You can avoid* quotes only for integers (which 62ac1175 is not). Try
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = '$URL_ID'";
Also, the code you show is vulnerable to SQL injection. Use the proper sanitation method of your library (like mysql_real_escape_string() for the classic mysql library that you are using), or switch to PDO and prepared statements.
In your code, this would look like so: Instead of
$URL_ID = $_GET["a"];
do
$URL_ID = mysql_real_escape_string($_GET["a"]);
* however, if you avoid quotes, mysql_real_escape_string() won't work and you need to check manually whether the parameter actually is an integer.

Categories