PATRON MVC BUSCAR FETCH JS HTML CSS PHP MYSQL

3-view.html

<!DOCTYPE html>

<html>

  <head>

    <title>View (User Interface)</title>

    <link rel="stylesheet" href="x-dummy.css">


<style>


table, td, th {  

  border: 3px solid #ddd;

  text-align: left;

  border-collapse: collapse;

  width: 50%;

}



tr:nth-child(even) {background-color: #f2f2f2;}

</style>



  </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 = "";


        let output = '';


        if (res !== null) { for (let r of res) {


          results.innerHTML += `<div>${r.id} - ${r.nombre}</div>`;



  output += ` 


  

             <tr>


             <td>${r.id}</td>


             <td>${r.nombre}</td>

                                    

             </tr>

          

              `;


        }


    }

  document.getElementById("response").innerHTML = output;

      });

      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>


<hr>


<table>


<thead>


<tr>

    <th>id</th>

    <th>Nombre</th>

  

</tr>


</thead>



<tbody id='response'></tbody>



</table>




  </body>

</html>

-------------------------------------------------------

1-model.php

<?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", "bdpersonas");

define("DB_CHARSET", "utf8");

define("DB_USER", "root");

define("DB_PASSWORD", "root");


// (E) NEW DATABASE OBJECT

$_DB = new DB();


---------------------------------------------

2-controller.php

<?php

// (A) DATABASE CONNECTION

require "1-model.php";


// (B) SEARCH FOR USERS

$results = $_DB->select(

  "SELECT * FROM `personas` WHERE `nombre` LIKE ?",

  ["%{$_POST["search"]}%"]

);


// (C) OUTPUT RESULTS

echo json_encode(count($results)==0 ? null : $results);


------------------------------------------------------

4-not-good.php

<!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-dummy.css

/* (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;

}





Comentarios

Entradas populares de este blog

Como proteger una api json con php al pasar el parametro POST[id] de los ataques sql injection y xss

Copia de Seguridad de Archivo MS Access (.mdb) a Pendrive con VB6

NUMEROS SERIE DE DISCO RIGIDO Y PENDRIVER USB CON PHP