LoginSignup
3
0

More than 5 years have passed since last update.

PHPでSQLに接続して、データベースに登録した順番でコンテンツを全て表示する

Last updated at Posted at 2018-11-28
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="keywords" content="XXX">
<meta name="description" content="XXX">
<title>XXX</title>
<link rel="stylesheet" href="/main.css">
</head>

<body>
<?php
try {
//DB名、ユーザー名、パスワード
$dsn = 'mysql:dbname=データベース名;host=サーバー名';
$user = 'ユーザー名';
$password = 'データベース接続のパスワード';

$PDO = new PDO($dsn, $user, $password); //MySQLのデータベースに接続
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //PDOのエラーレポートを表示
$sql = 'SELECT * FROM contents'; //SELECT文を変数に格納
$stmt = $PDO->query($sql); // SQLの命令文を実行し、結果を変数に格納

// foreach文で配列の中身を一行ずつ出力
foreach ($stmt as $row) {
    echo $row['name'];
    echo nl2br($row['description']); //nl2br関数でデータベース登録時の改行を反映する
}

} catch (PDOException $e) {
exit('データベースに接続できませんでした。' . $e->getMessage());
}

?>

<?php echo $rows; ?>
</body>
</html>

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0