php - 查询结果到对象集合

标签 php mysql

我有一个数据库 phpmyadmin,我创建了一个类:

<?php

class Ticket
{
private $NumDossier = 0;
private $NomTicket ="";
private $Service = "" ;
private $Impact = 0;
private $Urgence = "";
private $DateOuverture = "";

public function __construct($p_NumDossier, $p_NomTicket,$p_Service,$p_Impact,$p_Urgence,$p_DateOuverture)
{
    $this->NumDossier = $p_NumDossier;
    $this->NomTicket = $p_NomTicket;
    $this->Service = $p_Service;
    $this->Impact = $p_Impact;
    $this->Urgence = $p_Urgence;
    $this->DateOuverture = $p_DateOuverture;
}
public function getNumDossier()
{
    return $this->NumDossier;
}
public function getNomTicket()
{
    return $this->NomTicket;
}
public function getService()
{
    return $this->Service;
}
public function getImpact()
{
    return $this->Impact;
}public function getUrgence()
{
    return $this->Urgence;
}
public function getDateOuverture()
{
    return $this->DateOuverture;
}
} 
?>

对于查询返回的所有行,我想创建一个对象并将其添加到集合中。

我的代码:

$connexion = cnx(); 

if($connexion) { 
    $requete="SELECT * FROM ticket '"; 
    $result = mysqli_query($connexion, $requete); 
    $result = mysqli_query($connexion, $requete); 
    $row = mysqli_fetch_assoc($result); 
 } 

$test = new Ticket(0,"","",0,"",""); 

while($row) { 
    //create object for each line and add it to an collection 
}

如果您有解决方案/引导我解决这个问题。

感谢您的阅读!

最佳答案

我必须假设你的代码的开头部分是正确的,所以我复制了它。但我进一步改变了它。您想要检索多行,因此我将 mysqli_fetch_assoc 放入 while 循环内。对于每个新行,我都会创建一个新票证并将其放入“集合”数组中。

$connection = cnx(); 

if ($connexion) { 
    $query ="SELECT * FROM ticket"; 
    $result = mysqli_query($connection, $query); 
    if ($result === false) die("The query [$query] could not be executed.");

    $collection = [];
    while($row = mysqli_fetch_assoc($result)) {
        $collection[] = new Ticket($row["NumDossier"],
                                   $row["NomTicket"],
                                   $row["Service"],
                                   $row["Impact"],
                                   $row["Urgence"],
                                   $row["DateOuverture"]); 
    }

    echo "<pre>";
    print_r($collection);
    echo "</pre>";
} 

所以我使用了一个简单的数组来进行集合。我使用默认的数字数组索引,因为我不知道用什么来替换它。 $row["NomTicket"] 似乎是一个合乎逻辑的选择。

关于php - 查询结果到对象集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56462294/

相关文章:

php - ZEND Framework 2 RESTful Web 服务模板错误

php - 禁用 PHPUnit 代码覆盖率输出中的颜色

php - 不使用 "Application Specific Password"从 gmail 获取邮件

php - 你如何让当前用户登录到 apache 领域?

mysql 外连接不显示空结果

mysql - 如何将 sum(field_name) 存储在 MySql Select 语句中的变量中?

mysql - 在 C 应用程序中调用 MySQL 存储过程出现错误

php - 在后台模式下运行 bash 脚本时出现编码问题

php - 表单在数据库中添加新数据

MySQL 条件 CONCAT 语法取决于字段内容?