I am just beginning to learn about PHP OOP through videos on youtube and I am following along in building a website application.
I have to connect to the SQL database using PDO as the guy explained. I followed everything he did but my execution part for the PDO is not working and I don't know what is wrong with it. The code is below. it does not bring up any errors it just doesn't bring back any data from the database. I put some echos in between the function to find out how far the code is going and that is how I found out that it prepares the query but never executes it. Please help me figure this out. Thank you.
class Database{
private function connect()
{
$string = DBDRIVER . ":host =" .DBHOST.";dbname =".DBNAME;
if ($conn = new PDO($string, DBUSER, DBPASS)) {
return $conn;
} else {
die("Could not connect to database");
}
}
The code above is the connection to the database. it is working correctly as far as I can tell.
The code below is supposed to return the data from the database back to be displayed using a view.php file
public function query($query, $data = array(), $data_type = "object")
{
$con = $this->connect();
$stm = $con->prepare($query);
print_r($stm);
if ($stm) {
$check = $stm->execute($data); //right here is where I concluded that the code stops
print_r($check);//does not print anything
if ($check) {
if ($data_type == "object") {
$data = $stm->fetchAll(PDO::FETCH_OBJ);
} else {
$data = $stm->fetchAll(PDO::FETCH_ASSOC);
}
if (is_array($data) && count($data) > 0) {
return $data;
}
}
}
return false;
}
below is the part written in the controller to assign the query to the database to execute.
function index(){
$db = new Database();
$data = $db->query("select * from users");
if($data){echo $data;} //echos nothing because $data is empty
$this -> view('home', ['rows' => $data]);
}