test-PDO-class.php 2.13 KB
Newer Older
thibaut-felten's avatar
thibaut-felten committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
<?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>