データベースエントリが存在する場合、どのように最速でチェックできますか? 私はこのコードを使用します:
$exists = db_query('SELECT tid FROM {taxonomy_index} WHERE tid = 1 AND nid = 1 LIMIT 1');
if($exists->rowCount() > 0){
drupal_set_message("exists");
}
データベースエントリが存在する場合、どのように最速でチェックできますか? 私はこのコードを使用します:
$exists = db_query('SELECT tid FROM {taxonomy_index} WHERE tid = 1 AND nid = 1 LIMIT 1');
if($exists->rowCount() > 0){
drupal_set_message("exists");
}
私はするだろう:
$result = db_select('taxonomy_index', 'ti')
->fields('ti', array('tid'))
->condition('tid', 1)
->condition('nid', 1)
->range(0, 1)
->execute()
->rowCount();
if ($result) {
drupal_set_message(t('Exists'));
}
質問とは関係ありませんが、SQL インジェクションを防ぐために常にプレースホルダーを使用する必要があります。ただし、上記のようにクエリ ビルダーを使用すると、それが処理されます。また、画面にテキストを書き込むときは、常に t() 関数を使用する必要があります。
db_select()
よりもずっと遅いですdb_query()
。よりも適切なシナリオについては、このスレッドを参照してください。db_select()
db_query()
db_query()->fetchField()
最も簡単なアプローチです。次のスニペットを参照してください。
// Returns string(5) "admin"
var_dump(db_query('select name from {users} where uid = 1')->fetchField());
// Returns bool(false)
var_dump(db_query('select name from {users} where uid = -1')->fetchField());