use php function to list items
i am tying to do this by a function. i want every item found in 开发者_JAVA百科the db to be echoed out as a list
eg. item1
item2 item3 item4i know im missing something but it is puzzling me. for now im only seeing one list and upon refresh another item shows up replacing the other. plz help and thanks
function get_list() {
$id = mysql_real_escape_string(@$_GET['id']);
$get_list = array();
$bar = mysql_query(" SELECT bar.* FROM bar WHERE bar.b_id = '$id' ORDER BY rand()");
while($kpl = mysql_fetch_assoc($bar)){
$get_list[] = array( 'videoid' => $kpl['videoid'],
'name' => $kpl['name'],
'description' => $kpl['description'],
'type' => $kpl['type'],
'bev' => $kpl['bev'],
);
}
foreach ($get_list as $get_list);
return $get_list;
}
?>
<?php
$gkp_list = gkp_list();
foreach ($gkp_list as $gkp_list);
if (empty($gkp_list)){ echo 'no video'; }
else {
echo '<p>$gkp_list['name']. '<br/></p>';}
?>
There are some major syntax problems there.
function get_list() {
$id = mysql_real_escape_string(@$_GET['id']);
$get_list = array();
$bar = mysql_query(" SELECT bar.* FROM bar WHERE bar.b_id = '$id' ORDER BY rand()");
while($kpl = mysql_fetch_assoc($bar)){
$get_list[] = $kpl;
}
return $get_list;
}
$gkp_list = get_list();
if (empty($gkp_list)) {
echo 'no video';
} else {
foreach ($gkp_list as $gkp_item) {
echo '<p>' . $gkp_item['name']. '<br/></p>';
}
}
?>
- The purpose of
foreach
is to loop over an array and do something with each value. Don't use foreach if you're working with the array as a whole (in this case, returning it) - Foreach doesn't have a semicolon at the end, it typically has an opening curly brace (
{
). - You don't need to manually copy all of the array indexes in the
while
loop, because all of the indexes are the same. - The string for the output was formatted wrong, you have to be careful. Use a syntax-highlighting editor.
- The two variable names in
foreach
must be different. One refers to the array, and one refers to the value of that key.
精彩评论