I'm a newbie in need of some help!
Both 'user_id' and 'id' are of type integer in the database tables
I'm matching 'user_id' with 'id' to validate the creator of a simple note. The following code snippet will always return the 403 not authorized, using the strict operator ===
authorize($note['user_id'] === $currentUserId);
... but it will return the expected result if I use the comparison ==
This is returned from dd($currentUserId);
int(2)
...and this is returned with dd($notes);
[0]=>
array(3) {
["id"]=>
string(2) "26"
["body"]=>
string(17) "Keep Learning PHP"
["user_id"]=>
string(1) "2"
}
The ["id"]=> string(2) "26" , is the id of the posted note. $currentUserId = 2; is hardcoded for now as '2'.
I don't understand why it's failing with ===
or if the value being passed as a string, or as an integer?
The following code will not trigger the 403 error
// note.php
<?php
$config = require('config.php');
$db = new Database($config['database']);
$heading = 'Note';
// hardcode user 'id' to allow viewing the notes created by that user id //
$currentUserId = 2;
$note = $db->query('select * from notes where id = :id', [
'id' => $_GET['id']]
)->findOrFail();
// dd($currentUserId); //
authorize($note['user_id'] == $currentUserId);
// dd($id); //
require "views/note.view.php";
// notes.php
<?php
$config = require('config.php');
$db = new Database($config['database']);
$heading = 'My Notes';
// lists what notes are created by user_id = ' //
$notes = $db->query('select * from notes where user_id = 2')->get();
// dd($notes); //
require "views/notes.view.php";
// functions.php
<?php
function dd($value)
{
echo "<pre>";
var_dump($value);
echo "</pre>";
die();
}
function urlIs($value) {
return $_SERVER['REQUEST_URI'] === $value;
}
function authorize($condition, $status = Response::FORBIDDEN) {
if (! $condition) {
abort($status);
}
}
// Database.php
<?php
class Database
{
public $connection;
public $statement;
public function __construct($config, $username = 'root', $password = '')
{
$dsn = 'mysql:' . http_build_query($config, '', ';');
$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 get()
{
return $this->statement->fetchAll();
}
public function find()
{
return $this->statement->fetch();
}
public function findOrFail()
{
$result = $this->find();
if (! $result) {
abort();
}
//dd($result);
return $result;
}
}