//this is my code from class.php
class Functions
{
function getUsers($sex)
{
$stmt = $pdo->prepare('SELECT lname,fname from users WHERE gender = :gender');
$stmt->execute(array(':gender'=>$sex));
foreach($stmt as $row)
{
echo $row['lname'].'-'.$row['fname'];
//this is what i think but i don't need to echo because the echo must be in index.php.What is the right way?
}
}
$function = new Functions();
}
//this is for my index.php
include 'class.php'
$function->getUsers($gender);
//this is what i think but it is probably wrong or incomplete.
foreach(what should i put here?)
{
echo '<li>' names should be here? '</li>'
}
//the output should get all the user based on the gender :(
问题:如何从我的函数中检索值,因为它的值来自foreach并且值的数量不固定?在此先感谢:)
答案 0 :(得分:2)
您应该从getUsers返回用户,然后循环它们以显示在index.php
中 //this is my code from class.php
class Functions
{
function getUsers($sex)
{
$stmt = $pdo->prepare('SELECT lname,fname from users WHERE gender = :gender');
$stmt->execute(array(':gender'=>$sex));
if(is_array($stmt)){
return $stmt;
}else{
return false;
}
}
}
//this is for my index.php
include 'class.php'
$function = new Functions();
$gender = "male"
$users = $function->getUsers($gender);
if($users){
foreach($users as $row)
{
echo '<li>' . $row['lname'].'-'.$row['fname'] . '</li>'
}
}else{
echo "no users!";
}
//the output should get all the user based on the gender :(
答案 1 :(得分:1)
//this is my code from class.php
class Functions {
function getUsers($sex) {
$stmt = $pdo - > prepare('SELECT lname,fname from users WHERE gender = :gender');
$stmt - > execute(array(':gender' = > $sex));
foreach($stmt as $row) {
$names[] = $row['lname'].'-'.$row['fname'];
//this is what i think but i don't need to echo because the echo must be in index.php.What is the right way?
}
return $names;
}
}
//this is for my index.php
include 'class.php'
$function = new Functions();
$names = $function->getUsers($gender);
//this is what i think but it is probably wrong or incomplete.
foreach($names as $name) {
echo '<li>'.$name.'</li>'
}
//the output should get all the user based on the gender :(
//y u discriminate? just kidding..
答案 2 :(得分:0)
您可以保存数组中的所有值并返回该数组
class Functions
{
function getUsers($sex)
{
$stmt = $pdo->prepare('SELECT lname,fname from users WHERE gender = :gender');
$stmt->execute(array(':gender'=>$sex));
foreach($stmt as $row)
{
$userdetails[] = $row['lname'].'-'.$row['fname'];
//this is what i think but i don't need to echo because the echo must be in index.php.What is the right way?
}
return $userdetails;
}
}
我在你的代码中发现的另一个错误是,如果你想创建一个类的实例,它应该在类外面声明
$function = new Functions();