Jump to content

PHP MYSQL NESTED LOOP PROBLEM


boydt98

Recommended Posts

Hi guys, im new here, been coding php for around 6 months and havnt really encountered many problems in the past but if i did i just found a way around the problem.

 

This time i cant see any alternative to this piece of code im stuck on so im posting here for a little help...

 

I have a table i put names into, the code then uses these names to look in another table and retreive all the data which has the corresponding names under a field called 'tag'.

 

 

Heres the code:

 

$find="SELECT * FROM attribute";

$att=mysql_query($find);

$ext=mysql_fetch_array($att)or die(mysql_error());

 

do

 

{

 

$sql="SELECT * FROM method WHERE tag = '$ext[name]' " or die(mysql_error());

$result=mysql_query($sql);

$rows=mysql_fetch_assoc($result)or die(mysql_error());

 

echo $ext[name];

echo "<a href=article.php?id=" . $rows['id'] . "&db=" . $db . "&content=1>" . $rows['heading'] . "</a> "; 

 

}while($ext=mysql_fetch_array($att));

 

All is well and fine until the $sql statement cannot find a record. For instance i have a name called 'ICS' in the attribute table and this name cannot be found in any 'tag' field within the method table.

 

If this happens then the code just stops and no other SQL querys are run.

 

Any idea guys????

 

any help is apprecited in advance, thanks.

 

Tom.

Link to comment
https://forums.phpfreaks.com/topic/110951-php-mysql-nested-loop-problem/
Share on other sites

<?php
$att=mysql_query("SELECT * FROM `attribute`"); // your query user ` and ` to enclose your vars!
while($ext=mysql_fetch_array($att)){
$result=mysql_query("SELECT * FROM `method` WHERE `tag`= '{$ext[name]}' "); # arrays need to be enclosed with { }
$rows=mysql_fetch_assoc($result); # this will onyl return row 1, unless you loop it 
echo $ext['name'];
    echo "<a href=article.php?id={$rows['id']}&db=$db&content=1>$rows['heading']</a>"; ## again arrays need enclosing in { }
/*
looping it would be like...
while($rows=mysql_fetch_assoc($result)){
  //code here
}
*/
}

?>

You have many mis-placed "or die" clauses.

Let's re-write this as:

<?php
$find="SELECT * FROM attribute";
$att=mysql_query($find) or die("Problem with the query: $find<br>" . mysql_error());
while ($ext=mysql_fetch_assoc($att)) {
   $sql="SELECT * FROM method WHERE tag = '{$ext['name']}' ";
   $result=mysql_query($sql) or die("Problem with the query: $sql<br>" . mysql_error());
   $rows=mysql_fetch_assoc($result);
   echo $ext['name'];
   echo '<a href="article.php?id=' . $rows['id'] . '&db=' . $db . '&content=1">' . $rows['heading'] . '</a>'; 
}?>

 

Does this help?

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.