Query goes in endless loop - php

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?

Related

Count rows in while loop

I am trying to while loop information into a SELECT statement, then COUNT the results. I have tried at least 10 different "solutions" and none works. I only get 0, 1, or nothing. Here's my most recent attempt:
$query35 = "SELECT * FROM movies WHERE userID = $memberID";
$result35 = $db->query($query35);
while ($row35 = $result35->fetchAll(PDO::FETCH_ASSOC)) {
$movie = $row35['movie'];
$query36 = "SELECT COUNT(*) AS similar FROM movies WHERE userID = '$profileID' && movie = '$movie'";
$result36 = $db->query($query36);
$row36->fetchObject;
$similar = $row36['similar'];
echo $similar;
}
$row36->fetchObject;
Seems null object, I think it should be
$row36 = $result36->fetchObject();
If all you are looking to do is count the number of times your loop is run per script execution, then it is fairly simple to do. See below:
$count = 0;
while($row35 = $result35->fetch(PDO::FETCH_ASSOC)){
//Do all your loop stuff.
$count++;
}
var_dump($count);
Important to note that your $count variable needs to be declared outside of your loop.
Also you either need to use fetchAll with a foreach loop, or use fetch with a while loop, but don't mix them.
Also a tip on good practice. Try to avoid as much as possible executing any kind of database querying with a loop, you can run into serious performance issues down the line as your loops get bigger.
Not sure what are you doing. But at least try:
$query35 = "SELECT * FROM movies WHERE userID = $memberID";
$result35 = $db->query($query35);
if ($row35 = $result35->fetchAll(PDO::FETCH_ASSOC))
foreach ($row35 as $row) {
print_r($row);
}
or maybe
$query35 = "SELECT * FROM movies WHERE userID = $memberID";
$result35 = $db->query($query35);
while ($row = $result35->fetch(PDO::FETCH_ASSOC)) {
print_r($row);
$movie = $row['movie'];
$query36 = "SELECT COUNT(*) AS similar FROM movies WHERE userID = '$profileID' && movie = '$movie'";
$result36 = $db->query($query36);
$obj = $result36->fetchObject();
$similar = $obj->similar;
echo $similar;
}

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.

PHP while looping endlessly instead of iterating through MySQL table rows

I can't figure out why this keeps breaking my page. Could someone take a look? Thanks!
while ($row = mysql_fetch_array(mysql_query("SELECT * FROM `mytable` WHERE `col1` = 0"))) {
echo $row['id'];
}
I've seen this type of while loop show up pretty regularly in google searches and just browsing through stackoverflow. I don't know why it isn't working for me.
How would I achieve the desired result? (Echo the id of each row where col1 = 0)
Obviously it is because you create new MySQL resource with every iteration and then use it's first row.
Use something like
$res = mysql_query("...");
while ($row = mysql_fetch_array($res)) {
echo $row['id']'
}
By the way, you do know that mysql is deprecated, do you not?
$result = mysql_query("SELECT * FROM `mytable` WHERE `col1` = 0");
while ($row = mysql_fetch_array($result)) {
echo $row['id'];
}

PHP Query Call Issue

I have two tables in my database:
1) blog_table
2) content
In blog_table I have values called postID that may or may not match up to values called id in the table content. I am wanting to know how I can write a while loop or foreach loop that will cycle through content table and perform one action if the id equals the value of postID in the blog_table and perform a different action if it doesn't.
Right now I can only get id = postID
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogtable))
{
$getblogposts1 = mysql_query("SELECT postID FROM `$blog_table`");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
if( $row1['postID'] == $row['id']) {
echo "do something<br>";
}else{
echo "do something else<br>";
}
} echo "<p></p>";
}
[Edit based on OP's comments and revised question]
$getblogposts = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogposts))
{
$matches = mysql_query("SELECT * FROM $blog_table WHERE postID = $row['id']");
if (mysql_num_rows($matches) > 0)
{
// do something
}
else
{
// do something else
}
}
Regarding a different design, I can't say for sure that it's necessary, but I don't like running a loop of queries like this. I think one query should be enough to get everything you need in this case. Maybe if you describe your application, we could find a better query or more appropriate design.
Just providing an easier to see solution for you to your problem.
I suggest using inner joins which will solve the issue at hand.
For example, Something like:
SELECT * FROM content AS C INNER JOIN $blog_table AS B on B.postID = C.id
Here is a great introduction to joins (inner, left, right, full):
http://www.w3schools.com/sql/sql_join.asp
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT postID FROM `$blog_table`");
while ($row = mysql_fetch_assoc($getblogtable))
{
$postID = $row['postID'];
$getblogposts1 = mysql_query("SELECT * FROM content WHERE id = '$postID' ORDER BY `order` ASC");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
// if( $row1[id] == $postId )
// do something
// else
// do something else
}
}

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