mysql syntax error on performing a ranking query - php

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;
}

Related

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

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.

Same query works different

I made php script that updates database:
<?php
include 'config.php';
$PauseID = "2";
$ProductionID = "1411979966";
$sql = "SET #max = (SELECT MAX(Id) FROM tblproductionbreaks); UPDATE tblproductionbreaks SET IDPause = '$PauseID' WHERE ProductionID = '$ProductionID' AND Id = #max;";
mysql_query($sql) or die(mysql_error());
mysql_close($connect);
?>
While executing this script it returns 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 'UPDATE tblproductionbreaks SET IDPause = '2' WHERE ProductionID
= '1411979966' A' at line 1
But if I try same update query execute by command line it works
SET #max = (SELECT MAX(Id) FROM tblproductionbreaks); UPDATE tblproductionbreaks SET IDPause = '2' WHERE ProductionID = '1411979966' AND Id = #max;
I don't understand how the same thing works differently.
You can not run multiple queries as one statement with PHP. Try like this:
$sql = "UPDATE tblproductionbreaks SET IDPause = '$PauseID' WHERE ProductionID = '$ProductionID' ORDER BY Id DESC LIMIT 1;";
You don't need this variable anyway.
Its is because your PHP interpreter treats your $sql as string. Change your code to
$sql = "UPDATE tblproductionbreaks SET IDPause = '{$PauseID}' WHERE ProductionID = '{$ProductionID}' AND Id = (SELECT MAX(Id) FROM tblproductionbreaks)";
Also you can debug it by echo $sql and see what actually the $sql returning

Comparing two values set in MySQL table php

I have a mysql table that has 2 columns, claim_status and show (both VARCHAR(500)) I tested with int didn't work.
I want to query only the items that have claim_status='0' and show='1'
right now nothing is returned here is my PHP code:
$query = "SELECT COUNT(*) as num FROM $tableName WHERE claim_status='0' AND show='1'";
$query1 = "SELECT * FROM $tableName WHERE claim_status='0' AND show='1'";
** it fails on this line **
$query = "SELECT COUNT(*) as num FROM $tableName WHERE claim_status=0 AND show=1";
$query = SELECT * FROM tablename WHERE claim_status='0' AND show='1';
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}

PHP - How to Use ORDER BY and GROUP BY together

I created a table that contains message, sender, to, time I want group by sender and order by time this is my code
$query= mysql_query("SELECT * FROM `table` ORDER BY `time` GROUP BY `sender`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr ['message'];
echo '</br>';
echo $msg;
}
that shows me 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 'GROUP BYsender' at line 1
So how to fix that problem?
Thanks
Klaus
Note your precedence. After the results have been grouped , it should be ordered.
"SELECT * FROM `table` GROUP BY `sender` ORDER BY `time`"
try this code
$query= mysql_query("SELECT * FROM `table` GROUP BY `sender` ORDER BY `time` ")or die(mysql_error());
// ^^--will be before order
$num = mysql_num_rows($query); // out of the while loop
while($arr = mysql_fetch_array($query)){
$msg = $arr['message'].'<br />';
// ^^--remove space here
echo $msg;
}
how to use self-joins to get the max/min/something-n rows per group.
In your situation, it can be applied to the effect you want like so:
SELECT * FROM
(SELECT group_id, MAX(`yourdate`) AS yourdate FROM tbl_name GROUP BY group_id)
AS x JOIN tbl_name USING (`group_id`,yourdate);

Pass column value from Select query to another query for insertion in PHP

I was thinking of accomplishing the following as a PHP multi_query. But I'm trying to figure out how to pass the column value from the select query to the insert and update queries.
$query = "SELECT tbl_links.link, link_id
FROM tbl_links
INNER JOIN tbl_items ON tbl_links.item_id = tbl_items.item_id
WHERE tbl_items.item_name like '".$items_name[$counter]."'
AND NOT EXISTS (
select link_id
from tbl_clickedlinks
where tbl_clickedlinks.link_id = tbl_links.link_id
AND tbl_clickedlinks.cust_id = '$items_custID[$counter]'
)
limit 0, 1;" ;
$query .= "INSERT INTO tbl_claimedlinks (cust_id, link_id, claim_time) VALUES ('$items_custID', $row['link_id'], NOW()) ;";
$query .= "UPDATE tbl_links SET click_count = click_count+1 where link_id = '$linkID' ;";*/
Problem is, I'm not sure how to pass the link_id value to the other queries. So I'm thinking I might have to rearrange the queries into one, but again, I'm just not sure how to pull that off.
Anyone got any suggestions?
You need to execute select query 1st then use its output to execute 2nd & 3rd query.
$query = "SELECT tbl_links.link, link_id
FROM tbl_links
INNER JOIN tbl_items ON tbl_links.item_id = tbl_items.item_id
WHERE tbl_items.item_name like '".$items_name[$counter]."'
AND NOT EXISTS (
select link_id
from tbl_clickedlinks
where tbl_clickedlinks.link_id = tbl_links.link_id
AND tbl_clickedlinks.cust_id = '$items_custID[$counter]'
)
limit 0, 1;" ;
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$query2 = "INSERT INTO tbl_claimedlinks (cust_id, link_id, claim_time) VALUES ('$items_custID', $row['link_id'], NOW()) ;";
$query3 = "UPDATE tbl_links SET click_count = click_count+1 where link_id = '$linkID' ;";*/
mysql_query($query2);
mysql_query($query3);
}

Categories