sudhakar
sudhakar

Reputation: 29

php mysql foreach repeats twice

Hi i am using foreach in php oops to output data from the mysqlbut each data outputs twice please check my code and help it i have tried but no correct result

Here is the code below i have used

class getdata extends db{
    public function getdata(){
      $sql = "SELECT * FROM users";
      $results = $this->connect()->query($sql);
      $numrows = $results->num_rows;
      if($numrows > 0){
        while($row = $results->fetch_assoc()){
          $data[] = $row;
        }
        return $data;
      }
      else{
        echo 'no values';
      }
    }
  }

class showusers extends getdata{

    //show users
    public function showusers(){
      $datas = $this->getdata();

      foreach($datas as $data){
        echo $data['id'].'<br>';
        echo $data['name'].'<br>';
      }
    }

  }

$showusers = new showusers();
$showusers->showusers();

Upvotes: 0

Views: 55

Answers (2)

David
David

Reputation: 69

your code is a bit convoluted I'd suggest passing the database connection object rather than extending continiously. In this case your constructor showUsers() outputs a list of users. therefore it repeats because you are calling this function twice.

$showusers = new showusers();  // prints users
$showusers->showusers();  // prints users again

move your display function

  class showusers extends getdata{
    $data;
    //initialize
    public function showusers(){
      $this->data = $this->getdata();
    }

    //show users
    public function displayUsers(){
      foreach($this->data as $data){
        echo $data['id'].'<br>';
        echo $data['name'].'<br>';
      }
    }
  }

$showusers = new showusers();
$showusers->displayUsers();

Upvotes: 0

crossi100
crossi100

Reputation: 98

Don't give your function the same name as your class.

With $showusers = new showusers(); you are already executing the showusers function.

To cite php.net:

For backwards compatibility with PHP 3 and 4, if PHP cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class.

Source:https://www.php.net/manual/en/language.oop5.decon.php

So your function showusers() is treated as a constructor for your showusers class and therefore is executed twice. Once when you create an object of the class and once when you call the method.

Upvotes: 1

Related Questions