0
0

More than 1 year has passed since last update.

PHPでMySQLのデータを出力する

Last updated at Posted at 2022-07-02

PHPでMySQL連携ができたので、忘れないようにメモを残します。

MySQLの設定

MySQLに以下のような設定をしました。なおログインユーザはrootで、パスワードはpasswordにしています。

MySQLのデータベース
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| shop               |
| sys                |
+--------------------+
shopデータベース内のテーブル
+----------------+
| Tables_in_shop |
+----------------+
| member         |
+----------------+
memberテーブル内のデータ
+--------+------+
| name   | age  |
+--------+------+
| satou  |   29 |
| tanaka |   35 |
| ueda   |   25 |
| yamada |   40 |
+--------+------+

PHPファイル

下のshop.phpファイルを/var/www/html/配下に置きます。

shop.php
<html>
<head>
</head>
<body>
member list<br>
<?php
$dsn = 'mysql:host=localhost;dbname=shop;charset=utf8';
$user = 'root';
$password = 'password';
try {
        $pdo = new PDO($dsn,$user,$password);
} catch(PDOException $e) {
        exit('Database error. ('.$e->getMessage().')');
}
$sql = 'select name,age from member where name like :name';
$stmt = $pdo->prepare($sql);
$name = '%'.$_GET['name'].'%';
$stmt->bindParam(':name',$name,PDO::PARAM_STR);
$stmt->execute();
$all = $stmt->fetchAll();
foreach($all as $row){
        print htmlspecialchars($row['name'],ENT_QUOTES,'UTF-8').'('.$row['age'].")<br>\n";
}
?>
</body>
</html>

これはmemberテーブル内のnameを検索し出力するプログラムです。
※SQLインジェクション対策としてbindParamを使い、クロスサイトスクリプティング(XSS)対策としてhtmlspecialcharsを使用しています。

動作確認

Firefoxでlocalhost\shop.php?name=daと入力します。(daを含む名前を持つデータのみ出力します)
shop.png

予定通り、uedaとyamadaが出力されました。

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