Hello everyone, doing a task on the list of students, there is a method in the class that returns an array with all the entries.
Here is the method:
static function getStudentList(){ $db = Database::connect(); $sql = "SELECT id, name, surname, class, points FROM student" . " ORDER BY id DESC"; $result = $db->query($sql); $studentList = []; $i = 0; while($row = $result->fetch()){ $studentList[$i]['id'] = $row['id']; $studentList[$i]['name'] = $row['name']; $studentList[$i]['surname'] = $row['surname']; $studentList[$i]['class'] = $row['class']; $studentList[$i]['points'] = $row['points']; $i ++; } return $studentList; }
Then I call it and pass it to the view where I print each line in turn.
function indexAction($view) { $studentList = Student::getStudentList(); include_once ROOT . '/views/template.php'; }
Everything works, but when I want to use this method in another place or even if I do so. That is, I will try to take an array and write it into another variable. As below.
function indexAction($view) { $studentList = Student::getStudentList(); $studentListTest = Student::getStudentList(); include_once ROOT . '/views/template.php'; }
Connection code to the database:
static function connect(){ $dbConfig = include_once ROOT . '/config/dbConfig.php'; $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']}"; $user = $dbConfig['user']; $pass = $dbConfig['pass']; $db = new PDO($dsn, $user, $pass); $db->exec("set names utf8"); return $db; }
Then i get an error
Fatal error: Call to a member function fetch () on boolean.
Please explain the reason?
$db->query
can returnfalse
. (If theDatabase
wrapper for PDO, then this is quite a regular situation.) - Dmitriy Simushev