PHP foreach() not looping through data as expected?
I have the foillowing PHP code, but I can't get it to work?
This is the main PHP file:
function get_data() {
$query = 'SELECT title, article FROM submissions';
$result = mysql_query($query);
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
}
return $row; //perhaps because $row is not return all?
}
$data = get_data();
require('template/data.inc.php');
?>
and this is template/data.inc.php:
<?php
foreach ($data as $value):
echo $data['i'].'<br>';
echo $data['title'].'<br>';
echo $data['article'].'<br>';
endforeach;
?>
template/data.inc.php is meant to output s开发者_Go百科omething like:
1 How to get your site on Google?
Text...
2 Secrets of SEO Revealed
Text...
My guess is get_data() is not returning the array() in a form which is supported within the foreach? - as its currently giving an error.
Here is your problem:
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
}
On every iteration, $row
is being reset to current record, and in the end mysql_fetch_assoc
will turn it to FALSE
. You have to put each $row
into auxiliary array and return it as whole resultset:
$i = 0;
$returnArray = array();
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
$returnArray[] = $row;
}
return $returnArray;
ANd in your template use $value
to get details for each row:
foreach ($data as $value):
echo $value['i'].'<br>';
echo $value['title'].'<br>';
echo $value['article'].'<br>';
endforeach;
The way in which you're building $row and returning it
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
++$i;
$row['i'] = $i;
$row['title'] = limittext($row['title'], 15);
}
return $row;
}
You'll only EVER have the LAST iteration of $row set ... if that's what you want? In other words, $row will only continue a single value.
Your loop continues until $row has an value that is evaluated as false:
while ($row = mysql_fetch_assoc($result)) {
and then you return $row so you always return null or false!
replace
$row['title'] = limittext($row['title'], 15);
with
$row['title'] = limittext($row['title'], 15);
$result[]=$row;
and
return $row;
with
return $result;
精彩评论