getting specific columns from three tables - php

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.

Related

How to subtract data from one sql table from another in 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 ?.

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

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

Mysql query for using count on a view in php

I have a query:
$result = mysql_query("CREATE VIEW temporary(IngList) AS (
SELECT DISTINCT (r1.Ingredient)
FROM recipes r1,
recipes r2
WHERE r1.Country = '$temp'
AND r2.Country = '$temp2'
AND r1.Ingredient = r2.Ingredient)
SELECT COUNT(*) FROM temporary");
I want the query to make a view called temporary and have it return a count of the number of rows in the view temporary. I know this code works without the SELECT COUNT(*) because I checked my database and the view is created.
Yet this code throws the 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 'SELECT COUNT(*) FROM temporary' at line 1
I checked the syntax and it seems to be correct. What seems to be the problem because its quite frustrating.
From the mysql_query documentation:
mysql_query() sends a unique query (multiple queries are not supported)...
You can't create the view, and select from it in a single mysql_query. The view is unnecessary:
$sql = sprintf("SELECT COUNT(DISTINCT r1.Ingredient)
FROM recipes r1
WHERE r.country = '%s'
AND EXISTS(SELECT NULL
FROM recipes r2
WHERE r2.Country = '%s'
AND r1.Ingredient = r2.Ingredient)",
$temp, $temp2);
$result = mysql_query($sql);
For starters you have two statements. What you're writing looks more like a stored procedure. Even if it worked, you would need a semicolon at the end of the first statement. And another statement somewhere saying "DROP VIEW ...." when you are done.
And a temp view is a bit of a non sequitur. I can't find any reference to "CREATE VIEW temporary". Or maybe it's to create a view named temporary with an argument? Views don't take arguments.
I think you might get what you want with a semi-simple SQL statement something like:
$result = mysql_query(
"SELECT COUNT(DISTINCT r1.Ingredient)
FROM recipes r1
JOIN recipes r2 ON r1.Ingredient = r2.Ingredient
WHERE r1.Country = '$temp'
AND r2.Country = '$temp2'");

Categories