PHP - 查询有效,但结果很奇怪 : all null

标签 php mysql

我在我 future 网站的函数中使用数据库(使用 phpmyadmin 创建)。查询有效,但结果很奇怪: null 。

这是我的代码:

public  function select_toutcompetences($requete){
    $query = "SELECT niv , nom   FROM competences  WHERE element = '$requete' ";
    $result = $this->_db->query($query);
    $tableau = array();

    if ($result->rowCount() == 0){
        return $tableau;
    } else {
        while($row = $result->fetch()) {
            $tableau[] = new Competence($row->niv,$row->nom);
        }
        return $tableau;
    }
}

在我看来:

<?php if (!empty($table)) {?>
 <table>
  <caption>Les compétences</caption>
  <tr>
    <th>Niveau</th>
    <th>Nom</th>
<tr>
<?php foreach ($table as $i=> $element) { ?>
<tr>
<td><?php echo $element->niveau()?></td>
<td><?php echo $element->nom()?></td>
</tr>
<?php } ?>
</table>
<?php }?>

通过 var_dump ,我得到了这个:

object(Competence)[5]
 private '_niveau' => null
 private '_nom' => null

 null

我的类(class):

<?php

class Competence {
private $_niveau;
private $_nom;
public function Livre($niveau,$nom) {
    $this->_niveau = $niveau;
    $this->_nom = $nom;
}

public function niveau() {
    return $this->_niveau;
}

public function nom() {
    return $this->_nom;
}
}

?>

感谢您的帮助。我搜索过但不明白为什么它不起作用。 PS:我知道我的查询不安全。我希望它先工作。

编辑:sql数据库:comptences.sql

最佳答案

这是因为你的类没有构造函数。当对象启动 $tableau[] = new Competence($row->niv,$row->nom); 时,不会调用 Livre 方法。试试这个(我已经用 __construct 替换了 Livre):

<?php

class Competence {
    private $_niveau;
    private $_nom;

    public function _contruct($niveau,$nom) {
         $this->_niveau = $niveau;
         $this->_nom = $nom;
    }

    public function niveau() {
        return $this->_niveau;
    }

    public function nom() {
        return $this->_nom;
    }
}

还要确保数据库结果中有相同的值。

关于PHP - 查询有效,但结果很奇怪 : all null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29053852/

相关文章:

php - 准备好的动态mysql查询

MySQL 交换值(不在字段之间)

mysql - mysql 查询运行需要双别名

php - 在 PHP 中用 e 替换 é

php - 是否可以将 PHP 的简单片段重新编码为 JavaScript?

pentaho - PDI 或 mysqldump 提取数据而不阻塞数据库也不会获得不一致的数据?

mysql - Solr 和 Lucene,包括在 Web 应用程序中

php - Twig 用一个变量设置一个变量名 [TWIG/PHP]

php - 在自动建议期间缓存大约 15k 条记录

PHP Web 应用程序 (Magento) 遭到黑客攻击;这段黑客代码有什么作用?