0
//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 并且值的数量不固定?提前致谢 :)

4

3 回答 3

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 :(
于 2012-08-16T10:00:54.273 回答
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..
于 2012-08-16T10:10:30.827 回答
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();
于 2012-08-16T10:08:33.853 回答