Commit 922ab525 authored by Raphaël Peim's avatar Raphaël Peim

Add BackEnd TP files and move Images

parent 137b995c
.DS_Store
<?php
define('_MYSQL_HOST','localhost');
define('_MYSQL_PORT',8888);
define('_MYSQL_DBNAME','dbtest');
define('_MYSQL_USER','root');
define('_MYSQL_PASSWORD','root');
// define('__DEBUG', false);
define('__DEBUG', true);
// ================================================================================
// Debug utilities
// ================================================================================
if(__DEBUG) {
error_reporting(E_ALL);
ini_set("display_errors", E_ALL);
} else {
error_reporting(0);
ini_set("display_errors", 0);
}
function myLog($msg) {
if(__DEBUG) {
echo $msg;
}
}
function myDump($var) {
if(__DEBUG) {
var_dump($var);
}
}
?>
\ No newline at end of file
<?php
// returns true if $tableName exists
function tableExists($dbh, $tableName)
{
$result = $dbh->query("SHOW TABLES LIKE '$tableName'");
return $result;
}
try {
if(!tableExists($pdo,'town')) {
$pdo->exec("CREATE TABLE IF NOT EXISTS users (id INT not null AUTO_INCREMENT, name VARCHAR(30), email VARCHAR(30), primary key (id))");
$pdo->exec("DELETE FROM users");
$pdo->exec("INSERT INTO users (name,email) VALUES('riri', 'riri@disney.com')");
$pdo->exec("INSERT INTO users (name,email) VALUES('fifi', 'fifi@disney.com')");
$pdo->exec("INSERT INTO users (name,email) VALUES('loulou', 'loulou@disney.com')");
}
}
catch (PDOException $erreur) {
myLog('Erreur : '.$erreur->getMessage());
}
?>
<?php
// returns true if $tableName exists
function tableExists($dbh, $tableName)
{
$result = $dbh->query("SHOW TABLES LIKE '$tableName'");
return ($result !== false && $result->rowCount() > 0);
}
try {
if(!tableExists($pdo,'users')) {
$pdo->exec("CREATE TABLE IF NOT EXISTS users (id INT not null AUTO_INCREMENT, name VARCHAR(30), email VARCHAR(30), primary key (id))");
$pdo->exec("DELETE FROM users");
$pdo->exec("INSERT INTO users (name,email) VALUES('riri', 'riri@disney.com')");
$pdo->exec("INSERT INTO users (name,email) VALUES('fifi', 'fifi@disney.com')");
$pdo->exec("INSERT INTO users (name,email) VALUES('loulou', 'loulou@disney.com')");
}
}
catch (PDOException $erreur) {
myLog('Erreur : '.$erreur->getMessage());
}
?>
<?php
define('_MYSQL_HOST', 'localhost');
define('_MYSQL_PORT', 8888);
define('_MYSQL_DBNAME', 'dbtest');
define('_MYSQL_USER', 'root');
define('_MYSQL_PASSWORD', 'root');
$connectionString = "mysql:host=". _MYSQL_HOST;
if(defined('_MYSQL_PORT'))
$connectionString .= ";port=". _MYSQL_PORT;
$connectionString .= ";dbname=" . _MYSQL_DBNAME;
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8' );
try {
$pdo = new PDO($connectionString,_MYSQL_USER,_MYSQL_PASSWORD,$options);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $erreur) {
myLog('Erreur : '.$erreur->getMessage());
}
?>
\ No newline at end of file
<?php
require_once("initPDO.php");
require_once("createUserTable.php");
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// User class
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class User
{
// added by PDO
// private $id;
// private $name;
// private $email;
public static function getAllUsers() {
global $pdo; // we will improve this later
$request = $pdo->prepare("select * from users");
if (!$request) {
var_dump(debug_backtrace());
die('Error while doing request ' . $sqlRequest);
}
// $request->setFetchMode(PDO::FETCH_CLASS,'User');
$request->setFetchMode(PDO::FETCH_CLASS,get_called_class());
$request->execute();
$allUsers = $request->fetchAll();
return $allUsers;
}
// instance-side method to render a User object to HTML
public function toHtml() {
echo "<tr>"
. "<td>". $this->id . "</td>"
. "<td>". $this->name . "</td>"
. "<td>" . $this->email . "</td></tr>";
}
// class-side method to render an array of users as an HTML table
public static function showUsersAsTable($users) {
echo '<table><thead>
<tr><th>Id</th><th>Nom</th><th>Email</th></tr></thead><tbody>';
foreach($users as $u) {
$u->toHtml();
// print_r($u);
}
echo '</tbody></table>';
}
public static function showAllUsersAsTable() {
static::showUsersAsTable(static::getAllUsers());
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
table {
border-top: 1px solid black;
border-bottom: 1px solid black;
}
td {
text-align: center;
padding-left: 2em;
padding-right: 2em;
}
</style>
</head>
<body>
<h1>Users</h1>
<?php
User::showAllUsersAsTable();
?>
</body>
</html>
<?php
require_once("initPDO.php");
require_once("createUserTable.php");
class User
{
protected $props;
public function __get($prop) {
return $this->props[$prop];
}
public function __set($prop, $val) {
$this->props[$prop] = $val;
}
public static function executeRequest($req) {
$pdo = $GLOBALS['pdo'];
$request = $pdo->prepare($req);
if (!$request) {
myDump(debug_backtrace());
die('Error while doing request ' . $sqlRequest);
}
$request->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, get_called_class());
$request->execute();
return $request->fetchAll();
}
public static function getAllUsers() {
return static::executeRequest('select * from `users`');
}
// instance-side method to render a User object to HTML
public function toHtml() {
echo "<tr>"
. "<td>". $this->id . "</td>"
. "<td>". $this->name . "</td>"
. "<td>" . $this->email . "</td></tr>";
}
// class-side method to render an array of users as an HTML table
public static function showUsersAsTable($users) {
echo '<table><thead>
<tr><th>Id</th><th>Nom</th><th>Email</th></tr></thead><tbody>';
foreach($users as $u)
$u->toHtml();
echo '</tbody></table>';
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Get Results
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$allUsers = User::getAllUsers();
$allUsersEmails = [];
foreach($allUsers as $u)
$allUsersEmails[] = $u->email;
$allUsersEmailsAsJSON = json_encode($allUsersEmails);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Close the database connection
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$pdo = null;
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
var availableTags = <?php echo $allUsersEmailsAsJSON; ?>;
$( "#tags" ).autocomplete({
source: function(request, response) {
var filteredArray = $.map(availableTags, function(item) {
if(item.indexOf(request.term) == 0)
return item;
else
return null;
});
response(filteredArray);
},
minLength: 1
});
});
</script>
<style>
table {
border-top: 1px solid black;
border-bottom: 1px solid black;
}
td {
text-align: center;
padding-left: 2em;
padding-right: 2em;
}
</style>
</head>
<body>
<h1>Users</h1>
<?php
User::showUsersAsTable($allUsers);
?>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
<?php
require_once("initPDO.php");
if(isset($_POST['name']) && isset($_POST['email'])) {
$add = $pdo->prepare("INSERT INTO `users` (`id`, `name`, `email`) VALUES (NULL, '" . $_POST['name'] . "', '" . $_POST['email'] . "')");
$add->execute();
}
$request = $pdo->prepare("select * from users");
$request->execute();
$user = $request->fetch(PDO::FETCH_OBJ);
$allUsers = '<table><tr><td>Id</td><td>Nom</td><td>Email</td></tr>';
while(!empty($user)) {
$allUsers .= '<tr><td>'.$user->id.'</td><td>'.$user->name.'</td><td>'.$user->email.'</td></tr>';
$user = $request->fetch(PDO::FETCH_OBJ);
}
$allUsers .= "</table>";
$pdo = null;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
table {
border-top: 1px solid black;
border-bottom: 1px solid black;
}
td {
text-align: center;
padding-left: 2em;
padding-right: 2em;
}
</style>
</head>
<body>
<h1>Users</h1>
<?php
echo $allUsers;
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>name : <input type="text" name="name" /></p>
<p>email : <input type="text" name="email" /></p>
<input type="submit" value="Add">
</form>
</body>
</html>
<?php
require_once("initPDO.php");
require_once("createUserTable.php");
class User
{
protected $props;
public function __get($prop) {
return $this->props[$prop];
}
public function __set($prop, $val) {
$this->props[$prop] = $val;
}
public static function executeRequest($req) {
global $pdo;
$request = $pdo->prepare($req);
if (!$request) {
myDump(debug_backtrace());
die('Error while doing request ' . $sqlRequest);
}
$request->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, get_called_class());
$request->execute();
return $request->fetchAll();
}
public static function getAllUsers() {
return static::executeRequest('select * from `users`');
}
// instance-side method to render a User object to HTML
public function toHtml() {
// print_r($this);
echo "<tr>"
. "<td>". $this->id . "</td>"
. "<td>". $this->name . "</td>"
. "<td>" . $this->email . "</td></tr>";
}
// class-side method to render an array of users as an HTML table
public static function showUsersAsTable($users) {
echo '<table><thead>
<tr><th>Id</th><th>Nom</th><th>Email</th></tr></thead><tbody>';
foreach($users as $u) {
print_r($u);
$u->toHtml();
}
echo '</tbody></table>';
}
public static function showAllUsersAsTable() {
static::showUsersAsTable(static::getAllUsers());
}
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
table {
border-top: 1px solid black;
border-bottom: 1px solid black;
}
td {
text-align: center;
padding-left: 2em;
padding-right: 2em;
}
</style>
</head>
<body>
<h1>Users</h1>
<?php
User::showAllUsersAsTable();
?>
</body>
</html>
<?php
require_once("initPDO.php");
$request = $pdo->prepare("select * from users");
$request->execute();
$user = $request->fetch(PDO::FETCH_OBJ);
$allUsers = '<table><tr><td>Id</td><td>Nom</td><td>Email</td></tr>';
while(!empty($user)) {
$allUsers .= '<tr><td>'.$user->id.'</td><td>'.$user->name.'</td><td>'.$user->email.'</td></tr>';
$user = $request->fetch(PDO::FETCH_OBJ);
}
$allUsers .= "</table>";
$pdo = null;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
table {
border-top: 1px solid black;
border-bottom: 1px solid black;
}
td {
text-align: center;
padding-left: 2em;
padding-right: 2em;
}
</style>
</head>
<body>
<h1>Users</h1>
<?php
echo $allUsers;
?>
</body>
</html>
<?php
class DatabaseConnector {
protected static $pdo = NULL;
public static function current(){
if(is_null(static::$pdo))
static::createPDO();
return static::$pdo;
}
protected static function createPDO() {
// $db = new PDO("sqlite::memory");
$connectionString = "mysql:host=". DB_HOST;
if(defined('_MYSQL_PORT'))
$connectionString .= ";port=". DB_PORT;
$connectionString .= ";dbname=" . DB_DATABASE;
static::$pdo = new PDO($connectionString, DB_USERNAME, DB_PASSWORD);
static::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
?>
\ No newline at end of file
<?php
class UserModel {
public static function createUser($post) {
if(isset($post['name']) && isset($post['email'])) {
$request = DatabaseConnector::current()->prepare("INSERT INTO `users` (`id`, `name`, `email`) VALUES (NULL, '" . $post['name'] . "', '" . $post['email'] . "')");
$request->execute();
return [http_response_code(200), "Utilisateur ajouté"];
}
else {
return [http_response_code(400), "Les paramètres fournis sont incorrects"];
}
}
public static function getUser($id) {
$request = DatabaseConnector::current()->prepare("SELECT * FROM `users` WHERE `id` = " . $id);
$request->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, get_called_class());
$request->execute();
$user = $request->fetchAll();
if(!empty($user)) {
return [http_response_code(200), $user];
}
else {
return [http_response_code(400), "L'utilisateur n'existe pas'"];
}
}
public static function getAllUsers() {
$request = DatabaseConnector::current()->prepare("select * from users");
$request->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, get_called_class());
$request->execute();
$allUsers = $request->fetchAll();
return [http_response_code(200), $allUsers];
}
public static function updateUser($post, $id) {
$request = DatabaseConnector::current()->prepare("SELECT * FROM `users` WHERE `id` = " . $id);
$request->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, get_called_class());
$request->execute();
$user = $request->fetchAll();
if(!empty($user)) {
$quest = "";
if (isset($post['name']) && isset($post['email']))
$quest = "UPDATE `users` SET `name` = '" . $post['name'] . "', `email` = '" . $post['email'] . "' WHERE `users`.`id` = " . $id;
else if (isset($post['name']) && !isset($post['email']))
$quest = "UPDATE `users` SET `name` = '" . $post['name'] . "' WHERE `users`.`id` = " . $id;
else if (!isset($post['name']) && isset($post['email']))
$quest = "UPDATE `users` SET `email` = '" . $post['email'] . "' WHERE `users`.`id` = " . $id;
print_r($post);
echo "\n";
if ($quest != "") {
$request = DatabaseConnector::current()->prepare($quest);
$request->execute();
return [http_response_code(200), "Utilisateur modifié"];
}
else
return [http_response_code(400), "Les paramètres fournis sont incorrects"];
}
else {
return [http_response_code(400), "L'utilisateur n'existe pas"];
}
}
public static function deleteUser($id) {
$request = DatabaseConnector::current()->prepare("SELECT * FROM `users` WHERE `id`=" . $id);
$request->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, get_called_class());
$request->execute();
$user = $request->fetchAll();
if(!empty($user)) {
$request = DatabaseConnector::current()->prepare("DELETE FROM `users` WHERE `id` =" . $id);
$request->execute();
return [http_response_code(200), "Utilisateur supprimé"];
}
else {
return [http_response_code(400), "L'utilisateur n'existe pas"];
}
}
}
?>
\ No newline at end of file
<?php
class UsersController {
private $requestMethod;
public function __construct($requestMethod) {
$this->requestMethod = $requestMethod;
}
public function processRequest($post = [], $id = 0) {
switch ($this->requestMethod) {
case 'GET':
if ($id == 0)
$response = $this->getAllUsers();
else
$response = $this->getUser($id);
break;
case 'POST':
$response = $this->createUser($post);
break;
case 'PUT':
$response = $this->updateUser($post, $id);
break;
case 'DELETE':
$response = $this->deleteUser($id);
break;
default:
$response = $this->notFoundResponse();
break;
}
header($response['status_code_header']);
if ($response['body']) {
print_r($response['body']);
}
}
private function createUser($post) {
$response = [];
[$response['status_code_header'], $response['body']] = UserModel::createUser($post);
return $response;
}
private function getUser($id) {
$response = [];
[$response['status_code_header'], $response['body']] = UserModel::getUser($id);
return $response;
}
private function getAllUsers() {
$response = [];
[$response['status_code_header'], $response['body']] = UserModel::getAllUsers();
return $response;
}
private function updateUser($post, $id) {
$response = [];
[$response['status_code_header'], $response['body']] = UserModel::updateUser($post, $id);
return $response;
}
private function deleteUser($id) {
$response = [];
[$response['status_code_header'], $response['body']] = UserModel::deleteUser($id);
return $response;
}
private function notFoundResponse() {
$response['status_code_header'] = 'HTTP/1.1 404 Not Found';
$response['body'] = null;
return $response;
}
}
?>
\ No newline at end of file
<?php
require "bootstrap.php";
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE");
header("Access-Control-Max-Age: 3600"); // Maximum number of seconds the results can be cached.
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
function getRoute($url){
$url = trim($url, '/');
$urlSegments = explode('/', $url);
$scheme = ['controller', 'params'];
$route = [];
foreach ($urlSegments as $index => $segment){
if ($scheme[$index] == 'params'){
$route['params'] = array_slice($urlSegments, $index);
break;
} else {
$route[$scheme[$index]] = $segment;
}
}
return $route;
}
// $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
$route = getRoute($uri);
$requestMethod = $_SERVER["REQUEST_METHOD"];
$controllerName = $route['controller'];
switch($controllerName) {
case 'users' :
$controller = new UsersController($requestMethod);
$controller->processRequest($_POST);
break;
case 'user' :
$controller = new UsersController($requestMethod);
$controller->processRequest(fopen("php://input", "r"), $route['params'][0]);
break;
default :
header("HTTP/1.1 404 Not Found");
exit();
}
?>
\ No newline at end of file
<?php
require "config.php";
// simplest auto loader cf. doc PHP
// we will revisit that later
spl_autoload_register(function ($class_name) {
$classFile = $class_name . '.php';
include $classFile;
});
?>
\ No newline at end of file
<?php
define('DB_HOST','localhost');
define('DB_PORT',8888);
define('DB_DATABASE','dbtest');
define('DB_USERNAME','root');
define('DB_PASSWORD','root');
// define('__DEBUG', false);
define('__DEBUG', true);
// ================================================================================
// Debug utilities
// ================================================================================
if(__DEBUG) {
error_reporting(E_ALL);
ini_set("display_errors", E_ALL);
} else {
error_reporting(0);
ini_set("display_errors", 0);
}
function myLog($msg) {
if(__DEBUG) {
echo $msg;
}
}
function myDump($var) {
if(__DEBUG) {
var_dump($var);
}
}
?>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment