Classes
Other classes extend the Database class to access the server. In this example class, the User extends Database. It has methods such as getAll, get, create, update, and destroy which are used to carry actions on the user data. This is the PHP for all SQL commands that run the queries for selecting, creating, updating and deleting. The methods getAll and get selects database rows from SQL and display the result, the create methods create the user to the database, the update method updates it and destroy method to delete the user.
Selecting
This has two methods getAll(public function getAll()) and get(public function get($id). The getAll method selects all users from the database and output the result in the window and the get method select the result of one of the user and output it on the screen.
Create
The create(public function Create()) method creates user detail on the database table. The details are entered and stored on the database for later users. We use this in select and destroy methods to select and destroy a particular user from the database table.
Update
The update(public function update()) methods updates user details from the database. It changed user detail if they typed the wrong name, email, or password. When this is changed it will update detail in the database and the user will have new detail. This is useful for a user when they have forgotten a password and want to change it.
Destroy
Destroy(public function destroy()) delete a user from the database table. It erases the user totally from the database. If the user needs to get to the website again, they will have to create their details on the website again.
<?php
class User extends Database{
public function auth(){
if(!empty($_COOKIE['id']) && !empty($_COOKIE['password'])){
$user = $this->get($_COOKIE['id']);
if($user && $user['password'] == $_COOKIE['password']){
return $user;
}
}
return false;
}
public function getAll()
{
$prepare = $this->conn->prepare("SELECT * FROM user");
$prepare->execute();
return $prepare->fetchAll();
}
public function get($id)
{
$prepare = $this->conn->prepare("SELECT * FROM user WHERE id = ?");
$prepare->execute([$id]);
return $prepare->fetch();
}
public function getByEmail($email)
{
$prepare = $this->conn->prepare("SELECT * FROM user WHERE email = ?");
$prepare->execute([$email]);
return $prepare->fetch();
}
public function Create($gender, $fName, $lName, $email, $password)
{
$prepare = $this->conn->prepare("INSERT INTO user(gender, fName, lName, email, password) VALUES (?, ?, ?, ?, ?)");
$prepare->execute([$gender, $lName, $fName, $email, $password]);
}
public function update($gender, $lName, $fName, $email, $id)
{
$prepare = $this->conn->prepare("UPDATE user SET gender = ?, fName = ?, lName = ?, email = ? WHERE id = ?");
$prepare->execute([$gender, $fName, $lName, $email, $id]);
}
public function destroy($id)
{
$prepare = $this->conn->prepare("DELETE FROM user WHERE id = ?");
$prepare->execute([$id]);
}
}
File: Classes.php