Fatal error: Uncaught Error: Call to undefined method PDOStatement::fetch_assoc() in C:\xampp\htdocs\PDO_connection.php:40
Hi. Actually have two part question here. First: in need of help understanding why fetch_assoc() is an undefined method. Why is fetch_assoc considered undefined in my code?
If I use fetch() it does not throw error, however it does display:
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\PDO_connection.php on line 54
I have tried changing the case from lower to upper FETCH_ASSOC(), that did not remedy the problem. I have tried using as PDO::FETCH_ASSOC(), then I get different FATAL error.
I tried adding attribute to my $pdo variable
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
Secondly: Can I assume that I get the Warning on line 54 because $data is empty as a result of the call to undefined method?
My goal was to be able to output/view as many or as few columns of each row as desired.
Code is as follows:
<?php
//This class is used for connecting to the database.
class Dbh {
private $servername;
private $username;
private $password;
private $dbname;
public function connect() {
$this->servername = "localhost";
$this->username = "root";
$this->password = "";
$this->dbname = "miles_away_travel";
$this->charset = "utf8mb4";
try {
//set dsn
$dsn = 'mysql:host='.$this->servername.';dbname='.$this->dbname.';charset='.$this->charset;
//create a PDO instance
$pdo = new PDO($dsn,$this->username,$this->password);
//also set some attributes after PDO construction with the setAttribute method:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
} catch (PDOException $e) {
echo "<h2>connection failed:</h2> ".$e->getMessage();
}
}
}
//This class is used to query the database
class FindUser extends Dbh {
protected function seekUser(){
$sql = "SELECT COUNT(*) FROM members";
$result = $this->connect()->query($sql);
$numRows = $result->fetchColumn();
//print_r($numRows);
if ($numRows >0){
while($row = $result->fetch_assoc()){
$data[] = $row;
return $data;
//print_r($data);
}
//return $data;
}
}
}
//This class will be used view or use database column data
class UserData extends FindUser {
public function showData(){
$newData = $this->seekUser();
foreach ($newData as $data) {
echo $data['username']."</br>";
echo $data['password']."</br>";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PDO Connect_Query_Display</title>
</head>
<body>
<?php
$showUser = new UserData();
$showUser->connect();
echo $showUser->showData();
?>
</body>
</html>