简体   繁体   中英

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?

您的方法调用中存在拼写错误,请将其更改为:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM