How to subtract data from one sql table from another in php? - php

I have created mobile game, I store score data(minerals in this case) in sql table. Now I want to create daily score chart by subtracting yesterday scores from scores two days old. I have found that I can do it with EXCEPT but nothing I try works.
$sql = "SELECT playerid, playername, minerals, daydate
FROM dailyscore WHERE daydate = '".$yesterday."'
EXCEPT
SELECT playerid, playername, minerals, daydate
FROM dailyscore WHERE daydate = '".$twodays."'
ORDER BY minerals DESC";
I get this error: SQL 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 'EXCEPT SELECT playerid, playername, minerals, daydate FROM dailyscore WHERE da' at line 3"

There is no need for set operators like EXCEPT or MINUS. Just calculate the difference of the daily scores by joining the scores of the two days:
SELECT playerid, playername, minerals
FROM (
SELECT ds_yesterday.playerid,
ds_yesterday.playername,
CASE
WHEN ds_twodays.minerals IS NULL
THEN ds_yesterday.minerals
ELSE ds_yesterday.minerals - ds_twodays.minerals
END minerals
FROM dailyscore as ds_yesterday
LEFT JOIN dailyscore as ds_twodays ON
ds_twodays.playerid = ds_yesterday.playerid
AND ds_twodays.daydate = '2018-08-07'
WHERE ds_yesterday.daydate = '2018-08-08'
) scoredifference
ORDER BY minerals DESC;
You can use this SQL and place it in your PHP code. Dates should be replaced by the values stored in the PHP variables.

MySQL doesn't support EXCEPT. I think you an use:
SELECT ds.playerid, ds.playername, ds.minerals, ds.daydate
FROM dailyscore ds
WHERE daydate = '".$yesterday."' AND
NOT EXISTS (SELECT 1
FROM dailyscore
WHERE ds2.playerid = ds.playerid AND
ds2.minerals = ds.minerals AND
ds2.daydate = '".$twodays."'
)
ORDER BY ds.minerals DESC;
Note: You shouldn't be passing in parameters by munging strings. You should learn to pass in parameters correctly, using placeholders such as ?.

Related

getting specific columns from three tables

I need to get specific columns from three tables through joins.every time it goes wrong.my code is
$saf=mysqli_query($db , "select pod.mobile, tpaidamount.Aptdate, follow.cent, pdate, time from pod,tpaidamount, follow where tpaidamount.pid = follow.pid and pod.Customer Id = tpaidamount.pid and pod.Customer Id =follow.pid ");
$i=1;
while($sfg=mysqli_fetch_assoc($saf) or die(mysqli_error($db)))
;
?>
pod,tpaidamount,follow are tables and other coloumns
Getting 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 'Id = tpaidamount.pid and pod.Customer Id =follow.pid' at line 1
is it a typo? Is setfollowup.pid or follow.pid?
select pod.mobile, tpaidamount.Aptdate, follow.cent, <table>.pdate, <table>.time
from pod, tpaidamount, follow
where tpaidamount.pid = follow.pid
and pod.`Customer Id` = tpaidamount.pid
and pod.`Customer Id` = follow.pid
You shouldn't Ever create columns names with spaces. The name: "pod.Customer Id" is a Bad attribute name, and you need to avoid use names like datatypes (or any SGBD reserved word) like: 'date', 'time', 'char', 'table', 'column'....
However, if you need to do it, try this SQL:
SELECT p.mobile
, t.Aptdate
, f.cent
, ???.pdate
, ???.`time`
FROM pod AS p
JOIN tpaidamount AS t ON o.`Customer Id` = t.pid
JOIN follow AS f ON t.pid = f.pid ON p.`Customer Id` = f.pid
Use alias for easy coding SQL queryes. Ex: table_name AS tn, table_a_name AS tan.
!!! I sugest you to watch some basic SQL Lessons.
Good Luck.

Mysql query returns error #1093 - You can't specify target table

I need to check and update with same query my database.
The error says it is not possble to update same table which is included in the select statement. Is there any workaround of this to happen in 1 mysql query? Here is the query:
$query='update option_values_to_products set available="0" where id in (
select ovtp.id from option_values ov,option_values_to_products ovtp,options o where
ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and
o.name="Size" group by ovtp.id )';
Yes, this is a nagging feature of mysql and there is a workaround to it: wrap the subquery within the IN() clause into another subquery.
update option_values_to_products set available="0" where id in (select id from (
select ovtp.id from option_values ov,option_values_to_products ovtp,options o where
ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and
o.name="Size" group by ovtp.id ) as t)
Avoid using nested queries for many reasons like performance and memory issue, also it can be very hard to be understood for the next developers
Good practice Split your query into 2 parts :
<?php
$qSelect = 'select ovtp.id from option_values ov,option_values_to_products ovtp,options o where
ovtp.product_id="1657" and ovtp.option_values_id=ov.id and ov.options_id=o.id and
o.name="Size" group by ovtp.id';
$res = DATABASE_MANAGER::exec($qSelect);
$qUpdate = 'update option_values_to_products set available="0" where id in (' . implode(",", $res) .')';
$res2 = DATABASE_MANAGER::exec($qUpdate);

PHP Prepared Statement variable binding error with subquery

I have a query with a few subqueries like so
SELECT ...
FROM (SELECT ...
FROM ...
GROUP BY ...) as speedLimitCalc INNER JOIN
(SELECT ...
FROM date a INNER JOIN HOURLY_TEST b ON a.[FULL_DAY_DT] = b.DATE
WHERE (b.DATE BETWEEN '".$date_s."' AND '".$date_e."')
AND HOUR BETWEEN ".$time_s." AND ".$time_e."
AND(LKNO BETWEEN '".$lkno_s."' and '".$lkno_e."')
AND RDNO= '".$rdno."'
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (".$dayquery.")
GROUP BY RDNO, LKNO, PRESCRIBED_DIRECTION, CWAY_CODE) as origtable ON ...
,(SELECT ...
FROM [Dim_date]
WHERE (FULL_DAY_DT BETWEEN '".$date_s."' AND '".$date_e."')
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (".$dayquery.") ) as c
ORDER BY ...
where I am inserting variables in the inner query where clause.
I am trying to parametrize this query using odbc_prepare and odbc_execute, however I am running into issues of binding the variables. At present, when I use the following
$result = odbc_prepare($connection, $query);
odbc_execute($result)or die(odbc_error($connection));
to run this query, everything works fine. However, when I try to bind a variable, such as
AND RDNO= ?
...
odbc_execute($result, array($rdno))or die(odbc_error($connection));
I get the following error message.
PHP Warning: odbc_execute() [/phpmanual/function.odbc-execute.html]: SQL error: [Microsoft][ODBC SQL Server Driver]Invalid parameter number, SQL state S1093 in SQLDescribeParameter
My guess is that it's because I'm binding a variable in a subquery, since this procedure works when the Where clause is in the top Select query.
I was wondering whether anyone else has encountered this issue before, and how they solved it? Thanks
Fixed the issue by removing the need for parameters in the subquery by separating the query into multiple queries using temporary tables.
$query = "SELECT ...
INTO ##avgspeedperlink
FROM Date a INNER JOIN HOURLY_TEST ON a.[FULL_DAY_DT] = b.DATE
WHERE (b.DATE BETWEEN ? AND ?)
AND HOUR BETWEEN ? AND ?
AND(LKNO BETWEEN ? and ?)
AND RDNO= ?
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (?,?,?,?,?,?,?)
GROUP BY RDNO, LKNO, PRESCRIBED_DIRECTION, CWAY_CODE";
$result = odbc_prepare($connection, $query);
odbc_execute($result, array($date_s,$date_e,$time_s,$time_e,$lkno_s,$lkno_e,$rdno,$daysanitised[0],$daysanitised[1],$daysanitised[2],$daysanitised[3],$daysanitised[4],$daysanitised[5],$daysanitised[6]))or die(odbc_error($connection));
$query = "SELECT ...
INTO ##daysinperiod
FROM [RISSxplr].[dbo].[Dim_date]
WHERE (FULL_DAY_DT BETWEEN ? AND ?)
AND pub_hol IN (".$pubholquery.")
AND school_hol IN (".$schholquery.")
AND day_no IN (?,?,?,?,?,?,?)";
$result = odbc_prepare($connection, $query);
odbc_execute($result, array($date_s,$date_e,$daysanitised[0],$daysanitised[1],$daysanitised[2],$daysanitised[3],$daysanitised[4],$daysanitised[5],$daysanitised[6]))or die(odbc_error($connection));
$query = "SELECT ...
FROM ##avgspeedperlink, ##daysinperiod
ORDER BY LKNO, OUTBOUND
drop table ##avgspeedperlink
drop table ##daysinperiod";
Note that I had to use double ## for making the temporary tables (single # means that table is local to the query, ## means that the temporary table becomes global for multiple queries).

Can't insert query result into table using PHP

I am trying to insert some information to a new table in my database. For this I query information from two tables and a xref table, then I try to do the insert as I usually do. This is not working.
Here is the code,
$query = "select listaA.product_s_desc, category_name, listaA.product_desc, listaA.product_sku
from listaA, jos_vm_category, jos_vm_product_category_xref
where listaA.product_id = jos_vm_product_category_xref.product_id
and jos_vm_category.category_id = jos_vm_product_category_xref.category_id limit 10";
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die;
do{
$imagen = 'http://accesoriosazteca.mx/imagesite/'.$row['listaA.product_sku'].".png";
mysql_query("insert into lista_importat (id, activo, sku, nombre, categoria, descripcion_corta, descripcion_larga, pedidos, mostrar_precio, imagen)
values ('$row['listaA.product_id']', '1', '$row['listaA.product_sku']', '$row['listaA.product_s_desc']', '', '$row['listaA.product_s_desc']', '$row['listaA.product_desc']', '0', '0', '$imagen')");
}while($row = mysql_fetch_array($result));
With the code above I get a blank screen, and nothing is inserted into the new table. Any ideas?
If the query starting...
select listaA.product_s_desc, ...
returns a resultset, the first column in the resultset will have a column name of product_s_desc, not listaA.product_s_desc.
(Running the query in the mysql command line client will demonstrate this behavior.)
To reference to the value of that column in $row:
$row['product_s_desc']
Note that the query does not return a column with a name of listaA.product_id.
A few notes, beyond answering the question you asked:
For the benefit of readers, I recommend you ditch the old school comma syntax for the join operation and use the JOIN keyword in it's place, and relocate the join predicates from the WHERE clause to an ON clause. I also recommend the use of short table aliases, and also qualifying ALL column references. For example:
SELECT a.product_s_desc
, c.category_name
, a.product_desc
, a.product_sku
FROM listaA a
JOIN jos_vm_product_category_xref r
ON r.product_id = a.product_id
JOIN jos_vm_category c
ON c.category_id = r.category_id
ORDER BY 1
LIMIT 10

PHP MySQL - selecting values from table 1 which are not in table 2

This may be simple to solve but I'm having trouble with this piece of code - I'm a self taught newbie with PHP, and the code I've come up with doesn't seem to want to work.
The pages are for an online entry system for a sports competition. Judges' details are stored in table "club_judges", and users can enter them into a competition by copying them into "competition_judges". This is done via a checkbox form in a table.
I want to add functionality whereby judges who are already added to the competition do not appear in the import form, however my code does not seem to work. I am using a unique field of "bg_number" (the sport's identification number) to search for an existing entry.
Current code:
$existing_judges = mysql_query("SELECT bg_number FROM competition_judges WHERE competition='Test Competition'");
$existing_judges_fetch = mysql_fetch_array($existing_judges);
$existing_judges_array = "('" . implode( "', '", $existing_judges_fetch ) . "');" ;
$query = "SELECT * FROM club_judges WHERE (`club`='Test Club') AND (`bg_number` NOT IN '$existing_judges_array') ORDER BY name ";
$result = mysql_query($query) or die(mysql_error());
Error displayed:
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 ''('1234567', '1234567');') ORDER BY name' at line 1
For reference 1234567 is the bg_number for my test judge.
Any help would be greatly appreciated!
why dont u use just one query
SELECT *
FROM club_judges
WHERE `club`='Test Club'
AND `bg_number`
NOT IN (SELECT bg_number FROM competition_judges WHERE competition='Test Competition')
ORDER BY name
Use can use a single query instead like this:
$query = "SELECT * FROM `club_judges` WHERE `club`='Test Club'
AND
`bg_number` NOT IN
(SELECT `bg_number` FROM `competition_judges` WHERE `competition`='Test Competition')
ORDER BY `name` ";
$existing_judges_fetch = mysql_fetch_array($existing_judges);
$result = mysql_query($query) or die(mysql_error());
here's a JOIN version
SELECT a.*
FROM club_judges a
LEFT JOIN competition_judges b
ON a.bg_number = b.bg_number AND
b.competition='Test Competition'
WHERE b.bg_number IS NULL AND
a.club = 'Test Club'
ORDER BY a.name
To fully gain knowledge about joins, kindly visit the link below:
Visual Representation of SQL Joins

Categories