我在我 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/