Php loop need help?
This is sql table
id id_user id_userfor description date
1 231 119 a t开发者_开发问答o b 2010-02-05 17:42:47
2 231 231 myself 2010-02-05 17:36:28
3 231 119 from x to b 2010-02-05 17:36:29
I could not find the way to select output result which looks something like this:
user 119
a to b 2010-02-05 17:42:47
from x to b 2010-02-05 17:36:29
user 231
myself 2010-02-05 17:36:28
You can use
select id_userfor, description, date from table order by id_userfor;
then you can print all the date
column data for each distinct id_userfor
$old = '';
while($row = mysql_fetch_array($result)) {
if($old != $row['id_userfor']) {
$old = $row['id_userfor'];
echo "$row['id_userfor']<br />";
}
echo $row['description'] . " " . $row['date'] . "<br />";
}
You can query with the id_userfor
field sorted Then loop all record and everytime you encounter a new value of id_userfor
print it.
Something like this:
$SQL = 'select * from ... order by `id_userfor`';
$Result = ...;
$PrevUserFor = '';
while($Row = ...) {
const $UserFor = $Row['id_userfor'];
if ($PrevUserFor != $UserFor) {
// Here is where you print the user ID
echo "user $UserFor<br>";
$PrevUserFor != $UserFor;
}
$Description = $Row['description'];
$Date = $Row['date'];
echo(' $Description $Date<br>');
}
Hope this helps.
The codaddict query a little more readable:
SELECT `id_userfor`, `description`, `date` FROM `table` ORDER BY `id_userfor`
And then, inside the loop, you'll use something like this:
$sql = "SELECT `id_userfor`, `description`, `date` FROM `table` ORDER BY `id_userfor`";
$query = mysql_query($sql);
$user = null; // Empty user
while($data = mysql_fetch_assoc($query)) {
if ($data['id_userfor'] != $user) {
// Display the user only when it changes
echo '<H1>'. $data['id_userfor'] .'</H1>';
$user = $data['id_userfor'];
}
// Display the rest of the fields here :)
}
精彩评论