PHP MYSQL

SIMPLE MVC EXAMPLE WITH PHP MYSQL

class DB {   CONNECT TO DATABASE   function __construct () {     $this->pdo = new PDO("mysql:host=     HOST;dbname=NAME;charset=utf8",     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 $results = $DB->select(   "SELECT * FROM `TABLE` WHERE `COL`   LIKE ?", ["%{$_POST["search"]}%"]  );

OUTPUT RESULTS echo json_encode($results);

HTML SEARCH FORM <form id="myForm"            onsubmit="return search()">    <input type="text" name="search"/>    <input type="submit" value="Find"/> </form>   SEARCH RESULTS <div id="sr"></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 sr = document.getElementById("sr");     sr.innerHTML = "";     if (res !== null) { for (let r of res) {       sr.innerHTML += `<p>${r.name}</p>`;     }}   });   return false; }