Learn how to configure and use the database in MINI PHP
MINI uses PDO (PHP Data Objects) for secure and efficient database operations. This guide covers everything you need to know about database setup and usage.
public function getAllSongs(){ $sql = "SELECT id, artist, track, link FROM song"; $query = $this->db->prepare($sql); $query->execute(); return $query->fetchAll();}
public function getSong($song_id){ $sql = "SELECT id, artist, track, link FROM song WHERE id = :song_id LIMIT 1"; $query = $this->db->prepare($sql); $parameters = array(':song_id' => $song_id); $query->execute($parameters); return $query->fetch();}
Named parameters (:parameter_name) are used instead of question marks for better readability and maintainability.
public function deleteSong($song_id){ $sql = "DELETE FROM song WHERE id = :song_id"; $query = $this->db->prepare($sql); $parameters = array(':song_id' => $song_id); $query->execute($parameters);}
$sql = "SELECT id, artist, track FROM song WHERE id = :song_id LIMIT 1";$query = $this->db->prepare($sql);$query->execute(array(':song_id' => $song_id));// Returns single object$song = $query->fetch();echo $song->artist;
public function getAmountOfSongs(){ $sql = "SELECT COUNT(id) AS amount_of_songs FROM song"; $query = $this->db->prepare($sql); $query->execute(); return $query->fetch()->amount_of_songs;}
PDO prepared statements automatically escape all input, making SQL injection impossible when used correctly. Never concatenate user input directly into SQL strings.
// ✅ CORRECT - Uses prepared statements$sql = "SELECT * FROM song WHERE id = :id";$query->execute(array(':id' => $user_input));// ❌ WRONG - Vulnerable to SQL injection$sql = "SELECT * FROM song WHERE id = " . $user_input;$query->execute();
The database connection is available in all controllers:
class MyController extends Controller{ public function myMethod() { // Access via model (recommended) $songs = $this->model->getAllSongs(); // Direct database access (not recommended) $query = $this->db->prepare($sql); }}
Best practice: Keep all database queries in the Model class, not in Controllers. This maintains proper separation of concerns.
While MINI doesn’t include a debug helper by default, you can debug queries:
$sql = "SELECT * FROM song WHERE id = :id";$parameters = array(':id' => $song_id);// Debug the queryvar_dump($sql);var_dump($parameters);$query = $this->db->prepare($sql);$query->execute($parameters);