PHP MYSQL

SIMPLE MVC EXAMPLE WITH PHP MYSQL

(quick guide & example)

class DB {   CONNECT TO DATABASE   function __construct () {     $this->pdo = new PDO("mysql:host=     HOST;dbname=NAME;charset=utf8mb4",     USER, PASSWORD);   }

MODEL (DATABASE)

01

  RUN SELECT SQL QUERY   function select ($sql, $data) {     $this->stmt = $this->pdo->prepare($sql);     $this->stmt->execute($data);      return $this->stmt->fetchAll();   } }

CONNECT DATABASE require "MODEL.PHP";  $DB = new DB();

CONTROLLER (PROCESS)

02

DATABASE SEARCH echo json_encode($DB->select(   "SELECT * FROM `TABLE` WHERE `COL`   LIKE ?", ["%{$_POST["search"]}%"]  ));

HTML SEARCH FORM & RESULTS <form id=form"            onsubmit="return search()">    <input type="text" name="search">    <input type="submit" value="Find"> </form> <div id="res"></div>

VIEW (USER INTERFACE)

03

function search () {   GET SEARCH TERM   var data = new FormData(document.   getElementById("myForm"));

VIEW (USER INTERFACE)

04

  AJAX FETCH   fetch("CONTROLLER.PHP",    { method:"POST", body:data })   .then(res => res.json()).then(res => {     let d = document.getElementById("res");     d.innerHTML = "";     if (res !== null) { for (let r of res) {       d.innerHTML += `<p>${r.name}</p>`;     }}   });   return false; }