接続
require_once 'Zend/Db.php';
$params = array ('host' => 'IPパドレス',
'username' => 'ログイン名',
'password' => 'パスワード',
'dbname' => 'データベース名');
$db = Zend_Db::factory('PDO_MYSQL', $params);
SQLインジェクション対策
$db->quoteInto('id = ?', 1);
select
$sql = 'SELECT * FROM テーブル名 WHERE id = :ID';
$ary = array('title' => 'Sir');
全行取得
$result = $db->fetchAll($sql,$ary);
全行連想配列で取得
$result = $db->fetchAssoc($sql,$ary);
すべての行の最初のカラムを取得
$result = $db->fetchCol($sql,$ary);
最初の行の最初のカラム
$result = $db->fetchfetchOne($sql,$ary);
最初と2番目のカラムを連想配列にする
$result = $db->fetchPairs($sql,$ary);
最初の行
$result = $db->fetchRow($sql,$ary);
insert
$table = 'test';
$value = array (
'id' => $db->lastInsertId() + 1,
'name' => 'ggg',
'pass' => '1234',
);
$result = $db->insert($table, $value);
// auto incrementの値を取得
$id = $db->lastInsertId();
update
$table = 'test';
$set = array ('id' => '2');
$where = $db->quoteInto('id = ?', '1');
$result = $db->update($table, $set, $where);
$resultは実行された行数を返す。
delete
$table = 'test';
$where = $db->quoteInto('id = ?', '1');
$result = $db->delete($table, $where);
$resultは実行された行数を返す。
whereに複数の条件をつける。複雑な条件ならqueryをつかう。
$where = array(
$db->quoteInto('name = ?', 'baz'),
$db->quoteInto('age in(?)', array(20, 21, 22))
);
トランザクション
$db->beginTransaction();
try {
~
$db->commit();
} catch (Exception $ex) {
$db->rollBack();
echo $ex->getMessage();
}