Jump to content

[SOLVED] MYSQL PHP Foreach


Recommended Posts

I believe s/he means that a while loop will continue until it fails a condition while a foreach will continue until it cycles completely through an array.

 

 

Sample usage



<?php


//declare an array - or use an array pulled from a query
$var1 = array();
$var1[0] = "a";
$var1[1] = "b";
$var1[2] = "c";
$var1[3] = "d";
$var1[4] = "e";


foreach( $var1 as $content){
echo $content . "<br>";
}
?>

 

Or through using a while:

<?php

//declare an array - or use an array pulled from a query
$var1 = array();
$var1[0] = "a";
$var1[1] = "b";
$var1[2] = "c";
$var1[3] = "d";
$var1[4] = "e";

$count = 4;
$i = 0;

while($i <= $count) {
echo $var1[$i] . "<br>";
$i++;
}

 

foreach is a little shorter

$query = "SELECT * FROM `table`";
$result = mysql_query($query);

while($row = mysql_fetch_assoc($result)) {
   echo $row['col'], '<br>';
}

 

If you wanted to use a foreach statement, it would seem rather pointless because it would do something like:

$query = "SELECT * FROM `table`";
$result = mysql_query($query);

$array = array();
// gather each row into the array
while($row = mysql_fetch_assoc($result)) {
   $array[] =  $row['col'];
}
foreach($array as $key=>$value) {
   echo $value,'<br>';
}

got one more question i want it to how to make the while loop go in reverse order. to the first message is displayed last.

 

<?php
//Selecting the News From trhe Table news
$query = "SELECT * FROM `news`";
$result = mysql_query($query);

while($row = mysql_fetch_assoc($result)) {
echo '<div class="post">';
   	echo '<h2>', $row['title'], '</h2>';
  	echo '<small>', $row['date'], ' by ', $row['username'], '</small>';
  	echo '<br />';
  	echo '<br />';
echo typography($row['body']);
echo '<br />';
echo '<br />';
echo '</div>';
}
?>

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.