0

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(); 
2
  • Does var_dump(count($datas)); give you the expected amount of records, or is that number double of what you’d expect already? Commented Mar 26, 2020 at 11:52
  • 1
    Also, you should read more about MVC (Model-View-Controller) pattern as it seems you are trying to implement it but you stared with the wrong foot. And maybe about dependency injection too Commented Mar 26, 2020 at 11:54

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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(); 

2 Comments

Thank you David it fixed the issue was using same name for class and function
Glad I could help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.