Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Last active September 22, 2018 04:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yano3nora/1322936f9c41bcce690dd97a88fecd09 to your computer and use it in GitHub Desktop.
Save yano3nora/1322936f9c41bcce690dd97a88fecd09 to your computer and use it in GitHub Desktop.
[php: PDO] PDO - PHP Data Objects note. #php

Overview

PDO - php.net

PHP 5.1 より実装された DB 接続・操作クラス。MySQL や PostgreSQL などデータベース差異を PDO でラップして利用でき、プリペアドステートメントなどの機能も利用可能。エラー時は PDOException 例外をスローするため、try catch で異常系も制御しやすい。mysql や mysqli は将来的に非推奨となる。

Refs

Sample

/**
 * Update users.token with transaction.
 * @param  int    $id
 * @param  string $token
 * @return bool   
 * @throws PDOException
 */
public function updateUserToken(int $id, string $token): bool
{
    try {
        $dbh = new \PDO(DSN, DB_USER, DB_PASS);
        $dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $dbh->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        $dbh->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ);
        $dbh->beginTransaction();
        $stmt = $dbh->prepare('UPDATE users SET token = :token WHERE id = :id');
        $stmt->bindValue(':token', $token, \PDO::PARAM_STR);
        $stmt->bindValue(':id',    $id,    \PDO::PARAM_INT);
        $stmt->execute();
        return $dbh->commit();
    } catch (\PDOException $e) {
        $dbh->rollback();
        throw $e;
    }
}

TIPS

返り値のカスタマイズ

全体を連想配列で → fetch_assoc 1レコードをオブジェクト(ユーザ定義クラス)で → fetch_class

Select の 行数 count

$sql = 'select count(*) from table where name = :name';
$stmt = $pdo -> prepare($sql);
$stmt -> execute(['name' => 'おなまえ']);
$count = $stmt -> fetchColumn();
echo $count;

直前 create した id

create系のexecute()のあとで $pdo->lastInsertId() で返り値もらってください。

直前 execute の作用行数

$pdo->execute();
$affected = $pdo->rowCount();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment