Commit e32cfee0 authored by thibaut-felten's avatar thibaut-felten

TP2

parent 97c6d7f6
<?php <?php
define('_MYSQL_HOST','127.0.0.1'); define('_MYSQL_HOST','localhost');
define('_MYSQL_PORT',3306); define('_MYSQL_PORT',3306);
define('_MYSQL_DBNAME','dbtest'); define('_MYSQL_DBNAME','dbtest');
define('_MYSQL_USER','root'); define('_MYSQL_USER','root');
......
<?php
// initialise une variable $pdo connecté à la base locale
require_once("initPDO.php");
class User{
private $id;
private $name;
private $email;
// public function __construct($props = array()) { $this−>props = $props; }
// public function __get($prop) { return $this−>props[$prop]; }
// public function __set($prop, $val) { $this−>props[$prop] = $val; }
private static function getAllUsers(){
global $pdo;
$request = $pdo->prepare("select * from users");
$request->execute();
$allUsers = $request->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, get_called_class()
);
$pdo = null;
return $allUsers;
}
public static function showAllUsersAsTable(){
$allUsers = static::getAllUsers();
$result = '<table><tr><td>Id</td><td>Nom</td><td>Email</td></tr>';
foreach($allUsers as $user){
$result.= $user->toHtml();
}
$result .= "</table>";
echo $result;
}
private function toHtml(){
return('<tr><td>'.$this->id.'</td><td>'.$this->name.'</td><td>'.$this->email.'</td></tr>');
}
}
// POST
if(isset($_POST['name']) && isset($_POST['email'])) {
// ajout en POST
$addRequest = $pdo->prepare("INSERT INTO users(id, name, email) VALUES (NULL, '".$_POST["name"]."','".$_POST["email"]."')");
$addRequest->execute();
//SQL
}
// echo $allUsers;
/*** close the database connection ***/
?>
<!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();
?>
<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
// initialise une variable $pdo connecté à la base locale
require_once("initPDO.php");
class User{
private $id;
private $name;
private $email;
// public function __construct($props = array()) { $this−>props = $props; }
// public function __get($prop) { return $this−>props[$prop]; }
// public function __set($prop, $val) { $this−>props[$prop] = $val; }
private static function getAllUsers(){
global $pdo;
$request = $pdo->prepare("select * from users");
$request->execute();
$allUsers = $request->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, get_called_class()
);
$pdo = null;
return $allUsers;
}
public static function showAllUsersAsTable(){
$allUsers = static::getAllUsers();
$result = '<table><tr><td>Id</td><td>Nom</td><td>Email</td><td>Actions</td></tr>';
foreach($allUsers as $user){
$result.= $user->toHtml();
}
$result .= "</table>";
echo $result;
}
private function toHtml(){
$result = '<tr><td>'.$this->id.'</td><td>'.$this->name.'</td><td>'.$this->email;
$result.='</td><td><button>Edit</button>';
$result.='<form action="test-PDO-crud.php" method="GET"><button type="submit" value="Delete">Delete</button>';
$result.='</td></tr>';
return($result);
}
}
// POST
if(isset($_POST['name']) && isset($_POST['email'])) {
// ajout en POST
$addRequest = $pdo->prepare("INSERT INTO users(id, name, email) VALUES (NULL, '".$_POST["name"]."','".$_POST["email"]."')");
$addRequest->execute();
//SQL
}
// echo $allUsers;
/*** close the database connection ***/
?>
<!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();
?>
<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
// initialise une variable $pdo connecté à la base locale
require_once("initPDO.php"); // cf. doc / cours
// POST
if(isset($_POST['name']) && isset($_POST['email'])) {
// ajout en POST
$addRequest = $pdo->prepare("INSERT INTO users(id, name, email) VALUES (NULL, '".$_POST["name"]."','".$_POST["email"]."')");
$addRequest->execute();
//SQL
}
$request = $pdo->prepare("select * from users");
// à vous de compléter...
// afficher un tableau HTML avec les donnéees en utilisant fetch(PDO::FETCH_OBJ)
$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>";
// echo $allUsers;
/*** close the database connection ***/
$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
// initialise une variable $pdo connecté à la base locale
require_once("initPDO.php"); // cf. doc / cours
$request = $pdo->prepare("select * from users");
// à vous de compléter...
// afficher un tableau HTML avec les donnéees en utilisant fetch(PDO::FETCH_OBJ)
$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>";
// echo $allUsers;
/*** close the database connection ***/
$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>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TP1</title>
</head>
<body>
<h1>Users</h1>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php
// initialise une variable $pdo connecté à la base locale
require_once("initPDO.php"); // cf. doc / cours
$request = $pdo->prepare("select * from users");
// à vous de compléter...
// afficher un tableau HTML avec les donnéees en utilisant fetch(PDO::FETCH_OBJ)
/*** close the database connection ***/
$request->execute();
while($result = $request->fetch()){
echo("<tr>");
echo("<td>". $result["id"]. "</td>");
echo("<td>". $result["name"]. "</td>");
echo("<td>". $result["email"]. "</td>");
echo("</tr>");
}
echo("</table");
?>
</tbody>
</table>
</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 UsersController {
private $requestMethod;
public function __construct($requestMethod)
{
$this->requestMethod = $requestMethod;
}
public function processRequest()
{
switch ($this->requestMethod) {
case 'GET':
$response = $this->getAllUsers();
break;
default:
$response = $this->notFoundResponse();
break;
}
header($response['status_code_header']);
if ($response['body']) {
echo $response['body'];
}
}
private function getAllUsers()
{
// TODO ...
}
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
class UserModel
{
public static function getAllUsers() {
// TODO ... (cf. TP1)
}
}
\ 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' :
// GET api.php?/users
// POST api.php?/users
$controller = new UsersController($requestMethod);
break;
default :
header("HTTP/1.1 404 Not Found");
exit();
}
$controller->processRequest();
\ 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('_MYSQL_HOST','localhost');
define('_MYSQL_PORT',3306);
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
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