0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

negishi_tako完走したい!!Advent Calendar 2023

Day 4

PHPからMySQLへPDO接続

Last updated at Posted at 2023-12-03

PHPからDBへアクセスしたい!

PHPでデータベースの情報を参照したいときに使える

PDOとは

PHP5.1.0以降で動作するデータベース接続クラス。PEAR:Dbより高速。

実際に接続する

基本これ

code.php
try {
    // DB接続
    $pdo = new PDO(
        'mysql:host=localhost;dbname=データベースのテーブルの名前;',
        'ユーザ名',
        'パスワード'
    );
    $stmt = $pdo->prepare('SQL文');
    $stmt->execute();
} catch (PDOException $e) {
    //エラー発生時の処理
} finally {
    //正常時の処理
    $pdo = null;
}

SQLをセットしたらOK

code.php
try {
    // DB接続
    $pdo = new PDO(
        'mysql:host=localhost;dbname=データベースのテーブルの名前;',
        'ユーザ名',
        'パスワード'
    );
    $data = 'Qiita';
    $stmt = $pdo->prepare('INSERT INTO table (example) VALUES(:data)');
    $stmt->bindValue(':data', $data);
    $stmt->execute();
    //これより下は同じ

こんなかんじです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?