嗨,我
刚刚开始哎呀,我遇到了这个问题,我以正常的脚本顺序使用了这个脚本,它整理了项目列表,但是当我把它放到类文件中时,我只得到第一行有什么问题?类文件:
<?php
class getPVM{
function get ($sql){
while($row = mysql_fetch_array($sql)){
$id = $row["product_id"];
$product_name = $row["product_name"];
$price = $row["price"];
return $list =' <li>'.$id .' '.$product_name.' '.$price.'(PVM '.$price*0.21 .') </br></li>';
}
}
}
我这样称呼它:
$sql = mysql_query("SELECT * FROM product");
echo $list=($getPVM->get($sql))
你过早地返回你的值,你没有返回你的列表。试试这个:
<?php
class getPVM
{
function get($sql)
{
$list = "";
while ($row = mysql_fetch_array($sql)) {
$product_name = $row["product_name"];
$price = $row["price"];
$list .= ' <li>'.$id.' '.$product_name.' '.$price.'(PVM '.$price*0.21.') </br></li>';
}
return $list;
}
}
稍微解释一下:
-
$list .=
点运算符将字符串附加到"$list" -
return $list;
必须在末尾返回完整的列表,在 while-loop 中添加每个列表项后返回完整列表
您正在使用return
内部循环,请尝试以下操作:
class getPVM{
function get ($sql){
$list = array();
while($row = mysql_fetch_array($sql)){
$id = $row["product_id"];
$product_name = $row["product_name"];
$price = $row["price"];
$list[]=' <li>'.$id .' '.$product_name.' '.$price.'(PVM '.$price*0.21 .') </br></li>';
}
return $list;
}
}
使用以下代码并尝试:
class getPVM{
function get ($sql){
$list = '';
while($row = mysql_fetch_array($sql)){
$id = $row["product_id"];
$product_name = $row["product_name"];
$price = $row["price"];
$list .=' <li>'.$id .' '.$product_name.' '.$price.'(PVM '.$price*0.21 .') </br></li>';
}
return $list;
}
}
试试这个:
<?php
class getPVM{
function get ($sql){
$list = "";
while($row = mysql_fetch_array($sql)){
$id = $row["product_id"];
$product_name = $row["product_name"];
$price = $row["price"];
$list =' <li>'.$id .' '.$product_name.' '.$price.'(PVM '.$price*0.21 .') </br></li>';
}
return $list; //or whatever you return
}
}