データの一覧画面を作る場合

今回は DBから データを取得し、
一覧画面にする方法です
最初に PHPで MySQL のDB接続を行います
mysql_connect(‘localhost’,’root’,”) or die(mysql_error());
mysql_select_db(‘mysql’);
mysql_query(‘SET NAMES UTF8’);
続いて テーブルからデータを取得し、結果を変数 $recordSet へ格納します
$recordSet = mysql_query(‘SELECT * FROM my_items ORDER BY id DESC‘);
DESC を指定すると小さい順に並び替えします
そして、while文を使い、このループ機能を使うことで
全データを書き出します
while($table = mysql_fetch_assoc($recordSet){
print(htmlspecialchars($table[‘id’]);
print(htmlspecialchars($table[‘maker_id’]);
print(htmlspecialchars($table[‘item_name’]);
print(htmlspecialchars($table[‘price’]);
}
これで、データを表示することができます
print()で表示する時に
htmlspecialchars() を使っているのは
html で特殊な文字として扱われる記号などを表示するためです
詳しくは
特殊文字をHTMLエンティティに変換する
に載っていましたが
&lt; と記述しないと HTMLでは < となりません
こういった文字を適切に変換するために
htmlspecialchars() を使っています
ちなみにこれだけだとわけのわからない出力になってしまうため
テーブルにまとめます
<table width=”100%”>
<tr>
<th scope=”col”>ID</th>
<th scope=”col”>メーカー</th>
<th scope=”col”>商品名</th>
<th scope=”col”>価格</th>
</tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
ちなみに、 scope=”col” はCSSの設定です
次に、PHPの処理を組み込みます
PHPのコードは <?php?>
で囲むことで、HTMLの中に部分的に組み込むことができます
<table width=”100%”>
<tr>
<th scope=”col”>ID</th>
<th scope=”col”>メーカー</th>
<th scope=”col”>商品名</th>
<th scope=”col”>価格</th>
</tr>
<?php
while($table = mysql_fetch_assoc($recordSet)){
?>

<tr>
<td><?php print(htmlspecialchars($table[‘id’]));?></td>
<td><?php print(htmlspecialchars($table[‘maker_id’]));?></td>
<td><?php print(htmlspecialchars($table[‘item_name’]));?></td>
<td><?php print(htmlspecialchars($table[‘price’]));?></td>
</tr>
<?php
}
?>

</table>
赤字にしたのが PHPを組み込んだ部分です
参考にした書籍では
PHPだけでなく
HTMLのタグ、そしてCSSの知識が必要なため、ある程度の経験が必要になっています
ちなみに、
メーカーを番号ではなく人の名前にするには
mysql_query()

$recordSet = mysql_query(‘SELECT * FROM my_items ORDER BY id DESC’);
となっているのを
$recordSet = mysql_query(‘SELECT m.name, i.* FROM makers m, my_items i
WHERE m.id=i.maker_id
ORDER BY id DESC’);
へ変更し
<td><?php print(htmlspecialchars($table[‘maker_id’]));?></td>

<td><?php print(htmlspecialchars($table[‘name’]));?></td>
と変更し保存します

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です