Use mysql_fetch_array() with foreach() instead of while()

前端 未结 5 643
梦谈多话
梦谈多话 2020-12-05 21:49

i want to know how do we convert the following code to work with foreach

$query_select = \"SELECT * FROM shouts ORDER BY id DESC LIMIT 8;\"; 

    $result_se         


        
5条回答
  •  春和景丽
    2020-12-05 22:44

    To use foreach would require you have an array that contains every row from the query result. Some DB libraries for PHP provide a fetch_all function that provides an appropriate array but I could not find one for mysql (however the mysqli extension does) . You could of course write your own, like so

    function mysql_fetch_all($result) {
       $rows = array();
       while ($row = mysql_fetch_array($result)) {
         $rows[] = $row;
       }
       return $rows;
    }
    

    However I must echo the "why?" Using this function you are creating two loops instead of one, and requring the entire result set be loaded in to memory. For sufficiently large result sets, this could become a serious performance drag. And for what?

    foreach (mysql_fetch_all($result) as $row)
    

    vs

    while ($row = mysql_fetch_array($result))
    

    while is just as concise and IMO more readable.

    EDIT There is another option, but it is pretty absurd. You could use the Iterator Interface

    class MysqlResult implements Iterator {
      private $rownum = 0;
      private $numrows = 0;
      private $result;
    
      public function __construct($result) {
        $this->result = $result;
        $this->numrows = mysql_num_rows($result);
      }
    
      public function rewind() {
        $this->rownum = 0;
      }
    
      public function current() {
        mysql_data_seek($this->result, $this->rownum);
        return mysql_fetch_array($this->result);
      }
    
      public function key() {
        return $this->rownum;
      }
    
      public function next() {
        $this->rownum++;
      }
    
      public function valid() {
        return $this->rownum < $this->numrows ? true : false;
      }
    }
    
    $rows = new MysqlResult(mysql_query($query_select));
    
    foreach ($rows as $row) {
      //code...
    }
    

    In this case, the MysqlResult instance fetches rows only on request just like with while, but wraps it in a nice foreach-able package. While you've saved yourself a loop, you've added the overhead of class instantiation and a boat load of function calls, not to mention a good deal of added code complexity.

    But you asked if it could be done without using while (or for I imagine). Well it can be done, just like that. Whether it should be done is up to you.

提交回复
热议问题