hi I just started to lear oop and I came acros this problem, whwn I used this script in normal scripring sequence it ecoed out the list of items but when I put it to class file I get only the first line what is the problem? class file:
<?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>';
}
}
}
and I call it like this:
$sql = mysql_query("SELECT * FROM product");
echo $list=($getPVM->get($sql))
Use the below code and try:
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;
}
}
You return your value too early and you are not returning your list. Try this:
<?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;
}
}
To explain this a little bit:
$list .=
the dot-operator appends the string to `$list``return $list;
has to be at the end to return the complete list after you added every list item in your while-loopTry this:
<?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
}
}
You're using return
inside loop, try this instead:
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;
}
}