0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PDOを使ってMySQLのテーブルをPHPファイルのWebページに表示してみた

0
Last updated at Posted at 2023-03-21

PDOを使ってMySQLのテーブルをPHPファイルのWebページに表示してみた。

まずphpファイルを作成してwebブラウザで表示できることを確認する。

  1. MAMPを起動。
  2. htmlファイルの雛形を用意。
  3. VSCodeを起動して、MAMPのhtdocsフォルダを開く。
  4. 新規ファイルを作成し、htmlファイルの雛形をコピペしてhdoc.phpという名前で保存。
  5. chromeの検索バーで"http://localhost:8888/hdoc.php" を検索。表示されることを確認。

という手順で行った。

htmlファイルの雛形

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>ページタイトル</title>
</head>
<body>
	<h1>見出し1</h1>
	<p>段落1</p>
	<h2>見出し2</h2>
	<p>段落2</p>
</body>
</html>

次に、MySQLのテーブルの表示に必要なコードを挿入する

hdoc.phpのbodyの段落1を消して、MySQLのテーブルの表示に必要なコードを挿入。

<MySQLサーバーへの接続に必要な指定>

  • ホスト名、ユーザー名、パスワードはデフォルトだと"localhost"、"root"、"root"である。
  • portは、MySQLのデフォルトのポート番号は8889を設定している。
    MAMPでMySQLのポート番号を確認するには、MAMPアプリの画面左上の"Preferences"を選択する。"Ports"タブを選択して、MySQLのポート番号を確認できる。
  • dbnameは、接続したいデータベースの名前を選択する。
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>ページタイトル</title>
</head>
<body>
	<h1>見出し1</h1>
  <?php
    // MySQLサーバーへの接続
    $servername = "localhost"; // ホスト名
    $username = "root"; // ユーザー名
    $password = "root"; // パスワード
    $port = 8889; 
    $dbname = "shirokuma"; // データベース名

    try {
        $conn = new PDO("mysql:host=$servername;port=$port;dbname=$dbname", $username, $password);
        // PDOエラーモードを例外モードに設定
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected successfully"." <br>";
        echo "<br>";
        $stmt = $conn->prepare("SELECT * FROM menu");
        $stmt->execute();
        // set the resulting array to associative
        // 結果を取得
         $result = $stmt->fetchAll();

        // 結果を表示
        echo "price  menu"."<br>";
    foreach($result as $row) {
        echo $row['name']." ".$row['price']."円<br>";
        }
    } catch(PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
    }
    ?>
  
	<h2>見出し2</h2>
	<p>段落2</p>
</body>
</html>

chromeの検索バーで"http://localhost:8888/hdoc.php" を検索して、表示されることを確認する。
スクリーンショット 2023-03-21 23.39.51.png

0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?