Echo rows via JOIN in MySQL/PHP (?) - php

I wanna be able to echo out if Groupname and Username are connected correctly, where the current userid (saved in a session) is $uid.
I've been sitting for hours trying all kinds of JOINs and the closest I've gotten is having it output 1/? members for each team, but not all of them.
EDIT:
$uid = $_SESSION['uid'];
$sql = "SELECT * FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user
INNER JOIN usergroup ON user.userid=usergroup.userid
WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
$row2 = mysqli_fetch_array($result2);
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
Thing is, that it kinda works well, except that it doesn't print all the groupmembers names out, it prints out just one. Which one seems to depend on the order in the table.

You did not have a loop on the second query's resultset. However, it is not needed to have a second SQL query. Just do it in one go; SQL was designed for that.
Also, you'll have much simpler code:
$uid = $_SESSION['uid'];
// Select everything you need in one go (join user table as well)
$sql = "SELECT group.group_id, group.groupname, user.username
FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
INNER JOIN user ON user.userid=usergroup.userid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
// Don't need to call mysqli_num_rows if you continue like this:
while($row = mysqli_fetch_array($result)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
Maybe you want to echo some <tr> and </tr> tags, or you"ll have everything in one row, like:
echo "<tr><td>".$row['groupname']."</td>"
."<td>".$row['username']."</td>"
."<td>".$row['groupid']."</td></tr>";

There you go: (you were missing nested while loop)
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user INNER JOIN usergroup ON user.userid=usergroup.userid WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
if(mysqli_num_rows($result2)>0) {
while($row2 = mysqli_fetch_array($result2)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
}
}
Side note: You could achieve the same results with just one SQL query, something like:
SELECT
*
FROM
usergroup ug
INNER JOIN
user u ON ug.userid = u.userid
GROUP BY
ug.id
and then in PHP (pseudo code just, do not copy-n-paste)
while($row => mysqli_fetch_array($result)) {
if (!isset($groupsWithUsers[$row['groupid']['users'])) {
$groupsWithUsers[$row['groupid']['users'] = array()
}
$groupsWithUsers[$row['groupid']['users'][$row['userid']] = $row;
}

Related

Displaying name from an inner joined table?

I've got two tables, one called category, which has the rows id and name, and another called placecategory, which has the tables id, place_id and category_id. I need to inner join these two to echo out the names of the categories where the placecategory.place_id is equal to a $GET[ID].
I've got this so far, but it echo's out nothing.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name FROM category
INNER JOIN placecategory
ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id.'';
$result = mysqli_query($dbc,$qry);
while ($row = mysqli_fetch_array($result))
{
echo ''.$row['name'].'';
};
?>
This wont fix your query, but it will display the error generated by the incorrect query. Its a start.
I cannot solve the query issue without a better understanding of your schema.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name
FROM category
INNER JOIN placecategory ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id;
$result = mysqli_query($dbc,$qry);
// test the status before continuing
if ( ! $result ) {
echo mysqli_error($dbc);
exit;
}
while ($row = mysqli_fetch_array($result))
{
echo $row['name'];
}
?>

obtaining comments for each post

hi I have to create a system of comments within various trhead I performed before and all the while the trhead 'while inside the comment and it works but is really slow and with a large number of threads often gives me timeout error how can I fix the problem?
function commenti($id) {
$query2 = "SELECT * FROM table2 WHERE numid='$id' ORDER BY id ASC";
$result2 = mysqli_query($conn,$query2);
if($result2->num_rows >0)
{
while($row2 = $result2->fetch_array(MYSQLI_ASSOC))
{
$idt2 = $row2['id'];
$testot2 = $row2['testo'];
return $testot2;
}
} else {
echo "No comment";
}
}
$query = "SELECT * FROM table1 where visualizza='1' ORDER BY id DESC";
$result = mysqli_query($conn,$query);
if($result->num_rows >0)
{
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$id = $row['id'];
$titolo = $row['titolo'];
$testo = commenti($id);
echo "$titolo $testo <br>";
}
}
mysqli_close($conn);
?>
I thought to use the join but if there are more duplicates also post comments
$query = "SELECT * FROM table1 left JOIN table2 ON table1.id = table2.numid where visualizza='1' ORDER BY id DESC";
I'm going to assume that you are trying to pull a ton of records. The best way to approach this is to add pagination and only load ~10-20 comments per page. depending on your server
Update:
#OP Basically on first load of the page you load ~10 comments, once they click view more then you load in the next few using ajax. Rinse and repeat.

Get result of mysql_query inside while of mysql_fetch_array

I am using a code something like below to get data from the second table by matching the id of first table. Code is working well, but I know it slow down the performance, I am a new bee. Please help me to do the same by an easy and correct way.
<?php
$result1 = mysql_query("SELECT * FROM table1 ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ))
{
$tab1_id = $row1['tab1_id'];
echo $row['tab1_col1'] . "-";
$result2 = mysql_query("SELECT * FROM table2 WHERE tab2_col1='$tab1_id' ") or die(mysql_error());
while( $row2 = mysql_fetch_array( $result2 ))
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
}
?>
You can join the two tables and process the result in a single loop. You will need some extra logic to check if the id of table1 changes, because you'll only want to output this value when there's a different id:
<?php
// Join the tables and make sure to order by the id of table1.
$result1 = mysql_query("
SELECT
*
FROM
table1 t1
LEFT JOIN table2 t2 ON t2.col1 = t1.id
ORDER BY
t1.id") or die(mysql_error());
// A variable to remember the previous id on each iteration.
$previous_tab1_id = null;
while($row = mysql_fetch_array( $result1 ))
{
$tab1_id = $row['tab1_id'];
// Only output the 'header' if there is a different id for table1.
if ($tab1_id !== $previous_tab1_id)
{
$previous_tab1_id = $tab1_id;
echo $row['tab1_col1'] . "-";
}
// Only output details if there are details. There will still be a record
// for table1 if there are no details in table2, because of the LEFT JOIN
// If you don't want that, you can use INNER JOIN instead, and you won't need
// the 'if' below.
if ($row['tab2_col1'] !== null) {
echo $row['tab2_col2'] . "-";
echo $row['tab2_col3'] . "</br>";
}
}
Instead of having 2 while loops, what you can do is join the 2 tables and then iterate over the result.
If you're not sure what join is look here: https://dev.mysql.com/doc/refman/5.1/de/join.html
Also here is a fairly simple query written using join: Join Query Example
You can use this. One relation with two tables:
<?php
$result1 = mysql_query("SELECT tab2_col2, tab2_col3 FROM table1, table2 where tab2_col1 = tab1_id ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ),)
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
?>
Like Sushant said, it would be better to use one JOIN or simpler something like that:
SELECT * FROM table1, table2 WHERE `table1`.`id` = `table2`.`id

Query goes in endless loop

The following goes into an endless loop, meaning it just constantly shows the same record over and over and over again.
<?php
while ($rowr = mysql_fetch_assoc(mysql_query("SELECT * FROM table1")) {
while($rowu = mysql_fetch_assoc(mysql_query("SELECT * FROM table2 WHERE id = '".$rowr['uid']."'"))){
while($rowc = mysql_fetch_assoc(mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'"))){
?>
<tr><td><?php echo $rowc['post']; ?></td><td><?php echo $rowu['username']; ?></td><td><font color="#FF0000">X</font></td></tr>
<?php
};
};
};
?>
Why does that happen and how can I fix it?
You are putting the mysql query in the while statement so every time it gets there it does the same query and shows the same first record, you are never advancing to the next record in the result set.
Personally I would combine all queries into one, but to show how you can solve your problem (the same applies to all loops):
$results = mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'");
while ($rowc = mysql_fetch_assoc($results))
{
// do stuff
}
Simply because the query gets executed again every time the loop condition is checked. That means you'll always get the same result unless something changes in the database in the meantime.
You need something like this:
<?php
$res1 = mysql_query("SELECT * FROM table1");
while ($rowr = mysql_fetch_assoc($res1)) {
$res2 = mysql_query("SELECT * FROM table2 WHERE id = '".$rowr['uid']."'");
while($rowu = mysql_fetch_assoc($res2)){
$res3 = mysql_query("SELECT * FROM table3 WHERE id = '".$rowr['cid']."'");
while($rowc = mysql_fetch_assoc($res3)){
?>
<tr><td><?php echo $rowc['post']; ?></td><td><?php echo $rowu['username']; ?></td><td><font color="#FF0000">X</font></td></tr>
<?php
}
}
}
?>
That's just to illustrate why it doesn't work. As others already noted, combining your queries into one using JOIN would be advisable.
Btw, you don't need a ; after a {} block.
Use joins and you can do it in one query.
Mysql Join
Join Tutorial
You're re-executing the queries on each loop iteration, restarting the results from scratch.
You want something like this instead:
$resultR = mysql_query("... table1");
while($rowR = mysql_fetch_assoc($resultR)) {
$resultU = mysql_query("... table2");
while($rowU = mysql_fetch_assoc($resultU)) {
etc...
}
}
Of course, this is a highly inefficient construct. You end up running count($rowR) * count($rowU) * count($rowC) queries. Why not reformulate it as a join?

loop problem within a statement

i hope someone can help about to scream!
basically I am trying to do a few things with the statement below;
First i want to check if the user id exists in member_categories_position.
If it Does i want then to exclude all entries from the second statement where member_id equals all results from the first statement
the third statement is the else statement that displays if the member_id is not present in the member_categories position.
PROBLEM - the result from the first system loops fine, however when i try and insert into the second statement (!='$memid') is produces no results and has no effect. I think the problem is that $memid is a looped result.
How do i get the second statement to say that any member_id that is in member_categories_position will not show in that statement?
$sql2 = "
SELECT *
FROM member_categories_position a
JOIN member_users b
ON b.id = a.member_id";
$rs2 = mysql_query($sql2);
while ($row = mysql_fetch_array($rs2))
{
$memid = "".$row['member_id']."";
}
if(mysql_num_rows($rs2) != 0)
{
$new= "
SELECT *
FROM member_categories
JOIN member_users
ON member_categories.member_id=member_users.id
JOIN member_config
ON member_categories.member_id=member_config.member_id
WHERE
member_categories.categories='$category'
AND member_categories.member_id !='$field'
GROUP BY member_config.member_id
ORDER BY RAND() limit 0,42";
$rs = mysql_query($new);
while ($row = mysql_fetch_assoc($rs))
{
echo "result excluding member ids from the first statement";
}
echo "<div class=\"clear\"></div>";
}
else
{
$new= "
SELECT *
FROM member_categories
JOIN member_users
ON member_categories.member_id=member_users.id
JOIN member_config
ON member_categories.member_id=member_config.member_id
WHERE
member_categories.categories='$category'
GROUP BY member_config.member_id
ORDER BY RAND() limit 0,42";
$rs = mysql_query($new);
while ($row = mysql_fetch_assoc($rs))
{
echo "Result with all member ids";
}
echo "<div class=\"clear\"></div>";
} } <-- (second is a stray from original post)
$memid is not in scope since it appears to be defined inside the loop. Try defining $memid = ''; at the top of your script.. like this.
$memid = '';
$sql2 = "
SELECT *
That way it will be defined when you use it below..

Categories