Post data to mysql DB - php

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.

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.

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.

using form variables for mysql query

I'm trying to fetch a result from a mysql table using two form variables namely $sessionID and $semesterID. I used the following code and it seems to have an error in the sql syntax
<?php
...
mysql_select_db($database_connChePortal, $connChePortal);
$query_rsRegcourses =sprintf("SELECT * FROM VW_reg vwr WHERE vwr.sessionID=%s AND vwr.semesterID=%s",$sessionID,$semesterID);
$rsRegcourses = mysql_query($query_rsRegcourses, $connChePortal) or die(mysql_error());
$row_rsRegcourses = mysql_fetch_assoc($rsRegcourses);
$totalRows_rsRegcourses = mysql_num_rows($rsRegcourses);
print_r($query_rsRegcourses); die;
...
?>
I tried running the query and I have the following error report
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 'AND vwr.semesterID=' at line 1
thanks
I think you should surround your variable with single quotes '' please change as follow
"SELECT * FROM VW_reg vwr WHERE vwr.sessionID='%s' AND vwr.semesterID='%s'"
Put the %s in single quotes like this
"SELECT * FROM VW_reg vwr WHERE vwr.sessionID='%s' AND vwr.semesterID='%s'",$sessionID,$semesterID);
To insert a variable into query, you have to properly format it.
Two other answers contains improper formatting - so, you shouldn't follow them.
To make formatting more handy, you have to encapsulate sprintf() into function like this:
function paraQuery()
{
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val)
{
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
$result = mysql_query($query);
if (!$result)
{
throw new Exception(mysql_error()." [$query]");
}
return $result;
}
which would apply proper formatting and also will handle errors
Also note that your way of counting records is extremely inefficient and may cause server to hang. You have to query the only data you need. So, if you need only count - request the count only
so, the code would be
mysql_select_db($database_connChePortal, $connChePortal);
$sql = "SELECT count(*) FROM VW_reg vwr WHERE vwr.sessionID=%s AND vwr.semesterID=%s";
$res = paraQuery($sql,$sessionID,$semesterID);
$row = mysql_fetch_row($res);
print_r($row[0]); die;
it will make your query properly formatted and thus invulnerable to SQL injection
also, it seems that $semesterID is not set which may cause some problem too

PHP mysql_query Syntax Error

<?php
mysql_connect("localhost","root","");
mysql_select_db("hftwmvirtualdb");
$Booknum = mysql_real_escape_string($_POST['Booknum']);
$Chapternum = mysql_real_escape_string($_POST['Chapternum']);
$Versenum = mysql_real_escape_string($_POST['Versenum']);
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = $Booknum AND `CHAPTERID` = $Chapternum AND `VERSENO` = $Versenum");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
mysql_close();
?>
I am trying to use posted data from an android application to trigger a query and retrieve the results from the mysql database. The Table has 4 columns, and I'm trying to retrieve the value in the third column by defining the values in the first 3 columns. Each time i clicked the button, I get the parsing error to find out my PHP script was not processing the SQL query. When running the scriptthrough the browser I get the messages:
Undefined index: Booknum in C:\wamp\www\GetVerse.php on line 4
Undefined index: Chapternum in C:\wamp\www\GetVerse.php on line 5
Notice: Undefined index: Versenum in C:\wamp\www\GetVerse.php on line 6
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 'AND CHAPTERID = AND VERSENO =' at line 1
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\wamp\www\GetVerse.php on line 9.
I understand i get the warning messages 1-3 is because I did not submit the post data but the latter I don't know how to fix as I have tried using the correct syntax, I tried removing "=" for "like" and that failed also. What is the problem?.
The undefined index errors are, as you specified, occurring because you did not submit the post data. This, in turn, is causing the variables $Booknum, $Chapternum, and $Versenum to be empty.
With the empty variables, the MySQL query is being generated with a WHERE clause like:
WHERE `BOOKID` = AND `CHAPTERID` = AND ...
The missing values are causing invalid MySQL, hence your error. Additionally, as you've specified (in a comment) that the POST-values are strings (and not integers which is what I would have assumed based on their usage and names), you have to wrap the values in quotes in your MySQL query too. If you do not wrap the values in quotes, even valid strings may cause the query to fail.
To fix this, try something like:
$Booknum = isset($_POST['Booknum']) ? mysql_real_escape_string(trim($_POST['Booknum'])) : null;
$Chapternum = isset($_POST['Chapternum']) ? mysql_real_escape_string(trim($_POST['Chapternum'])) : null;
$Versenum = isset($_POST['Versenum']) ? mysql_real_escape_string(trim($_POST['Versenum'])) : null;
if (!empty($Booknum) && !empty($Chapternum) && !empty($Versenum)) {
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = '" . $Booknum . "' AND `CHAPTERID` = '" . $Chapternum . "' AND `VERSENO` = '" . $Versenum . "'");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
mysql_close();
}
This will verify that the values are properly set - if not, they will be set to null. If all three values are not empty, via PHP's empty(), your query will be executed.
This is what your SQL query will look like when the variables are substituted in:
SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = AND `CHAPTERID` = AND `VERSENO` =
When the variables contain no content (as they won't if you submit no data), the query is meaningless: the syntax is malformed.
Check whether the data is posted before doing the query. Moreover, it will also profit you to start using parameterised queries (using MySQLi or PDO) for security and convenience.
The "undefined index" messages you're getting are because those variables are not set. Check that you're actually posting those to the script.
The empty variables are why your query is wrong and you get an error.
Consider using PDO as the "mysql_" commands are deprecated. You should check your inputs before passing them to the query. isset() will work for that.
CHeck whether the Post data is coming or not, undefined index it is because, there is no data for the variables you have used. SO first verify it and then execte the SQL query.
if(isset($_POST['Booknum']) && isset($_POST['Chapternum']) && isset($_POST['Versenum']))
{
$Booknum = mysql_real_escape_string($_POST['Booknum']);
$Chapternum = mysql_real_escape_string($_POST['Chapternum']);
$Versenum = mysql_real_escape_string($_POST['Versenum']);
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = $Booknum AND `CHAPTERID` = $Chapternum AND `VERSENO` = $Versenum");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
}
else
{
echo "No post data";
}

Categories