標準的な使い方
Select
use Phalcon\Db\Adapter\Pdo\Mysql as DB;
$config = [
"host" => "localhost",
"username" => "user",
"password" => "pass",
"dbname" => "service"];
$db = new DB($config);
$sql = "select * from `user`";
$rows = $db->fetchAll($sql);
foreach($rows as $row) {
echo $row["fullname"] . "\t" . $row["mail"] . "\n";
}
Fetch Object
use Phalcon\Db\Adapter\Pdo\Mysql as DB;
$config = [
"host" => "localhost",
"username" => "user",
"password" => "pass",
"dbname" => "service"];
$db = new DB($config);
$result = $db->query("select * from `user`");
$result->setFetchMode(Phalcon\Db::FETCH_OBJ);
$rows = $result->fetchAll();
foreach($rows as $row) {
echo $row->fullname . "\t" . $row->mail . "\n";
}
Other Query
$config = [
"host" => "localhost",
"username" => "user",
"password" => "pass",
"dbname" => "service"];
$db = new DB($config);
/**
* INSERT
*/
// Commmon.
$sql = "insert into `user` values(null, 'taro yamada', 'yamada@xx.co.jp', 'some password')";
$success = $db->execute($sql);
// using placeholder
$sql = "insert into `user` values(null, ?, ?, ?)";
$success = $db->execute($sql, ['taro yamada', 'yamada@xx.co.jp', 'some password']);
// 1 liner using the Array Format
$success = $db->insert("user", ['taro yamada', 'yamada@xx.co.jp', 'some password'], ['fullname', 'mail', 'password']);
// 1 liner using the Hash(dictionary) Format
$success = $db->insertAsDict("user",
[
"fullname" => "taro yamada",
"mail" => "yamda@xx.co.jp",
"password" => "some password"
]);
/**
* UPDATE
*/
// Common
$sql = "update `user` set `fullname`='hanako yamada' where `id`=1";
$success = $db->execute($sql);
// using placeholder
$sql = "update `user` set `fullname`=? where `id`=?";
$success = $db->execute($sql, ["hanako yamada", 1]);
// 1 liner using Array Format
$sucess = $db->update(
"user",
["fullname"],
["hanako yamada"]
"id=1"
);
// 1 liner using the Hash Format
$success = $db->updateAsDict(
"user",
["fullname"=>"hanako yamada"],
"id = 1"
);
// With specified option for the Escape
$success = $db->update(
"user",
["fullname"]
["hanako yamada"]
[
"condition" => "id =?",
"bind" => [1],
"bindTypes" => [PDO::PARAM_INT]
]
);
// this case, that specified the Type of valiable to integer by "bindTypes" option. however maybe never use..
/**
* DELETE
*/
// Common
$sql = $delete `user` where `id`=1";
$success = $db->execute($sql);
// using placeholder
$sql = $delete `user` where `id`=?";
$success = $db->execute($sql, [1]);
// 1 liner
$success = $db->delete("user", "id=?", [1]);
基本的なDBの利用、コンソールでちょこっと使いたいときは上記のどれかになると思います。
Controllerなどを利用するときはDIに登録して、Modelを操作することになりそうですけど、上記が分かってれば逆にModelの縛りはなくてもいいし、フレームワーク依存怖い。でも次の次あたりに書きます。
次は、トランザクションありき。