PHPでデータベースに接続してみる。
下準備としてこちらの記事を参照し、joytasというユーザー名でphpappsデータベースにアクセスできるようにしておくこと。
テーブル作成
1.phpmyadminにjoytasユーザーでログインする。
2.データベースphpappsに[persons]テーブルを作成する。
CREATE TABLE persons( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(30), age INT );
3.初期データを挿入しておく
INSERT INTO persons(name,age)VALUES
("John",30),("Paul",28),("George",27),("Ringo",26);

PHPからのDB接続
4.ドキュメントルート以下にlesson8フォルダを作成し、その中に以下のようなconnect.phpを作成する。
<?php
try{
$db=new PDO('mysql:host=localhost;dbname=phpapps;charset=utf8','joytas','12345');
echo 'OK';
$db=null;
}catch(PDOException $e){
die('エラーメッセージ:'.$e->getMessage());
}
5.ブラウザから実行しOKと出力されることを確認する。エラーが出る場合はlocalhostの部分を127.0.0.1に変更してみること。
一覧画面の作成
6.read.phpを以下のように作成する。
<?php
try{
$db=new PDO('mysql:host=localhost;dbname=phpapps;charset=utf8','joytas','12345');
$stt=$db->prepare('SELECT * FROM persons');
$stt->execute();
}catch(PDOException $e){
die('エラーメッセージ:'.$e->getMessage());
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHPLesson</title>
</head>
<body>
<a href="create.php">新規登録</a>
<table border="1">
<?php while($row=$stt->fetch()):?>
<tr>
<td><?=$row['id']?></td>
<td><?=$row['name']?></td>
<td><?=$row['age']?></td>
<td><a href="update?id=<?=$row['id']?>">更新</a>
<a href="delete?id=<?=$row['id']?>" onclick="return confirm('id=<?=$row['id']?>を削除してよろしいですか?');">削除</a></td>
</tr>
<?php endwhile;?>
</table>
</body>
</html>
7.ブラウザで実行してみよう。以下のようになれば成功だ。(現時点ではリンクを押すとエラー)

新規データ追加
8.create.phpを以下のように作成する。
<?php
if(count($_POST)>0){
try{
$db=new PDO('mysql:host=localhost;dbname=phpapps;charset=utf8','joytas','12345');
$stt=$db->prepare('INSERT INTO persons(name,age) VALUES(?,?)');
$stt->bindValue(1,$_POST['name']);
$stt->bindValue(2,(int)$_POST['age'],PDO::PARAM_INT);
$stt->execute();
header('location:./read.php');
exit;
}catch(PDOException $e){
die('エラーメッセージ:'.$e->getMessage());
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHPLesson</title>
</head>
<body>
<form method="post">
<p>名前:<input type="text" name="name"></p>
<p>年齢:<input type="number" name="age"></p>
<button type="submit">送信</button>
</form>
</body>
</html>
9.ブラウザからアクセスして、以下のように入力し送信ボタンを押す。

10.一覧が表示されデータが挿入されてれば成功だ。

データ更新
10.update.phpを以下のように作成する。
<?php
if(count($_POST)>0){
try{
$db=null;
$db=new PDO('mysql:host=127.0.0.1;dbname=phpapps;charset=utf8','joytas','12345');
$stt=$db->prepare('UPDATE persons SET name=? , age=? WHERE id=?');
$stt->bindValue(1,$_POST['name']);
$stt->bindValue(2,$_POST['age'],PDO::PARAM_INT);
$stt->bindValue(3,$_POST['id'],PDO::PARAM_INT);
$stt->execute();
header('location:./read.php');
exit;
}catch(PDOException $e){
die('エラーメッセージ:'.$e->getMessage());
}
}else if(isset($_GET['id'])){
try{
$db=new PDO('mysql:host=localhost;dbname=phpapps;charset=utf8','joytas','12345');
$stt=$db->prepare('SELECT * FROM persons WHERE id=?');
$stt->bindValue(1,$_GET['id'],PDO::PARAM_INT);
$stt->execute();
$result=$stt->fetch(PDO::FETCH_ASSOC);
if($result===false){
$name='';
$age='';
$id='';
}else{
$name=$result['name'];
$age=$result['age'];
$id=$result['id'];
}
}catch(PDOException $e){
die('エラーメッセージ:'.$e->getMessage());
}
}else{
header('Location:./read.php');
exit;
}
function h($str){
return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHPLesson</title>
</head>
<body>
<form method="post">
<p>名前:<input type="text" name="name" value="<?=h($name)?>"></p>
<p>年齢:<input type="number" name="age" value="<?=h($age)?>"></p>
<input type="hidden" name="id" value="<?=h($id)?>">
<button type="submit">送信</button>
</form>
</body>
</html>
データの削除
<?php
if(isset($_GET['id'])){
try{
$db=new PDO('mysql:host=localhost;dbname=phpapps;charset=utf8','joytas','12345');
$stt=$db->prepare('DELETE FROM persons WHERE id=?');
$stt->bindValue(1,$_GET['id'],PDO::PARAM_INT);
$stt->execute();
$db=null;
}catch(PDOException $e){
die('エラーメッセージ:'.$e->getMessage());
}
}
header('location:./read.php');

コメント