PHP+MariaDBでDB連携(基本編)
PHPでDB連携をしてみます。
まず、MariaDBで下記の準備をします。
- ユーザを作成(CREATE USER)
- ユーザに全権限を付与(GRANT ALL PRIVILEGES)
- データベースの作成(CREATE DATABASE)
- テーブルの作成(CREATE TABLE)
- レコードの登録(INSERT)
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
Query OK, 0 rows affected (0.00 sec)
MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO 'user001'@'localhost' IDENTIFIED BY 'pass001' WITH GRANT OPTION;
Query OK, 0 rows affected (0.00 sec)
Bye
Enter password: *******
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
Query OK, 1 row affected (0.00 sec)
Database changed
Query OK, 0 rows affected (0.16 sec)
+--------------+
| @@autocommit |
+--------------+
| 1 |
+--------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
+--------------+
| @@autocommit |
+--------------+
| 0 |
+--------------+
1 row in set (0.00 sec)
Query OK, 1 row affected (0.00 sec)
Query OK, 0 rows affected (0.02 sec)
+--------+----------+
| userid | password |
+--------+----------+
| guest | guest |
+--------+----------+
1 row in set (0.00 sec)
Bye
続いて、DBにSELECT文を発行するサンプルを載せる。
<html>
<body>
<?php
$result = $mysqli->query("SELECT userid, password FROM tbl001");
$row = $result->fetch_assoc();
echo 'user=' . htmlentities($row['userid']) . '<br>';
echo 'pass=' . htmlentities($row['password']) . '<br>';
$result->free();
$mysqli->close();
?>
</body>
</html>
user=guest
pass=guest
---------------------------------------
■ITとことんのトップページ
┗■PHPのトップページ
┗■本ページ