在 while 循环中调用 PHP 类函数


calling a php class function inside of a while loop

我想检索所有公司的员工数量,但它不调用该函数。

这是我的班级:

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

这是我定义事物的地方:

include('rimaxx.php');
$rimaxx = new Rimaxx();
$rimaxx->host = "23.12.12.32";
$rimaxx->username = "xxx";
$rimaxx->password = "xxxxxx";
$rimaxx->database = "rimaxx";
$companies = $rimaxx->GetCompanies();

这是我的while循环:

 <?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 }; ?>

拜托,身体可以帮助我吗?

您的方法调用中有一个拼写错误,请将其更改为:

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

这是对您的代码的建议,在循环上具有更好的性能,在构造函数上添加了连接

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