在while循环中调用php类函数

时间:2016-03-21 08:04:50

标签: php class 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 }; ?>

拜托,有些人可以帮我吗?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

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

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