Not a unique table/alias stock: - php

Ive got the query below :
$sql = "SELECT `scanners`.`KordNo`, `scanners`.`BundleNumber`
FROM `scanners`, `TWOrder`, `Stock`
INNER JOIN `TWORDER` ON `scanners`.`KordNo` = `TWOrder`.`KOrdNo`
AND `scanners`.`Date` = '" . $date . "'
INNER JOIN `Stock` ON `TWOrder`.`Product` =`Stock`.`ProductCode`
AND `Stock`.`ProductGroup` NOT BETWEEN 400 AND 650
AND `scanners`.`Scanner` IN (
ORDER BY `scanners`.`KordNo` ASC";
foreach($scanner as $x)
{$sql .= $x . ",";}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
$return[] = $row;
}
When i echo the sql on php my admin i get the error not a unique table/alias stock;
can someone advise?

Since you're using explicit JOINs, drop the other two tables off of the FROM clause.
...
FROM `scanners`
INNER JOIN `TWORDER` ON `scanners`.`KordNo` = `TWOrder`.`KOrdNo`
...

On line 2 you have...
FROM `scanners`, `TWOrder`, `Stock`
Then you have some INNER JOINs on to TWOrder and Stock.
That's mixing syntax (, and JOIN) which is messy. Stick to JOIN
It means that TWOrder and Stock are mentioned Twice in the query
If you REALLY need to include those table multiple times in one query, you need to give them alias names, so they can be distiguished from each other.
But I think it's probably a mistake and that Line 2 should just be
FROM `scanners`
Then, also, I'm not sure how you got that to compile. You have IN ( and then an ORDER BY clause, to which you append a list of values. You should append the list before the ORDER BY and then append the ORDER BY after you've finished the loop.

Related

Generate html table based on 2x mysql db queries

I'm trying to show stuff queried from two tables, but on one html table. Data is shown for the last 30 days, based on which, an html table is being generated.
Currently I'm stuck using two queries and generating two html tables:
$query1 = mysqli_query( $con, "SELECT date, stuff* " );
while( $record = mysqli_fetch_array( $query1 ) ){
echo '<html table generated based on query>';
}
$query2 = mysqli_query( $con, "SELECT date, other stuff*" );
while( $record = mysqli_fetch_array( $query2 ) ){
echo '<another html table generated based on query2>';
}
Is there a possibility to show both queries on one html table instead?
Note that it gets tricky since we have dates on one table which are not necessarily found in the second table or vice-versa.
Thanks for the support guys. So far I'm stuck at this:
SELECT * FROM user_visit_logs
LEFT JOIN surfer_stats ON user_visit_logs.date = surfer_stats.date
UNION
SELECT * FROM user_visit_logs
RIGHT JOIN surfer_stats ON user_visit_logs.date = surfer_stats.date
The query completes, but the 2nd table fields are all null:
Furthermore, it breaks when I add additional clause like:
WHERE user_id = '{$_SESSION['user_id']}' ORDER BY date DESC LIMIT 30
I think you are after FULL OUTER JOIN concept:
The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the right table (table2)
In which you may use common dates as a shared row.
So the query will get to simple one:
$query = "
SELECT table1.date, stuff
FROM table1
LEFT OUTER JOIN table2 ON table1.date = table2.date
UNION
SELECT table2.date, other_stuff
FROM table1
RIGHT OUTER JOIN table2
ON table1.date = table2.date
";
$result = mysqli_query( $con, $query );
while( $record = mysqli_fetch_array( $result ) ){
echo '<html table generated based on query>';
}
Example
This is an schematic diagram of FULL OUTER JOIN concept:
After running into quite a few bumps with this one, I finally managed to merge 2 columns from each table and also to use where and sort clauses on them with the following query:
( SELECT user_visit_logs.user_id,user_visit_logs.date,unique_hits,non_unique_hits,earned,sites_surfed,earnings FROM user_visit_logs
LEFT OUTER JOIN surfer_stats ON user_visit_logs.user_id = surfer_stats.user_id AND user_visit_logs.date = surfer_stats.date where user_visit_logs.user_id = 23 ORDER BY date DESC LIMIT 30 )
UNION
( SELECT surfer_stats.user_id,surfer_stats.date,unique_hits,non_unique_hits,earned,sites_surfed,earnings FROM user_visit_logs
RIGHT OUTER JOIN surfer_stats ON user_visit_logs.user_id = surfer_stats.user_id AND user_visit_logs.date = surfer_stats.date where user_visit_logs.user_id = 23 LIMIT 30 )
Simplified, "user_visit_logs" and "surfer_stats" were the 2 tables needed to be joined.
Absolutely. Just pop them both into a variable:
$data = '';
$query = mysqli_query($con,"SELECT date, stuff* ");
while($record = mysqli_fetch_array($query)) {
$data.= '<tr><td>--Your Row Data Here--</td></tr>';
}
$query2 = mysqli_query($con,"SELECT date, other stuff*");
while($record = mysqli_fetch_array($query2)) {
$data .= '<tr><td>--Your Row Data Here--</td></tr>';
}
echo "<table>$data</table>";
Instead of using echo in your loop, you're just storing the results in $data. Then, you're echoing it out after all data has been added to it.
As for your second point, it's not a big deal if fields don't exist. If they're null, you'll just have a column that doesn't have data in it.
Here's an example with fake column names:
$data = '';
$query = mysqli_query($con,"SELECT date, stuff* ");
while($record = mysqli_fetch_array($query)) {
$data.= "<tr><td>{$record[id]}</td><td>{$record[first_name]}</td><td>{$record[last_name]}</td></tr>";
}
$query2 = mysqli_query($con,"SELECT date, other stuff*");
while($record = mysqli_fetch_array($query2)) {
$data .= "<tr><td>{$record[id]}</td><td>{$record[first_name]}</td><td>{$record[last_name]}</td></tr>";
}
echo "<table><tr><th>ID</th><th>First Name</th><th>Last Name</th></tr>$data</table>";
I have a feeling I may have misunderstood the need. If so, I apologize. If you can elaborate just a bit more I can change my answer :)

JOIN in MySQL and relational tables error

I have three tables, "food","member" and "member_food". I'm trying to make an update user page where a collection of tags are prepopulated by the data in "member_food".
I have debugged the ID sending from the previous page which allows me to select the entry I wish to query, ID:4.
$query = "SELECT * FROM `food` left join `member_food` on food.entityid = member_food.food_id WHERE member_id = '$id'";
//Breakfast
$breakfastresult1 = $mysqli->query($query);
echo '<select name="breakfast1">';
while($BreakfastData1 = mysqli_fetch_array($breakfastresult1, MYSQL_ASSOC))
{
echo '<p><option value="' . htmlspecialchars($BreakfastData1['member_food.food_id']) . '">'
. htmlspecialchars($BreakfastData1['member_food.food_name'])
. '</option>'
. '</p>';
}
echo '</select>';
However, the select fields appear to be empty. I think it's not pulling the correct values from my leftjoin table.
Here is an example of my member_food table:
food table:
edit this, first you have a typo (space missing in left + join) second you need to tell from which of the table member_id belong
$query = "SELECT * FROM `food` as f left join `member_food` as mf on f.entityid = mf.food_id WHERE mf.member_id = '$id'";
You can use this to plan your joins correctly. And, as Abdul pointed out, typos are bad ;)

Codeigniter not showing proper results for array fetched by MySQL query.

I am working with Codeigniter with mysql databases,
I have a model function
public function get_all_data(){
$this->output->enable_profiler(TRUE);
$years = $this->input->post('year');
$months = $this->input->post('month');
$exec_ids = $this->input->post('exec_id');
$query = $this->db->query("SELECT * FROM client_booking AS cb
RIGHT OUTER JOIN executive_client_unit_relation AS ecur ON cb.id = ecur.booking_id
LEFT OUTER JOIN new_invoice ON cb.id = new_invoice.booking_id
WHERE ecur.executive_id IN (" . implode(',', $exec_ids) . ") AND MONTH(cb.booking_date) IN (" . implode(',', $months) . ") AND YEAR(cb.booking_date) IN (" . implode(',', $years) . ")");
return $query->result();
}
The sql generated by this is (as seen in the profiler) :
SELECT * FROM client_booking AS cb
RIGHT OUTER JOIN executive_client_unit_relation AS ecur ON cb.id = ecur.booking_id
LEFT OUTER JOIN new_invoice ON cb.id = new_invoice.booking_id
WHERE ecur.executive_id IN (4,5,6) AND MONTH(cb.booking_date) IN (1,2,3,4,5) AND YEAR(cb.booking_date) IN (2013,2014)
My problem is that the booking_id value is set to NULL when I var_dump() the result of this query.
On the other hand, when I run the SQL in my phpmyadmin, everything goes well and I can see the booking_id
PS: client_booking table's primary key is id which is the booking_id for all the other tables.
Can anyone help me to resolve this?
You are using LEFT/RIGHT joins so when there is no association found between your tables a null row will be returned ,second thing is your tables new_invoice and executive_client_unit_relation both have common names for the column name booking_id and in your select statement you are doing select * so for the columns with same name i guess the last one is picked which is null,for the solution you either you select only needed columns not all like SELECT cb.* or either the columns have same name with your query table then specify them individually with the alias you wish to provide but in the end of select statement in query like SELECT *,cb.id AS booking_id,....

How can I convert these two queries in a loop into a single JOINed query?

I am currently trying to get data from my table (mostKills by Weapon in a table with over 300 kills). Initially I did a normal query
$q = $mysql->query("SELECT * FROM `kills`") or die($mysql->error);
but when I tried to
$query2 = $mysql->query("SELECT `killerID`, COUNT(`killerID`) AS tot_kills FROM `kills` WHERE `killText` LIKE '%$gun%' GROUP BY `killerID` ORDER BY `tot_kills` DESC;") or die($mysql->error);
$kData = $query2->fetch_assoc();
$query3 = $mysql->query("SELECT `Username` FROM `players` WHERE `ID` = '" . $kData['killerID'] . "'") or die($mysql->error);
$uData = $query3->fetch_assoc();
$array[$gun]['Kills']++;
$array[$gun]['Gun'] = $gun;
$array[$gun]['BestKiller'] = $uData['Username'];
$array[$gun]['killAmount'] = $kData['tot_kills'];
function sortByKills($a, $b) {
return $b['Kills'] - $a['Kills'];
}
usort($array, 'sortByKills');
foreach($array as $i => $value)
{
// table here
}
I had to do it in a while loop, which caused there to be around 600 queries, and that is obviously not acceptable. Do you have any tips on how I can optimize this, or even turn this into a single query?
I heared JOIN is good for this, but I don't know much about it, and was wondering if you guys could help me
Try this...
I added a inner join and added a username to your select clause. The MIN() is just a way to include the username column in the select and will not have an impact on you result as long as you have just 1 username for every Killerid
SELECT `killerID`
, COUNT(`killerID`) AS tot_kills
, MIN(`Username`) AS username
FROM `kills`
INNER JOIN `players`
ON `players`.`id` = `kills`.`killerid`
WHERE `killText` LIKE '%$gun%'
GROUP BY `killerID`
ORDER BY `tot_kills` DESC
SELECT kills.killerID, count(kills.killerID) as killTotal, players.Username
FROM kills, players
WHERE kills.killText
LIKE '%$gun%'
AND players.ID` = kills.killerID
GROUP BY kills.killerID
ORDER BY kills.tot_kills DESC
Here is a good place to learn some more about joins.
http://www.sitepoint.com/understanding-sql-joins-mysql-database/
The best way is to have your own knowledge so you can be able to tune up your select queries.
Also put more indexes to your DB, and try to search and join by index.

Help construct a simple query Using 3 tables

Hey guys need some more help
I have 3 tables USERS, PROFILEINTERESTS and INTERESTS
profile interests has the two foreign keys which link users and interests, they are just done by ID.
I have this so far
$statement = "SELECT
InterestID
FROM
`ProfileInterests`
WHERE
userID = '$profile'";
Now I want it so that it selects from Interests where what it gets from that query is the result.
So say that gives out 3 numbers
1
3
4
I want it to search the Interests table where ID is = to those...I just don't know how to physically write it in PHP...
Please help.
Using a JOIN:
Best option if you need values from the PROFILEINTERESTS table.
SELECT DISTINCT i.*
FROM INTERESTS i
JOIN PROFILEINTERESTS pi ON pi.interests_id = i.interests_id
WHERE pi.userid = $profileid
Using EXISTS:
SELECT i.*
FROM INTERESTS i
WHERE EXISTS (SELECT NULL
FROM PROFILEINTERESTS pi
WHERE pi.interests_id = i.interests_id
AND pi.userid = $profileid)
Using IN:
SELECT i.*
FROM INTERESTS i
WHERE i.interests_id IN (SELECT pi.interests_id
FROM PROFILEINTERESTS pi
WHERE pi.userid = $profileid)
You are on the right track, lets say you execute the query above using this PHP code:
$statement = mysql_query("SELECT InterestID FROM `ProfileInterests`
WHERE userID = '$profile'");
Then you can use a PHP loop to dynamically generate an SQL statement that will pull the desired IDs from a second table. So, for example, continuing the code above:
$SQL = "";
while ($statementLoop = mysql_fetch_assoc($statement)) {
//Note the extra space on the end of the query
$SQL .= "`id` = '{$statementLoop['InterestID']}' OR ";
}
//Trim the " OR " off the end of the query
$SQL = rtrim($SQL, " OR ");
//Now run the dynamic SQL, using the query generated above
$query = mysql_query("SELECT * FROM `table2` WHERE {$SQL}")
I haven't tested the code, but it should work. So, this code will generate SQL like this:
SELECT * FROM `table2` WHERE `id` = '1' OR `id` = '3' OR `id` = '4'
Hope that helps,
spryno724
Most likely you want to join the tables
select
i.Name
from
ProfileInterests p
inner join
interests i
on
p.interestid = i.interestid
where
p.userid = 1

Categories