Guest User

Untitled

a guest
Dec 16th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. /**
  2. * Render a filtered list of entries in the database.
  3. *
  4. * DBTNG also helps processing queries that return several rows, providing the
  5. * found objects in the same query execution call.
  6. *
  7. * This function queries the database using a JOIN between users table and the
  8. * example entries, to provide the username that created the entry, and creates
  9. * a table with the results, processing each row.
  10. *
  11. * SELECT
  12. * e.pid as pid, e.name as name, e.surname as surname, e.age as age
  13. * u.name as username
  14. * FROM
  15. * {dbtng_example} e
  16. * JOIN
  17. * users u ON e.uid = u.uid
  18. * WHERE
  19. * e.name = 'John' AND e.age > 18
  20. *
  21. * @see db_select()
  22. * @see http://drupal.org/node/310075
  23. */
  24. function dbtng_example_advanced_list() {
  25. $output = '';
  26.  
  27. $select = db_select('dbtng_example', 'e');
  28. // Join the users table, so we can get the entry creator's username.
  29. $select->join('users', 'u', 'e.uid = u.uid');
  30. // Select these specific fields for the output.
  31. $select->addField('e', 'pid');
  32. $select->addField('u', 'name', 'username');
  33. $select->addField('e', 'name');
  34. $select->addField('e', 'surname');
  35. $select->addField('e', 'age');
  36. // Filter only persons named "John".
  37. $select->condition('e.name', 'John');
  38. // Filter only persons older than 18 years.
  39. $select->condition('e.age', 18, '>');
  40. // Make sure we only get items 0-49, for scalability reasons.
  41. $select->range(0, 50);
  42.  
  43. // Now, loop all these entries and show them in a table. Note that there is no
  44. // db_fetch_* object or array function being called here. Also note that the
  45. // following line could have been written as
  46. // $entries = $select->execute()->fetchAll() which would return each selected
  47. // record as an object instead of an array.
  48. $entries = $select->execute()->fetchAll(PDO::FETCH_ASSOC);
  49. if (!empty($entries)) {
  50. $rows = array();
  51. foreach ($entries as $entry) {
  52. // Sanitize the data before handing it off to the theme layer.
  53. $rows[] = array_map('check_plain', $entry);
  54. }
  55. // Make a table for them.
  56. $header = array(t('Id'), t('Created by'), t('Name'), t('Surname'), t('Age'));
  57. $output .= theme('table', array('header' => $header, 'rows' => $rows));
  58. }
  59. else {
  60. drupal_set_message(t('No entries meet the filter criteria (Name = "John" and Age > 18).'));
  61. }
  62. return $output;
  63. }
Add Comment
Please, Sign In to add comment