How to properly concat/escape this sql query in php [duplicate] - php

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I am trying to insert multiple rows in mysql database using php.
A portion of the code is as below.
$b_address = $_POST["b_address"];
$s_address = $_POST["s_address"];
$query = "INSERT INTO order VALUES";
foreach ($_SESSION['buy'] as $products) {
$username = $_COOKIE["uname"];
$Product_Name = $products["Product_Name"];
$qty = $products["qty"];
$price = $products['qty'] * $products['Price'] ;
$query .= "('',
(select id from user_detail where user_name = $username ) ,
(select Product_id from products where Product_Name = $Product_Name ) ,
$qty,
$price ,
$b_address ,
$s_address ,
NOW()
),";
}
rtrim($query, ',');
But i am getting some syntex error where selecting id.
How to get rid of the syntex error and run the code properly?
error i am getting is as below :
errorYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order VALUES('', (select id from user_detail where user_name = ar' at line 1
EDIT
I changed the line into $query = "INSERT INTOordersVALUES";
and now the error i am getting is :
errorYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 21
EDIT 2
Here is the whole code of the page, incase i am blindly mistaking somewhere.
<?php
session_start();
$con=mysql_connect('localhost','root','mypass');
if(!$con)
{
die ('connection error'.mysql_error());
}
mysql_select_db('test1',$con);
if (isset($_POST['submit'])) {
if (!empty($_POST['b_address']) && !empty($_POST['s_address']) ) {
$b_address = $_POST["b_address"];
$s_address = $_POST["s_address"];
$query = "INSERT INTO `orders` VALUES ";
foreach ($_SESSION['buy'] as $products) {
$username = $_COOKIE["uname"];
$Product_Name = $products["Product_Name"];
$qty = $products["qty"];
$price = $products['qty'] * $products['Price'] ;
$query .= "('',
(select id from user_detail where user_name = '$username' ) ,
(select Product_id from products where Product_Name = '$Product_Name' ) ,
'$qty',
'$price' ,
'$b_address' ,
'$s_address' ,
NOW()
),";
}
rtrim($query, ',');
if(!mysql_query($query,$con))
{
die ("error".mysql_error());
}
else
{
echo "Thank you for your purchase. Your order is under processing.";
unset($_SESSION['buy']);
}
}else{
echo 'All fields are required.';
}
}

Try this:
Please observe order
$query = "INSERT INTO `order` VALUES ";
foreach ($_SESSION['buy'] as $products) {
$username = $_COOKIE["uname"];
$Product_Name = $products["Product_Name"];
$qty = $products["qty"];
$price = $products['qty'] * $products['Price'] ;
$query .= "('',
(select id from user_detail where user_name = '$username') ,
(select Product_id from products where Product_Name = '$Product_Name') ,
'$qty',
'$price' ,
'$b_address' ,
'$s_address' ,
NOW()
),";
Explanation: Order is MySQL reserved word.
You can not use it in your SQL for any Table name or field name.

Related

Updating a date row and time row within MySQL with php

I'm getting the following error when I try to update a date and a time row within my table:
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 'date = '7890-06-06' time = '12:34:00' ' at line 3
Not entirely sure why I'm getting this as I'm using '' in the sql code and the format in the tables is all correct.
PHP code:
<?php
include 'database_conn.php';
if(!$conn)
{
echo "Error connecting to database";
}
if (mysqli_connect_errno())
{
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
}
$eventid = isset($_GET['eId']) ? $_GET['eId'] : NULL;
$title = isset($_REQUEST['titleField']) ? $_REQUEST['titleField'] : '';
$time = isset($_REQUEST['timeField']) ? $_REQUEST['timeField'] : '';
$date = isset($_REQUEST['dateField']) ? $_REQUEST['dateField'] : '';
$location = isset($_REQUEST['locationField']) ? $_REQUEST['locationField'] : '';
$description = isset($_REQUEST['descriptionField']) ? $_REQUEST['descriptionField'] : '';
//echo "Event: $eventid";
//echo "User: $uid";
//echo "Comment: $comment";
echo "$date";
echo "$time";
$sql = "UPDATE Events
SET name = '$title'
date = '$date'
time = '$time'
location = '$location'
description = '$description'
WHERE eventid = '$eventid'
";
$results = mysqli_query($conn, $sql)
or die(mysqli_error($conn));
if($results)
{
echo "Event successfully edited";
}
mysqli_close($conn);
?>
Not sure the best way to represent the table, but here it is:
# Name Type
1 eventid int(11)
2 name varchar(255)
3 date date
4 time time
5 location varchar(255)
6 description varchar(1000)
you should add comma separations',' between sets statements:
$sql = "UPDATE Events
SET name = '$title',
date = '$date',
time = '$time',
location = '$location',
description = '$description'
WHERE eventid = '$eventid'
";

Error in SQL syntax, check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY category ASC' at line 1

Site has been working fine for years and all of a sudden I am getting this error. Any help from the experts would be greatly appreciated.
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 'ORDER BY category ASC' at line 1
Here is the code in question:
// SQL injection attack prevention function
$unit_Recordset1 = "";
if (isset($_GET['unit'])) {
$unit_Recordset1 = GetSQLValueString($_GET['unit'], "text");
}
$category_Recordset1 = "";
if (isset($_GET['category'])) {
$category_Recordset1 = GetSQLValueString($_GET['category'], "text");
}
else $_GET['category'] = "";
// Query builder that create single or multiple AND query
$sql = "SELECT * FROM documents WHERE ";
if(!empty($unit_Recordset1)) {$sql .= " unit = $unit_Recordset1 AND ";}
if(!empty($category_Recordset1)) {$sql .= " category = $category_Recordset1 AND ";}
// Remove the last AND
$sql = substr($sql, 0, -4);
if(!empty($category_Recordset1)) $sql .= " ORDER BY title ASC";
else $sql .= " ORDER BY category, title ASC";
// Query for left nav DISTINCT category values
$sqlnav = "SELECT DISTINCT category FROM documents WHERE unit = $unit_Recordset1 ORDER BY category ASC";
mysql_select_db($database_local, $local);
$Recordset1 = mysql_query($sql, $local) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
$Recordset2 = mysql_query($sqlnav, $local) or die(mysql_error());
$row_Recordset2 = mysql_fetch_assoc($Recordset2);
$totalRows_Recordset2 = mysql_num_rows($Recordset2);
There are flows where $unit_Recordset1 may be empty. In which case, the following statement:
$sqlnav = "SELECT DISTINCT category FROM documents WHERE unit = $unit_Recordset1 ORDER BY category ASC";
Will evaluate to:
SELECT DISTINCT category FROM documents WHERE unit = ORDER BY category ASC
Which, of course, isn't valid SQL.
You need to add a check against this case too, something down the lines of:
$unitClause = "";
if(!empty($unit_Recordset1) {
$unitClause = "WHERE unit = $unit_Recordset1 ";
}
$sqlnav = "SELECT DISTINCT category FROM documents $unitClause ORDER BY category ASC";
Your $sqlnav query should be like this
SELECT DISTINCT category FROM documents WHERE unit = '$unit_Recordset1' ORDER BY category ASC
encapsulate variable $unit_Recordset1 with single quotes

Error: You have an error in your SQL syntax; check the manual that corresponds .. syntax to use near '1' at line 1

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. the code is a follows where i get the error and that is come going from http://cms2.br-de.tk/editinfo.php to http://cms2.br-de.tk/updateinfo.php
<?php
mysql_connect("mysql10.000webhost.com","******_12","*******") or die("Error:".mysql_error());
mysql_select_db("******_1");//add your dbname
//get the variables we transmitted from the form
$Title = $_POST['Title'];
$Author = $_POST['Author'];
$Date = $_POST['Date'];
$Content = $_POST['Content'];
//replace TestTable with the name of your table
//replace id with the ID of your user
$sql = "UPDATE `posts` SET `Tilte` = '$Tilte',`Author` = '$Author',`Date` = '$Date',`Content` = '$Content' WHERE `posts`.`ID` = '$ID' 1 ";
mysql_query($sql) or die ("Error: ".mysql_error());
echo "Database updated. <a href='editinfo.php'>Return to edit info</a>";
?>
You have added additional 1 at the end of query. It should be like this:
$sql = "UPDATE `posts` SET `Tilte` = '$Title',`Author` = '$Author',`Date` = '$Date',`Content` = '$Content' WHERE `posts`.`ID` = '$ID'";
You have a spare 1 at the end of your statement.
UPDATE `posts` SET `Tilte` = '$Title',`Author` = '$Author',`Date` = '$Date',`Content` = '$Content' WHERE `posts`.`ID` = '$ID';"
As Grigore correctly spotted, you might also have a typo in your statement depending on your column names.
UPDATE `posts` SET `Title` = '$Title',`Author` = '$Author',`Date` = '$Date',`Content` = '$Content' WHERE `posts`.`ID` = '$ID';"
`Tilte` = '$Title'
maybe this is title not tilte, besides that there's a "1" right at the ending of the query

mysql syntax error on performing a ranking query

i want to perform a ranking query but i'm not sure what is the right syntax
here is my query:
static public function sortranks(){
global $db;
$sql ="TRUNCATE TABLE `ranking`";
$db->query($sql);
$sql = "INSERT INTO `ranking` (`user_id`) VALUES
( SELECT `employe_id` FROM `rates_employe` WHERE `status` = '0' ORDER BY rawpoint DESC ) ";
$db->query($sql);
$sql = "UPDATE rates_employe , ranking SET rates_employe.rank = ranking.rank WHERE
rates_employe.employe_id = ranking.user_id ";
$db->query($sql);
echo 'ok';
exit;
}
i keep getting syntax error when i run this query
Database 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 'SELECT employe_id FROM rates_employe WHERE
status = '0' ORDER BY rawpoint ' at line 2
You should execute the queries one by one, instead of joining them together.
Change the .= string concatenation with a simple assignment, and after assigning each query, execute it. Such as:
$sql = "TRUNCATE TABLE ranking";
$db->query($sql);
$sql = "INSERT INTO `ranking`(`user_id`) VALUES ...";
$db->query($sql);
Also remove VALUES from the query:
INSERT INTO ranking (user_id)
( SELECT employe_id FROM rates_employe WHERE status = '0' ORDER BY rawpoint DESC )
Sorry if I sound pedantic, but in English Employee is spelt with two e at the end of the word.
Try running each queries separately:
static public function sortranks(){
global $db;
$sql ="TRUNCATE TABLE ranking";
$db->query($sql);
$sql = "INSERT INTO `ranking`(`user_id`) VALUES
( SELECT `employe_id` FROM `rates_employe` WHERE `status` = '0' ORDER BY `rawpoint` DESC ) ";
$db->query($sql);
$sql = "UPDATE rates_employe , ranking SET rates_employe.rank = ranking.rank WHERE
rates_employe.employe_id = ranking.user_id ";
$db->query($sql);
echo 'done';
exit;
}

PHP Query problem

UPDATE
Maybe I am just a dummy and can't see my mistake. Basically this is function is handling the math behind everything else. It has multiple queries and updates and inserts in two different tables..
When I try to process it, it gives me:
Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /home/content/53/7311353/html/gs/cca/accounts/include/processAct.php on line 241
Here's my function:
function calculateBilling(){
$date = date('mdY');
$bid = mysql_real_escape_string($_POST['bid']);
$account = mysql_real_escape_string($_POST['account']);
$timein = mysql_real_escape_string($_POST['timein']);
$desc = mysql_real_escape_string($_POST['desc']);
$hrs2calc1 = mysql_real_escape_string($_POST['hrly']);
$hrs2calc2 = mysql_real_escape_string($_POST['rhrly']);
$query = 'SELECT bid, account, hrly, rhrly, bal FROM billing WHERE bid='.$bid;
$result = mysql_query($query);
HERES LINE 241 ----> while($row = mysql_fetch_row($result)){
$accounttobebilled = $row[1];
$hrly = $row[2];
$rhrly = $row[3];
$curbal = $row[4];
}
$sub1 = $hrly * $hrs2calc1;
$sub2 = $rhrly * $hrs2calc2;
$subtotal = $sub1 + $sub2;
$total = $curbal + $subtotal;
$query2 = 'UPDATE billing SET bal = '.$total.' WHERE bid ='.$bid;
$result2 = mysql_query($query2);
// Update Billing Log for this customer
mysql_query("INSERT INTO billingLog (bid, date, hrsOnsite, hrsRemote, timein, descript, total) VALUES ('$bid', '$date', '$hrs2calc1', '$hrs2calc2', '$timein', '$desc', '$subtotal')");
}
I think the problem is coming from my select (drop down) where it posts to the script:
<select class="form-dropdown validate[required]" style="width:150px" id="input_5" name="account">
<?php
while($row =
mysql_fetch_row($result)){
$bid =$row[0];
$account = $row[1];
echo '<option value="'.$bid.'">'.$account.'</option>';
}
?>
</select>
For James:
SELECT bid, account, hrly, rhrly, bal FROM billing WHERE bid=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 '' at line 1
Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in /home/content/53/7311353/html/gs/cca/accounts/include/processAct.php on line 243
UPDATE billing SET bal = 0 WHERE bid =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 '' at line 1INSERT INTO billingLog (bid, date, hrsOnsite, hrsRemote, timein, descript, total) VALUES ('', '07292011', '2', '2', '2', '2', '0')
If you use this instead, what output do you get:
function calculateBilling(){
$date = date('mdY');
$bid = mysql_real_escape_string($_POST['bid']);
$account = mysql_real_escape_string($_POST['account']);
$timein = mysql_real_escape_string($_POST['timein']);
$desc = mysql_real_escape_string($_POST['desc']);
$hrs2calc1 = mysql_real_escape_string($_POST['hrly']);
$hrs2calc2 = mysql_real_escape_string($_POST['rhrly']);
$query = 'SELECT bid, account, hrly, rhrly, bal FROM billing WHERE bid='.$bid;
echo $query;
$result = mysql_query($query);
echo mysql_error();
while($row = mysql_fetch_row($result)){
$accounttobebilled = $row[1];
$hrly = $row[2];
$rhrly = $row[3];
$curbal = $row[4];
}
$sub1 = $hrly * $hrs2calc1;
$sub2 = $rhrly * $hrs2calc2;
$subtotal = $sub1 + $sub2;
$total = $curbal + $subtotal;
$query2 = 'UPDATE billing SET bal = '.$total.' WHERE bid ='.$bid;
echo $query2;
$result2 = mysql_query($query2);
echo mysql_error();
// Update Billing Log for this customer
$query3 = "INSERT INTO billingLog (bid, date, hrsOnsite, hrsRemote, timein, descript, total) VALUES ('$bid', '$date', '$hrs2calc1', '$hrs2calc2', '$timein', '$desc', '$subtotal')";
echo $query3;
mysql_query($query3);
echo mysql_error();
}
It's your concatenation.
Change
$query = 'SELECT bid, account, hrly, rhrly, bal FROM billing WHERE bid='.$bid.'';
to
$query = 'SELECT bid, account, hrly, rhrly, bal FROM billing WHERE bid='.$bid;
I'm also assuming that bid is an integer. Otherwise you need quotes:
$query = 'SELECT bid, account, hrly, rhrly, bal FROM billing WHERE bid="'.$bid.'"';
This is wrong too
mysql_query("UPDATE billing SET bal = '$total' WHERE bid ='.$bid.'");
should be something like
mysql_query("UPDATE billing SET bal = '{$total}' WHERE bid ='{$bid}'");
-- or full concatenation
mysql_query("UPDATE billing SET bal = '" . $total . "' WHERE bid ='" . $bid . "'");
Same goes for you last query.
With the information provided, it's kinda hard to figure out what the problem is. Your best solution is outputting mysql_error() right after you run the query.
$result = mysql_query($query);
echo mysql_error();
Unless you have incorrectly specify table name or field name, the value on your SELECT statement, should be wrapped with proper quoted.
To me, it seems helpful to check the result of generating the SQL query string from php eg. echo $query (that should show the presumed error in the first query).
If reading the string does not spot the errors, feeding it via mysql into a test db might help a lot, especially. Mixing sql, php, single and double quotes is not always easy write nor read ...

Categories