Mysql querys over multiple tables - php

This code pulls together a list of members then lists all the items they have added in a category and then outputs all this information to a table.
Here's the 3 table layouts:
Members
member_id - fname - lname - etc.
Items
member_id - item_id - etc.
Categories
name - etc.
And the current code which takes FOREVER to load:
<?php $sql="SELECT * FROM members ORDER BY lname, fname ASC";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){ ?>
<? echo('Name'); ?>
<? echo $rows[fname];?> <? echo $rows[lname];?>
<? $sql2="SELECT * FROM leadtypes ORDER BY name ASC";
$result2=mysql_query($sql2);
while($rows2=mysql_fetch_array($result2)){ ?>
<? echo $rows2[name];?>
<? echo(': '); ?>
<? $sql4="SELECT lead_id FROM leads WHERE member_id='$rows[member_id]' AND type='$rows2[name]' ORDER BY name ASC";
$result4=mysql_query($sql4);
$num4 = mysql_num_rows($result4); ?>
<? echo $num4;?>
<? } ?>
<? } ?>`
I know I shouldn't query * but this is a very stripped down piece of code on a test server. I would be grateful If somebody knows a good way of combining all this together to speed up the system.

Try this
$sql = SELECT A.lead_id,B.name,C.fname,C.lname
FROM leads A
JOIN leadtypes B ON A.type = B.name
JOIN members C ON A.member_id = C.member_id
You can echo this as
$rs = mysql_query($sql);
while($rows = mysql_fetch_array($rs)){
echo $row['name'];
echo $row['fname'];
}
Have a look at these links
http://www.w3schools.com/sql/sql_join.asp
http://dev.mysql.com/doc/refman/5.0/en/join.html

Try doing one join instead of multiple queries. For example,
SELECT lt.*, l.lead_id FROM leadtypes lt, leads l WHERE l.member_id=lt.member_id AND l.type=lt.name ORDER BY l.name ASC
If that one query is still slow then it means you need to add indices on your tables.

Related

How to echo second column with only the primary key - SQL/PHP

I'm trying to create a fixture list for a football competition currently, and i have been stuck with trying to display something like "team1name V team2name".The tables that i am trying to pull the data from are:
Team
teamID
teamname
Fixtures
hometeam
awayteam
The sql query I have written up is:
$sql = "SELECT homeTeam, awayTeam, roundID, teamID, teamName, logo, groundName, abbreviatedName, matchDate, matchTime, venue
FROM fixtures
INNER JOIN team ON fixtures.homeTeam = team.teamID
INNER JOIN ground ON ground.groundID = team.groundID";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error());
and the PHP code which i have been using to display this data is:
<?php
while ($row = mysqli_fetch_array($results))
{
?>
<tr>
<td><?php echo $row ["teamName"]?></td>
<td> V </td>
<td><?php echo $row ["teamName"]></td>
</tr>
<?php
}
mysqli_close($conn);
?>
I understand i am calling teamname twice and hence why i am getting the same name displayed, but i am unsure as to how to get my code to differentiate the two IDs and names. Any help would be greatly appreciated
This is just a SQL problem. You need to join team twice, once for home team and once for away team.
SELECT homeTeamID, awayTeamID, homeTeam.teamID homeTeamID,
awayTeam.teamID awayTeamID, homeTeam.teamName homeTeamName,
awayTeam.teamName awayTeamName
FROM fixtures
INNER JOIN team homeTeam ON fixtures.homeTeam = homeTeam.teamID
INNER JOIN team awayTeam ON fixtures.awayTeam = awayTeam.teamID
INNER JOIN ground ON ground.groundID = team.groundID
By naming the selects, you can use the separately in your PHP code.
<?php echo $row['homeTeamName']; ?> v <?php echo $row['awayTeamName']; ?>

Why does one of my column shows empty?

I have my table that one of my column shows empty. It has the column of Id, Date, Cust name, Product + Qty, and amount. But only in Product + Qty shows empty even it has data in database.
PHP code
<?php
include('connect.php');
$start = isset($_GET['d1']) ? $_GET['d1'] : '';
$end = isset($_GET['d2']) ? $_GET['d2'] : '';
if(isset($_GET['submit']) && $_GET['submit']=='Search')
{
$result = mysql_query(
"SELECT
t1.qty,
t2.lastname,
t2.firstname,
t2.date,
t3.name,
t2.reservation_id,
t2.payable FROM prodinventory AS t1
INNER JOIN reservation AS t2
ON t1.confirmation=t2.confirmation
INNER JOIN products AS t3
ON t1.room=t3.id
WHERE str_to_date(t2.date, '%d/%m/%Y') BETWEEN
str_to_date('$start', '%d/%m/%Y') AND
str_to_date('$end', '%d/%m/%Y')
GROUP BY t2.confirmation") or die(mysql_error());
while ($row = mysql_fetch_array($result)){
echo'<tr class="record">';
echo '<td>'.$row['reservation_id'].'</td>';
echo '<td>'.$row['date'].'</td>';
echo '<td>'.$row['firstname'].' '.$row['lastname'].'</td>';
echo '<td><div align="left">';
$rrr=$row['confirmation'];
$results = mysql_query("SELECT * FROM prodinventory where confirmation='$rrr'");
while($row1 = mysql_fetch_array($results))
{
$roomid=$row1['room'];
$resulta = mysql_query("SELECT * FROM products where id='$roomid'");
while($rowa = mysql_fetch_array($resulta))
{
echo $rowa['name'].' x';
}
echo ' '.$row1['qty'].'<br>';
}
echo '<td>'.'PHP ' . number_format(floatval($row['payable']));
}
?>
Hmmmm I have deleted my answer but noone tried so...
I think this echo ' '.$row1['qty'].'<br>'; is the row you asked about. And all this looks like a typo. If this is the case:
You have no confirmation in the SELECT clause (it's used only in JOIN and GROUP BY) and it possible your $rrr to be blank. Echo it to be sure there is a value.
Check does your query works and return results. Echo the query string (or take it from the mysql log file) and test it.
You have SELECT *. Is the field name 'qty' correct in a case-sensivity environment? 'Qty' may be different and the query may work but you don't get the result.
i think that's because you have inner join and maybe the intersection tables have no data
try to do left join first if it works
insure that all of tables have data in it

i want to count specific IDs from my tables

i have this code
<?php
$votes_query=mysql_query("select * from votes where CandidateID='$id'");
$vote_count=mysql_num_rows($votes_query);
echo $vote_count;
?>
which fetches individual *ID*s from my votes table.
I need a code which can help fetch the sum of specific *ID*s.
Lets say, I have ID-205 and ID-209 in my table.
<?php
$ids = array('205','209');
$votes_query=mysql_query("select * from votes where CandidateID IN($ids) ");
$vote_count=mysql_num_rows($votes_query);
echo $vote_count;
?>
Put all ID's in an array & Use IN Clause of mysql.
<?php
$ids = array('205','209');
$sql "SELECT SUM(field_score) AS vote_score FROM votes WHERE CandidateID IN ($ids)";
$vote_score = mysql_query($sql);
echo $vote_score;
?>

Extracting member's first name from member table using results from another table

<?php
include 'dbFunctions.php';
$courseid = $_GET['Course_id'];
$query = "SELECT * FROM course WHERE Course_id=".$courseid."";
$arrCourse = executeSelectQuery($query);
$query2 = "SELECT * FROM course_member WHERE Course_id=".$courseid."";
$result = mysqli_query($link,$query2) or die(mysqli_error($link));
?>
HTML body:
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<?php echo $row['member_id']
?>
<?php
}
?>
this correctly prints the results of the member id that is involved in the selected course, however, i want to extract the first_name using the result generated that belong to another table called member.
been trying all the join queries but it didn't work.
Sounds like you need to read up on the JOIN operation in SQL. The following query will return all the data you seem to need, from a single query:
SELECT *
FROM course
INNER JOIN course_member ON course.id = course_member.course_id
INNER JOIN member ON member.id = course_member.member_id
As far as I see
$sql="select last_name from course_member
join member on course_member.member_id = member.member_id
where course_member.Course_id = ".$courseid;
I'm going to take a guess here at your table defs...
$query2 = "SELECT m.first_name, cm.* FROM course_member cm join member m on m.id = cm.member_id WHERE Course_id=".$courseid."";
If you want only the member name and you are not much interested with the id then you can merge it into a single query
$query = SELECT fName from member WHERE id = (SELECT member_id FROM course_member WHERE Course_id=$courseid);

Populate Checkboxes on Edit Form

I have an edit page that gets populated when accessed. The input values work fine, but I'm having a hard time ticking the category checkboxes. I get the information from two tables. One that displays all the categories and the other one that gets the categories associated with the item.
The following code doesn't work because the second while statement finishes its loop in the first round. Is there an appropriate way to do this?
<?php $check_cats = mysql_query("SELECT * FROM item_categories WHERE itemid = '$itemid'") or die(mysql_error()); ?>
<?php $result = mysql_query("SELECT * FROM categories ORDER BY cname") or die(mysql_error()); ?>
<?php while($row = mysql_fetch_array( $result )) { ?>
<input type="checkbox" id="<?php echo $row['cname']; ?>" name="cat[]" value="<?php echo $row['id']; ?>"
<?php while($check_cat_rows = mysql_fetch_array( $check_cats )) {
if ($check_cat_rows['catid'] == $row['id']) {
echo 'checked="yes"';
}
}
} ?>
My Two tables:
TABLE `item_categories`
`id`
`itemid`
`catid`
TABLE `categories`
`id`
`cname`
Your basic structure could use improvement. Rather than two separate queries, and two nested loops, you could be using a single query which JOINS to the two tables together. Part of the joined data would be the "checked" flag, which you can check for within the loop and output the appropriate html.
SELECT ..., categories.id AS checked
FROM item_categories
LEFT JOIN categories
ON (item_categories.catid = categories.id)
and then while looping:
while($row = mysql_fetch_assoc()) {
$flag = ($row['checked') ? ' checked="yes"' : ''
...
}
Your whole thing is structured incorrectly, you can't assume the two results will line up perfectly, and your loops are wrong. Try this:
SELECT *,
(case when id IN
(SELECT catid FROM item_categories WHERE itemid = '$itemid')
then 1 else 0 end) checked
FROM categories ORDER BY cname
Now you just run the one query and have a nice little $row['checked'] to use!
SELECT *,
(case when categories.id IS NOT NULL
then 1 else 0 end) checked
FROM item_categories
LEFT JOIN categories
ON (item_categories.catid = categories.id)
WHERE itemid = '$itemid'
Improved based on hybrid between marc B and mine... Only efficiency difference is that the query handles testing the validity of categories.id instead of the php
I don't really understand your question, but you want the check box to be checked when the page loads? In that case you have to add "checked" to the tag
<input type="checkbox" name="option2" value="Butter" checked>
Something like this?
<?php
$query = <<<query
SELECT
c.id,
c.cname,
ifnull(ic.catid, '', 'checked="yes"') as checked
FROM
categories c
LEFT JOIN item_categories ic
ON ic.itemid = '$itemid'
AND ic.catid = c.id
ORDER BY
c.cname
query;
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) { ?>
<input type="checkbox" id="<?=$row['cname'];?>" name="cat[]" value="<?=$row['id'];?>" <?=$row['checked'];?>>
<?
}
?>

Categories