test-PDO-post.php 1.5 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
<?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>