WordPressでは、いくつか使い回しのできる外部ライブラリが組み込まれていて、そのうちの一つがezSQLだ。このezSQLは、WordPress以外のPHP+MySQLなサービスを作るときにとても重宝する。
その簡単な設定方法をご紹介する。
設定
1. 上記からダウンロードし、任意のフォルダに入れておく(ezSQLなど)
2. フォルダの中に、設定ファイルを作成する。*.phpで以下の内容を入れておく(わかりやすいように、WordPressと同じ名前でDEFINEしている)。
<?php
include_once "shared/ez_sql_core.php";
include_once "mysql/ez_sql_mysql.php";
define('DB_NAME', 'db_name');
/** MySQL データベースのユーザー名 */
define('DB_USER', 'db_user');
/** MySQL データベースのパスワード */
define('DB_PASSWORD', 'db_password');
/** MySQL のホスト名 */
define('DB_HOST', 'localhost');
/** データベースのテーブルを作成する際のデータベースの文字セット */
define('DB_CHARSET', 'utf8');
/** データベースの照合順序 (ほとんどの場合変更する必要はありません) */
define('DB_COLLATE', '');
$db = new ezSQL_mysql( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
?>
3. あとはこのファイルをincludeすれば、WordPressで使われている$wpdbと同様に、$dbとして使える。
もちろん、WordPressで使われているget_post()やWP_Query()は使えないが、簡単にmySQLでクエリを実行できる。
使い方
主に使う関数は(こちらより抜粋)
$db->get_results - Get multiple row result set from the database $db->get_row - Get one row from the database $db->get_col - Get one column from query based on column offset $db->get_var - Get one variable, from one row, from the database $db->query - Send a query to the database (and if any results, cache them) $db->debug - Print last SQL query and returned results (if any) $db->vardump - Print the contents and structure of any variable $db->select - Select a new database to work with $db->get_col_info - Get information about columns such as column name $db = new db - Initiate new db object
ほかにも様々な関数が用意されている。こちらが詳しい: http://blog.rakkoc.com/2012/06/ezsql-samples/
色々と楽になること請け合い。使いやすいし、お勧め。
