Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

MySQL and a while loop. 1

Status
Not open for further replies.

Zilch

Programmer
Nov 24, 2003
10
0
0
US
I've a slight problem with my while loop. Although it is doing exactly as it is suppose to, I relized something. I need to contact the MySQL database, find the value of every line with a given username, then show the content of each of those lines one by one. I thought maybe an array or something, but I'm really not sure.

Current code:
// $rows is the number of MySQL rows with '$userName' as the reciver.
$x = "0";
while ($x < $rows) {
// Query the Database:
$sql = &quot;select * from pm where reciver = '$userName'&quot;;
$result = mysql_query($sql,$conn) or die(&quot;Query fail.&quot;);

// PM Information Vars
$id = mysql_result ($result, 0, 'id');
$sender = mysql_result ($result, 0, 'sender');
$subject = mysql_result ($result, 0, 'subject');
$date = mysql_result ($result, 0, 'date');

$list = &quot;<tr>\n&quot;;
$list .= &quot;<td>$sender</td>\n&quot;;
$list .= &quot;<td><a href=$v?content=Members/pm/index.php&action=read&id=$id>$subject</a></td>\n&quot;;
$list .= &quot;<td>$date</td>\n&quot;;
$list .= &quot;</tr>\n&quot;;

++$x;
}
 
Code:
$list = mysql_num_rows($result); 
while($i < $list)	
{
$row = mysql_fetch_array($result); 
$sender=$row[&quot;sender&quot;];
$subject=$row[&quot;subject&quot;];

print &quot;<tr><td>$subject</td><td>$sender</td></tr>&quot;;

$i++;
}

something like this
 
Has hos2's post helped? If it hasnt, im not too sure exactly what you mean. Could you clarify a little further?

Skute

&quot;There are 10 types of people in this World, those that understand binary, and those that don't!&quot;
 
Here's the really shortest way:
Code:
$SQL = &quot;SELECT * FROM pm WHERE reciver = '$userName'&quot;;
# always catch errors
$result = mysql_query($SQL) OR die(mysql_error());

while ($row = mysql_fetch_assoc($result)){
   print &quot;<tr><td>&quot;;
   print $row['subject'];
   print &quot;</td><td>&quot;;
   print $row['sender'];
   print &quot;</td></tr>&quot;;
}

You need to know the following things:
1. $result is a resource identifier that holds access to all records for the query.
2. The while loop will fetch one record at a time and move to the next in the result set.
3. mysql_fetch_assoc() returns an associative array that is keyed by the column name. No need for any temporary vars. Just print the array element by column name.



 
hos2's code did not work for what I was trying to do. However, DRJ478's fixed the problem perfectly. Thank you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top