我在我未来网站的函数中使用了一个数据库(用phpmyadmin创建)。查询有效,但结果很奇怪:空。
这是我的代码:
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
我的班级 :
<?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;
}
}
还要确保数据库结果中的值相同。
尝试将类中的变量也设为公开。
public $_niveau;
public $_nom;