MySQL・データーベースからPHPを使い記事を引き出し表示する授業
3日ほど学校で解説を受けながら練習してきたデーターベースからPHPを使って情報を引き出すプログラムがいったん出来上がった。
index.php 表示一覧
<?php require_once dirname(__FILE__).'/init.php'; $dbh=''; try{ $dbh = new PDO(DB_CONNECT,DB_USER,DB_PASS); }catch(Exception $e){ exit('システムエラーが発生しました'); } $sql="SELECT news_id,news_headline,news_date FROM news limit 3;"; $stmt=$dbh->query($sql); ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>無題ドキュメント</title> <style> body{ background:#000; } #container{ width:800px; margin:0 auto; background:#FFFFFF; border-radius:10px; background:linear-gradient(#666,#CCC); } h2{ background:linear-gradient(#906,#90F); text-align:center; border-radius:10px 10px 0 0; color:#FFFFFF; margin:0; border-bottom:solid 3px #fff; text-shadow:5px 5px 5px #000; } #news{ padding:5px; } a{ color:#00F; text-decoration:none; } ul{ list-style-type:none; } span{ color:#fff; } </style> </head> <body> <div id="container"> <h2>新着ニュース</h2> <div id="news"> <ul> <?php foreach($stmt as $row){ print'<li><a href="news.php?news_id='; print h($row['news_id']); print'">'; print h($row['news_headline']); print'</a><span>'; print h($row['news_date']); print"</li></span>\n"; } ?> </ul> </div> </div> </body> </html>
news.php ニュースの個別記事
<?php require_once dirname(__FILE__).'/init.php'; if(!isset($_GET['news_id'])||!is_numeric($_GET['news_id'])){ header(ROOT_URL.'/index.php'); exit; } $news_id=$_GET['news_id'];//IDをゲット $dbh=''; try{//DBに接続 $dbh = new PDO(DB_CONNECT,DB_USER,DB_PASS); }catch(Exception $e){ exit('システムエラーが発生しました'); } $sql="SELECT news_headline, news_article, news_date FROM news WHERE news_id=news_id;"; $stmt=$dbh->query($sql);//アロー演算子 $stmt->bindParam(':news_id',$news_id);//delete対策、紐付ける $stmt->execute(); $row=$stmt->fetch(PDO::FETCH_ASSOC); if(false===$row){ header(ROOT_URL.'/index.php'); exit; } foreach($row as $k=>$v){ $$k=$v; } ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>無題ドキュメント</title> <style> body{ background:#000; } #container{ width:800px; margin:0 auto; background:#FFFFFF; border-radius:10px; background:linear-gradient(#666,#CCC); padding-bottom:20px; } dt{ background:linear-gradient(#906,#90F); text-align:center; border-radius:10px 10px 0 0; color:#FFFFFF; margin:0; border-bottom:solid 3px #fff; font-size:24px; } p{ border-radius:50%; width:50px; height:50px; line-height:50px; text-align:center; background:#FFFFFF; color:#999; margin:0 0 20px 20px; } a{ display:block; } </style> </head> <body> <div id="container"> <dl> <?php print"<dt>".h($news_headline)." ".h($news_date)."</dt>\n"; print'<dd>'.nl2br(h($news_article)); print"</dd>\n"; ?> </dl> <p><a href="./index.php">TOP</a></p> </div> </body> </html>
init.php
<?php function h($str){ return htmlspecialchars($str,ENT_QUOTES,"utf-8"); } define('DB_CONNECT', 'mysql:host=localhost;dbname=oritani_newsfeed;charset=utf8'); define('DB_USER','root'); define('DB_PASS','root'); define('ROOT_URL','Location:http://localhost/oritani_php/newsfeed'); ?>
出来上がり