データベース名:db
テーブル1:orders
カラム:id(int not null primary 4), name(varchar 20), older(int 4)
+————+————-+——–+
| id | name | older |
+————+————-+——–+
| 1 | 山田 | 42 |
| 2 | 田中 | 22 |
| 3 | 佐藤 | 32 |
+————+————-+——–+
今回は上記のテーブルのレコードを例に表示していきます。
事前にMySQLでさくっと作成しておきましょう。
PHP上でMySQLのテーブルを表示するためのソースコード
test.php
<!doctype html> <html lang="ja"> <head> <title>UpdownTech</title> <meta charset="utf-8" /> <style> body{ margin: 10px; } h1{ color: lightgray; font-size: 48px; margin: 0px; text-align: right; } h2{ font-size: 16px; } h3{ font-size: 14px; margin: 50 0 10 0; } p{ font-size: 14px; } p.logout{ text-align: right; } th{ border: 1px solid white; padding: 5px; background-color: #ddf; } td{ border: 1px solid white; padding: 5px; background-color: #eee; } </style> <?php $message = '正しく表示されました。'; $data = []; #MySQLに接続する $mysqli = mysqli_connect('localhost', 'root', ' ', 'db'); #エラーの有無を確認する。エラーが発生しない場合0となる。:mysqli_connect_errno #エラーの有無を確認する。エラーが発生しない場合空欄となる。:mysqli_connect_error if(mysqli_connect_errno()){ $message = mysqli_connect_errno() . ":" . mysqli_connect_error() }else{ #エラーがなければ処理続行。文字化け防止。 mysqli_set_charset($mysqli, "utf8"); #ordersテーブルから全て選択(SELECT文) $sql = 'select * from orders'; if($result = mysqli_query($mysqli, $sql)){ $data = mysqli_fetch_all($result); }else{ $message = mysqli_connect_errno() . ":" . mysqli_connect_error(); } #リソースの開放 mysql_close($mysqli); } ?> <body> <h1>UpdownTech</h1> <p><?= $message ?></p> <table> <tr><th>id</th><th>name</th><th>older</th></tr> <?php foreach($data as $item){ ?> <tr> <!-- $data = mysqli_fetch_all($result);で取り出した$dataを$itemに格納 --> <th><?= $item[0]; ?></th> <td><?= $item[1]; ?></td> <td><?= $item[2]; ?></td> <td><?= $item[3]; ?></td> </tr> <?php } ?> </table> </body> </html>