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?

More than 1 year has passed since last update.

【Mysql】PODの使い方

Last updated at Posted at 2023-01-18

PDOの使用

DB接続

$dbname = 'vocaloid';
$host = 'localhost';
$user = 'root';
$password = 'password';

// データベースとの接続
try {
    $pdo = new PDO('mysql:dbname='.$dbname.';host='.$host.';charset=utf8mb4', $user, $password);
}   catch (PDOException $e) {
    echo "データベース接続エラー :".$e->getMessage();
}

使用方法

1. DBファイルを読み込む

// DB接続ファイルを読み込む
require("../detabase/dbconnect.php");

2. prepareで処理内容を記載

$stmt = $pdo->prepare('SELECT * FROM users WHERE userid=?');

3. executeで実行

$stmt->execute(array("12345"));
$id = $stmt->execute(array("12345"));

上記のようにfetchを省略することも可能です。


4. fetchで値を取り出す

$user = $stmt->fetchAll(PDO::FETCH_ASSOC);

fetchを使うと余計な値を含まずに返してくれたり、希望する連想配列で返してくれたりもできる。
デフォルトはFETCH_BOTH

FETCH_BOTH:【配列のキー】カラム名&連番
FETCH_ASSOC:【配列のキー】カラム名のみ
FETCH_KEY_PAIR:指定した2つのカラムを「キー/値」のペアの配列にする
FETCH_COLUMN:指定した1つのカラムだけを1次元配列で取得

FETCH_ASSOCがおすすめ。

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?