I am currently teaching myself php from a tutorial. In one of the intermediary steps to developing a controller for handling a ‘DELETE’ request, I created the following:
use coreDatabase;
$config = require base_path("config.php");
$db = new Database($config['database']);
$currentUserId = 1;
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
$note = $db->query('select * from notes where id = :id', [
'id' => $_GET['id']
])->find();
authorize($note['UserId'] === $currentUserId);
$db->query('delete from notes where id = :id', [
'id' => $_GET['id']
])->find();
header('location: /notes');
exit();
}
This code references a Database object that I created in a preceding step of the tutorial:
namespace core;
use PDO;
class Database {
public $_connection;
public $statement;
public function __construct($config, $username = 'root', $password = '')
{
$dsn = 'mysql:'.http_build_query($config,'',';');
// dd($dsn);
$this->$_connection = new PDO($dsn, $username, $password, [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
public function query($query, $params = [])
{
$this->$statement = $this->$_connection->prepare($query);
$this->$statement->execute($params);
return $this;
}
public function find(){
return $this->$statement->fetch();
}
}
when I run this code, I get the following error: Uncaught Error: Call to undefined method PDOStatement::prepare().
I have been trying for a few hours now to understand why this is occurring, but I cannot figure it out. Does anyone have an idea what might be happening here? Thank you in advance.
When I comment out the first query, it works:
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
// $note = $db->query('select * from notes where NoteId = :id', [
// 'id' => $_GET['id']
// ])->find();
// authorize($note['UserId'] === $currentUserId);
$db->query('delete from notes where NoteId = :id', [
'id' => $_GET['id']
])->find();
header('location: /notes');
exit();
}
It also works if I comment out the second query:
$note = $db->query('select * from notes where NoteId = :id', [
'id' => $_GET['id']
])->find();
authorize($note['UserId'] === $currentUserId);
// $db->query('delete from notes where NoteId = :id', [
// 'id' => $_GET['id']
// ])->find();
header('location: /notes');
exit();
I can also make it work by re-instantiating the Database object between the two queries.
Somehow it works for the instructor, and his source code is identical to mine. I cannot understand why his works and mine doesn’t.
I appreciate any help that you can provide. Thank you in advance.
Anatoli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.