bate's blog

調べたこと実装したことなどを取りとめもなく書きます。

phpからmysqlにアクセス

ちょっとしたサンプルを作ってphpmysqlを思い出す作業。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>

<a href="./">戻る</a>
<br>

<form method="post" action="register.php">
<p>ユーザー名:<br><input name="username" size="32"></p>
<p>パスワード:<br><input type="password" name="password" size="32"></p>
<p><input type="submit" value="登録"></p>

<?php
	if(@$_POST['username'] != "" && @$_POST['password'] != "") {
		echo $_POST['username']."<br>";
		echo $_POST['password']."<br>";
		$username = $_POST['username'];
		$password = $_POST['password'];
		
		$host = "localhost";
		$db_user = "phptest";
		$db_password = "phptest";
		$db = "bookshelf";

		/* 接続. */
		$mysqli = @new mysqli($host, $db_user, $db_password, $db);
		if($mysqli->connect_errno) {
			die("Connect Error: ".$mysqli->connect_errno);
		}

		echo "Success... ".$mysqli->host_info."<br>";
		
		/* 新規登録. */
		$query = "insert into user (name, password) values('$username', '$password')";
		$stmt = $mysqli->prepare($query);
		$stmt->execute();

		$query = "select * from user";
		$stmt = $mysqli->prepare($query);
		$stmt->execute();
		
		$stmt->bind_result($res_id, $res_name, $res_password);
		while($stmt->fetch()) {
			echo $res_id."<br>";
			echo $res_name."<br>";
			echo $res_password."<br>";
		}

		/* 切断. */
		$mysqli->close();
	}
?>

</body>

</html>
広告を非表示にする