Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active June 28, 2024 18:56
Show Gist options
  • Save code-boxx/372bb08f4763937aed08b678ca900781 to your computer and use it in GitHub Desktop.
Save code-boxx/372bb08f4763937aed08b678ca900781 to your computer and use it in GitHub Desktop.
PHP MYSQL MVC Example

SIMPLE PHP MYSQL MVC EXAMPLE

https://code-boxx.com/simple-php-mvc-example/

NOTES

  1. Create a dummy database and import 1-users.sql.
  2. Change the database settings to your own in 1-model.php.
  3. Launch 3-view.html in your browser.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

<?php
class DB {
// (A) CONNECT TO DATABASE
public $error = "";
private $pdo = null;
private $stmt = null;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) CLOSE CONNECTION
function __destruct () {
if ($this->stmt!==null) { $this->stmt = null; }
if ($this->pdo!==null) { $this->pdo = null; }
}
// (C) RUN A SELECT QUERY
function select ($sql, $data=null) {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
return $this->stmt->fetchAll();
}
}
// (D) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (E) NEW DATABASE OBJECT
$_DB = new DB();
CREATE TABLE `users` (
`id` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD KEY `name` (`name`);
INSERT INTO `users` (`id`, `name`) VALUES
(24, 'Abby Ward'),
(21, 'Aleksandra Devine'),
(43, 'Aston Simmonds'),
(47, 'Aston Simmonds'),
(15, 'Beth Skywalker'),
(26, 'Bridget Wooten'),
(10, 'Coby Kelleigh'),
(20, 'Darrah Shadow'),
(9, 'Drake Adelaide'),
(12, 'Elizabeth Stewart'),
(19, 'Gareth Solderini'),
(42, 'Gregor Bryant'),
(46, 'Gregor Bryant'),
(13, 'Hannah Strickland'),
(52, 'Harvey Frame'),
(7, 'Imogene Thad'),
(53, 'Ismaeel Carty'),
(41, 'Issac Calderon'),
(45, 'Issac Calderon'),
(2, 'Jane Doe'),
(5, 'Jaslyn Keely'),
(40, 'Jax Howe'),
(39, 'Joey Whyte'),
(1, 'John Doe'),
(17, 'Joseph Stewart'),
(34, 'Julia Greaves'),
(31, 'Junior Douglas'),
(32, 'Kaiden Bentley'),
(16, 'Kenneth Sanders'),
(30, 'Keziah Knapp'),
(28, 'Kirstie Thomas'),
(33, 'Lawrence Murphy'),
(14, 'Leah Shan'),
(51, 'Marcus Best'),
(29, 'Maya Paine'),
(23, 'Myla Bostock'),
(50, 'Nathaniel Khan'),
(4, 'Peers Sera'),
(6, 'Richard Breann'),
(54, 'Rowan Avalos'),
(3, 'Rusty Terry'),
(37, 'Sacha Gross'),
(27, 'Sally Castillo'),
(11, 'Sarah Sanders'),
(18, 'Seth Sonnel'),
(38, 'Shannon Peterson'),
(25, 'Shayan Clements'),
(49, 'Shoaib Vickers'),
(35, 'Sulaiman Gilmour'),
(44, 'Taran Morin'),
(48, 'Taran Morin'),
(22, 'Thelma Kim'),
(8, 'Tillie Sharalyn'),
(36, 'Virgil Collier');
<?php
// (A) DATABASE CONNECTION
require "1-model.php";
// (B) SEARCH FOR USERS
$results = $_DB->select(
"SELECT * FROM `users` WHERE `name` LIKE ?",
["%{$_POST["search"]}%"]
);
// (C) OUTPUT RESULTS
echo json_encode(count($results)==0 ? null : $results);
<!DOCTYPE html>
<html>
<head>
<title>View (User Interface)</title>
<link rel="stylesheet" href="x-dummy.css">
</head>
<body>
<!-- (A) SEARCH JAVASCRIPT -->
<script>
function doSearch () {
// (A1) GET SEARCH TERM
var data = new FormData(document.getElementById("mySearch"));
// (A2) AJAX - USE HTTP:// NOT FILE://
fetch("2-controller.php", { method:"POST", body:data })
.then(res => res.json())
.then(res => {
let results = document.getElementById("results");
results.innerHTML = "";
if (res !== null) { for (let r of res) {
results.innerHTML += `<div>${r.id} - ${r.name}</div>`;
}}
});
return false;
}
</script>
<!-- (B) SEARCH FORM -->
<form id="mySearch" onsubmit="return doSearch()">
<input type="text" name="search" required>
<input type="submit" value="Search">
</form>
<!-- (C) SEARCH RESULTS -->
<div id="results"></div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Not really a good design</title>
<link rel="stylesheet" href="x-dummy.css">
</head>
<body>
<!-- (A) SEARCH FORM -->
<form method="post">
<input type="text" name="search" required>
<input type="submit" value="Search">
</form>
<!-- (B) SEARCH + SHOW RESULTS -->
<div id="results"><?php
if (isset($_POST["search"])) {
// (B1) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (B2) CONNECT TO DATABASE
$pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
// (B3) SEARCH
$stmt = $pdo->prepare("SELECT * FROM `users` WHERE `name` LIKE ?");
$stmt->execute(["%{$_POST["search"]}%"]);
$results = $stmt->fetchAll();
// (B4) OUTPUT
if (count($results)>0) { foreach ($results as $r) {
echo "<div>{$r["id"]} - {$r["name"]}</div>";
}}
}
?></div>
</body>
</html>
/* (X) NOT IMPORTANT - COSMETICS */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
padding: 10px;
width: 400px;
}
form {
display: flex;
padding: 10px;
border: 1px solid #efefef;
background: #f7f7f7;
}
input[type=text] {
flex-grow: 1;
padding: 10px;
border: 1px solid #cbcbcb;
}
input[type=submit] {
padding: 10px;
border: 0;
color: #fff;
background: #af2727;
cursor: pointer;
}
#results {
margin-top: 20px;
}
#results div {
padding: 10px;
background: #efefef;
}
#results div:nth-child(even) {
background: #fff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment