如何从类中循环调用?

时间:2017-04-14 14:15:23

标签: php pdo

我有getinfo.php类和脚本welcome.php。在获取信息类里面我有GetAll函数。我希望首先通过变量$ this->调用所有“first”并且只返回一个值,但我希望行中的所有“first”。请参阅下面的

    //script getinfo.php
class GetInfo{
     function getAll(){
             global $conn;
            $sql = $conn->prepare("SELECT * FROM users");
            $sql->execute();
            while($row = $sql->fetch(PDO::FETCH_ASSOC)){
            $this->first = $row['first'];
            $this->last = $row['last'];
            $this->email = $row['email'];
            }

        }
}
        //script welcome.php

     <?php
      $info = new GetInfo();
      $info->getAll();
      echo $info->first;
      //this is returning only one value, but I want to get all row values.
      ?>

2 个答案:

答案 0 :(得分:2)

您的代码:

while($row = $sql->fetch(PDO::FETCH_ASSOC)){
            $this->first = $row['first'];
            $this->last = $row['last'];
            $this->email = $row['email'];
            }

实际上只是将$this->first, $this->last,$this-email设置为从数据库中提取的每一行的新值。因此,当您首先使用$ this-&gt;时,只返回一个值。

我不确定我是否理解你(你想要做什么),但如果我做了......

您可以使用一个带有数组的函数作为参数,告诉您要使用哪些列,如下所示:

//script getinfo.php
protected function getAll( $use_columns = array() ){
    global $conn;
    $sql = $conn->prepare("SELECT * FROM users");
    $sql->execute();

    $sql_arr = array();
    $row_index = 0;
        while($row = $sql->fetch(PDO::FETCH_ASSOC)){
            foreach($use_columns as $uc) {
                $sql_arr[$row_index][$uc] = $row[$uc];
            }
            $row_index++;
        }    
    return $sql_arr;
}

 //script welcome.php

 <?php
  $info = new GetInfo();
  echo $info->getAll( array('first') ); //Print out all rows with first-value
  echo $info->getAll( array('last') ); //Print out all row with last-value
  echo $info->getAll( array('first', 'last') ); //Print out all row with first and last value
  ?>
  

请注意!我不确定100%以上的工作(未经测试),但我希望你理解这个一般的想法!

     

注2!请务必验证值,以便用户无法输入任何值   到发送到getAll函数的数组参数。

答案 1 :(得分:0)

将其列为数组

    class GetInfo{
        function getAll(){
            global $conn;
            $sql = $conn->prepare("SELECT * FROM users");
            $sql->execute();
            while($row = $sql->fetch(PDO::FETCH_ASSOC)){
                $this->first[] = $row['first'];
                $this->last[] = $row['last'];
                $this->email[] = $row['email'];
            }
            return $this;
        }
    }