Kylian Wester
Kylian Wester

Reputation: 27

calling a php class function inside of a while loop

I want to retrieve the amount of employees all the companies have, but it doesn't call the function.

This is my Class:

class Rimaxx {

public $host = "";
public $username = "";
public $password = "";
public $database = "";

public function GetCompanies()
{
$conn = new mysqli ($this->host, $this->username, $this->password, $this->database);

$sql = "SELECT * FROM freelancers";
$result = $conn->query($sql);

return $result;

$conn->close();

}

public function CountEmployees($id)
{
$conn = new mysqli ($this->host, $this->username, $this->password, $this->database);

$sql = "SELECT * FROM Werknemers WHERE Idbedrijf = '$id'";
$result = $conn->query($sql);

return $result->num_rows;

$conn->close();
}

And here is where I define things:

include('rimaxx.php');

$rimaxx = new Rimaxx();

$rimaxx->host = "23.12.12.32";
$rimaxx->username = "xxx";
$rimaxx->password = "xxxxxx";
$rimaxx->database = "rimaxx";

$companies = $rimaxx->GetCompanies();

And here is my while loop:

 <?php while($row = $companies->fetch_assoc()) { ?>
            <tr>
              <td><?php echo $row["Bedrijf"]; ?></td>
              <td><?php echo $row["Plaats"]; ?></td>
              <td><?php echo $row["Postcode"]; ?></td>
              <td><?php echo $row["Provincie"]; ?></td>
              <td><?php echo $rimaxx->CountEmployees($row["Idbedijf"]); ?></td>
            </tr>
 <?php }; ?>

Please, can some body help my?

Upvotes: 1

Views: 1215

Answers (2)

doerig
doerig

Reputation: 1857

There is a typo in your method call, change it to this:

$rimaxx->CountEmployees($row["Idbedrijf"]);

Upvotes: 2

Mauricio Florez
Mauricio Florez

Reputation: 1132

This is a recommendation for your code, better performance on the cycles, added the connection on the constructor

class Rimaxx
{
    protected $conn;

    public function __construct($host, $username, $password, $database)
    {
        $this->conn = new mysqli ($host, $username, $password, $database);
    }

    public function GetCompanies()
    {
        $sql = "SELECT * FROM freelancers";
        $result = $this->conn->query($sql);
        return $result;
    }

    public function CountEmployees($id)
    {
        $sql = "SELECT * FROM Werknemers WHERE Idbedrijf = '$id'";
        $result = $this->conn->query($sql);
        return $result->num_rows;
    }

    public function close(){
        $this->conn->close();
    }
}


$rimaxx = new Rimaxx  ('23.12.12.32', 'xxx', 'xxxxxx', 'rimaxx');

//.....


$rimaxx->close();

Upvotes: 1

Related Questions