Reputation: 27
I use a data base ( created with phpmyadmin) in a function for my future website. The query worked but the result is strange : null .
This is my code :
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;
}
}
In my view :
<?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 }?>
With a var_dump , I got this :
object(Competence)[5]
private '_niveau' => null
private '_nom' => null
null
My 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;
}
}
?>
Thanks you for your help. I searched but I didn't understand why it doesn't work. PS : I know my query isn't securized. I would it to work first.
Edit : the sql data base : comptences.sql
Upvotes: 0
Views: 64
Reputation: 4310
It is because your class does not have constructor. Method Livre is not called when object is initiating $tableau[] = new Competence($row->niv,$row->nom);
. Try this (I have replaced Livre with __construct):
<?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;
}
}
Also be sure you have same values in database result.
Upvotes: 1
Reputation: 679
Try making the variables in your class public as well.
public $_niveau;
public $_nom;
Upvotes: 0