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

Link to comment
Share on other sites

$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>';
}

Link to comment
Share on other sites

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>';
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.