loop problem within a statement - php

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..

Related

Echo rows via JOIN in MySQL/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;
}

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

While loop not printing all answers

This might be really simple, but i cannot figure out the problem with this code:
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
Now based on my database the query is returning 2 results, the echo mysql_num_rows($sql) also gives out 2. However the reached is echoed only once. Does anyone see a potential problem with the code?
P.S: My bad, $sql is being repeated, that was a silly mistake
It will only echo once because of this line :
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
your overwriting the $sql variable.
Why not just run a single query and join the data you require ?
try ($sql2 instead of $sql and $sql[0] to $sql2[0]):
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql2 = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql2[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
I think it'll be because you are ressetting the sql variable
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
when you are still using it in the while loop. :P
It's probably this line:
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
Try using a different variable name.
You are changing the $sql variable inside the loop, therefore the next time you run $row = mysql_fetch_array($sql), the value will be different (probably won't be any based on your code).
Inside the while loop you are re-using the same variable: $sql. This is used to control the terminating condition of the loop.
Using a different variable name, e.g. $sql2 should leave the original variable intact and the loop should proceed as expected.

Select statement within a while statement

First, I coded this, which looks inside a table, gets the last 10 entries, and displays them. The output is as expected, a list of the 10 last entries in the database.
$query = "SELECT dfid FROM downloads_downloads ORDER BY did DESC limit 10";
$dlresult = mysql_query( $query );
$i=0;
$num = mysql_num_rows ($dlresult);
while ($i < $num) {
$dfid= mysql_result($dlresult,$i,"dfid");
echo "<b>filenumber:</b> $dfid <br>";
++$i;
}
But I don't just need the filenumber. I need the actual filename and url from another table. So I added a select statement inside the while statement, using the file number.
But for some reason, this code only displays one filename instead of 10. I know, from the above code, it's getting all 10 file numbers.
$query = "SELECT dfid FROM downloads_downloads ORDER BY did DESC limit 10";
$dlresult = mysql_query( $query );
$i=0;
$num = mysql_num_rows ($dlresult);
while ($i < $num) {
$dfid= mysql_result($dlresult,$i,"dfid");
$query2 = "SELECT file_name, file_name_furl FROM downloads_files WHERE file_id = '$dfid'";
$dlresult2 = mysql_query( $query2 );
$dlfile_name= mysql_result($dlresult2,$i,"file_name");
$dlfile_name_furl= mysql_result($dlresult2,$i,"file_name_furl");
echo "filenumber: $dfid <br>"; //Shows 10, as expected.
echo "filename: $dlfile_name - $dlfile_name_furl <br>"; //Shows only 1?
++$i;
}
I can manually execute the sql statement and retrieve the file_name and file_name_furl from the table. So the data is right. PHP isn't liking the select within the while statement?
Looks like you're only going to ever have 1 row, in your 2nd select statement, because you are just selecting one row, with your where statement.
So, you're only going to ever have row 0 in the 2nd statement, so its only finding row 0 on the first loop. try instead:
$dlfile_name= mysql_result($dlresult2,0,"file_name");
$dlfile_name_furl= mysql_result($dlresult2,0,"file_name_furl");
However, insrtead of making 11 separate queries, try using just one:
$link = new mysqli(1,2,3,4);
$query = "SELECT downloads_downloads.dfid, downloads_files.file_name, downloads_files.file_name_furl FROM downloads_downloads LEFT OUTER JOIN downloads_files ON downloads_files.file_id = downloads_downloads.dfid ORDER BY downloads_downloads.dfid DESC limit 10;
$result = $link->query($query) ;
if((isset($result->num_rows)) && ($result->num_rows != '')) {
while ($row = $result->fetch_assoc()) {
echo "filenumber: $row['dfid'] <br>";
echo "filename: $row['file_name'] - $row['file_name_furl'] <br>";
}
Read up on mysql joins http://www.keithjbrown.co.uk/vworks/mysql/mysql_p5.php
I'm not sure if this is syntax correct, but it gives you the right idea =)

Printing Duplicate Records In PHP / Mysql

I am trying to print the duplicate records of the table but only the single row is getting
echoed.However in mysql this query results all the duplicate records. Here is the query:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
$r = mysql_fetch_array($q);
$s = mysql_num_rows($q);
while($s !=0)
{
echo $r;
$s=$s-1;
}
Whats wrong with the code?
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144' GROUP BY cust_id");
while($r = mysql_fetch_array($q))
{
print_r($r);
}
You need to loop through the entire record set... you are only grabbing the first row:
$resultset = mysql_query("select * from add where cust_id = '144' group by cust_id");
while($row = mysql_fetch_assoc($resultset))
{
echo $row['column_name'];
}
Your SQL query will in practice only ever return 0 or 1 rows, due to the GROUP BY clause. Are you absolutely sure that that's the query you were executing in mysql?
well, if you want to get duplicate values, then this query will serve you well:
T = the table
f = the field to check for duplicates
id = the rows id
select id,f from T group by f having count(f)= 2;
or >2 if you want every value in f that occurs in more than one row.
having is like where but evaluated after group by.
Try the following:
$q = mysql_query("SELECT * FROM add WHERE cust_id = '144'");
while($r = mysql_fetch_array($q))
{
echo $r;
}

Categories