Skip to content

Instantly share code, notes, and snippets.

@mgng
Created December 10, 2013 06:14
Show Gist options
  • Save mgng/7886432 to your computer and use it in GitHub Desktop.
Save mgng/7886432 to your computer and use it in GitHub Desktop.
sqlite test
<?php
// PDOオブジェクト
$pdo = null;
// DBファイルパス
$db_path = './db.sqlite';
// 接続 $db_path ファイルがなければ作成される
try{
$pdo = new PDO( "sqlite:{$db_path}", '', '' );
} catch(Exception $e) {
var_dump($e);
exit;
}
// hogeテーブルが存在しなければcreate table して insert
$sql = "select * from sqlite_master where type = 'table' AND name = 'hoge'";
$stmt = $pdo->query( $sql );
if ( count( $stmt->fetchAll() ) === 0 ) {
$pdo->exec( "create table hoge ( id integer primarykey, name text )" );
$pdo->exec( "insert into hoge (id,name) values (1, 'テスト1')" );
$pdo->exec( "insert into hoge (id,name) values (2, 'テスト2')" );
$pdo->exec( "insert into hoge (id,name) values (3, 'テスト3')" );
}
// select
$sql = "select * from hoge WHERE id = :id";
$params = array( 'id' => 2 );
$stmt = $pdo->prepare($sql);
$stmt->execute( $params );
print_r( $stmt->fetchAll(PDO::FETCH_ASSOC) );
/*
Array
(
[0] => Array
(
[id] => 2
[name] => テスト2
)
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment