Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Views notwithstanding

721 views

Published on

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Views notwithstanding

  1. 1. Views Notwithstanding<br />A Programmer’s guide to working with MySQL Tables in Drupal using PHP and SQL<br />-- Srikanth Bangalore.<br />Bangalore.srikanth@gmail.com<br />Drupal ID: bangalos<br />
  2. 2. Drupal APIs (in PHP) for:<br />Creating a table<br />During installation of your custom module<br />Post installation of your custom module<br />Inserting into table<br />Querying the table and iterating over rows<br />Creating a “Block”<br />Creating an Admin “menu” (form)<br />Creating a form<br />
  3. 3. Creating a Table (during installation of custom module)<br />hotornot.info<br />name = Hot Or Not<br />description = Builds A Hot Or Not Block, And Lets Users Rate Images In A Folder.<br />package = Hot Or Not<br />core = 6.x<br />hotornot.module (to be populated later)<br />hotornot.install (see next slide)<br />
  4. 4. Hotornot.install<br /><?php<br />function hotornot_install() {<br /> switch ($GLOBALS['db_type']) {<br /> case 'mysql':<br /> case 'mysqli':<br /> // the {tablename} syntax is so multisite installs can add a prefix to the table name as set in the settings.php file<br />db_query("CREATE TABLE {hotornot_filelist} (<br />file_idint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,<br />file_pathvarchar(256) NOT NULL DEFAULT './.',<br />present_or_notsmallint unsigned NOT NULL DEFAULT 1,<br /> title varchar(256),<br /> description text<br /> ) /*!40100 DEFAULT CHARACTER SET utf8 */;");<br />break;<br /> }<br />}<br />
  5. 5. Adding Another Table later<br />function hotornot_update_1() {<br /> switch ($GLOBALS['db_type']) {<br /> case 'mysql':<br /> case 'mysqli':<br />db_query ("CREATE TABLE {hotornot_userchoice} (<br />file_idint unsigned NOT NULL DEFAULT 0,<br />uidint unsigned NOT NULL DEFAULT 0,<br />hot_or_notsmallint unsigned NOT NULL DEFAULT 0,<br /> PRIMARY KEY (file_id, uid)<br /> ) /*!40100 DEFAULT CHARACTER SET utf8 */;");<br /> break;<br /> }<br />}<br />
  6. 6. Things To Remember …<br />db_query function accepts an SQL statement as input, and executes it.<br />
  7. 7. function hotornot_repopulate() {<br /> $path_to_files = realpath('.') . variable_get('hotornot_folder', '/sites/default/files/hotornot');<br /> $output = "";<br /> $isql = "UPDATE {hotornot_filelist} SET present_or_not = 0 WHERE file_id>0";<br /> $iresult = db_query($isql);<br /> if ($handle = opendir($path_to_files)) {<br /> while (false !== ($file = readdir($handle))) {<br /> if ($file != "." && $file != "..") {<br /> $output .= "$filen";<br /> $query = "SELECT COUNT(*) FROM {hotornot_filelist} WHERE file_path = '$file'";<br /> $num = db_result(db_query($query));<br /> if($num) {<br /> $isql = "UPDATE {hotornot_filelist} SET present_or_not=1 WHERE file_path = '$file'";<br /> $iresult = db_query($isql, $file);<br /> } else {<br /> $isql = "INSERT INTO {hotornot_filelist} (file_path, present_or_not) VALUES ('%s', 1)";<br /> $iresult = db_query($isql, $file);<br />}<br /> }<br /> }<br />closedir($handle);<br /> }<br />drupal_set_message($output);<br />}<br />
  8. 8. Things To Remember …<br />db_query function accepts an SQL statement as input, and executes it.<br />db_result(db_query($sql)) extracts the SINGLE value of the db_query result.<br />variable_get function is used to get the value of a programmer-defined variable. (see later).<br />
  9. 9. hotornot.module – part 1: adding the admin menu (a)<br /><?php<br />function hotornot_menu() {<br /> $items = array();<br /> $items['admin/settings/hotornot'] = array(<br /> 'title' => t('Hot Or Not'),<br /> 'description' => t('Select The Hot Or Not Image Folder'),<br /> 'page callback' => 'drupal_get_form',<br /> 'page arguments' => array('hotornot_admin_settings'),<br /> 'access arguments' => array('administer site configuration'),<br /> );<br /> return $items;<br />}<br />….(see next slide)<br />
  10. 10. hotornot.module – part 1: adding the admin menu (b)<br />function hotornot_admin_settings() {<br /> $form = array();<br /> $form['hotornot_folder'] = array(<br /> '#type' => 'textfield',<br /> '#title' => t('The folder where all the images for the Hot Or Not are Stored'),<br /> '#default_value' => variable_get('hotornot_folder', 'sites/default/files/hotornot'),<br /> );<br /> $form['hotornot_repopulate'] = array(<br /> '#type' => 'submit',<br /> '#value' => 'Repopulate',<br /> );<br /> $form['#submit'][] = 'hotornot_admin_settings_submit_handler';<br /> return system_settings_form($form);<br />}<br />function hotornot_admin_settings_submit_handler(&$form, &$form_state) {<br /> if ($form_state['clicked_button']['#id'] == 'edit-hotornot-repopulate') {<br />hotornot_repopulate();<br /> }<br />}<br />
  11. 11. Things to remember …<br />Use drupal forms api to build the forms, even the Admin forms.<br />3 steps to having your own module’s admin settings form:<br />Define path + form_builder_function in hook_menu();<br />Build your form using the forms API. Remember to wrap your form with “system_settings_form”<br />Do your “stuff” in the submit handler.<br />
  12. 12. hotornot.module – part 2adding the block (a)<br />function hotornot_block($op = 'list', $delta = 0, $edit = array()) {<br /> switch ($op) {<br /> case 'list':<br /> $blocks[0]['info'] = t('Rate this!');<br /> return $blocks;<br /> case 'view':<br /> if ($delta == 0 ) { <br /> $block[0]['subject'] = t("Do you like ...");<br /> $block[0]['content'] = drupal_get_form('hotornot_hotornotform');<br /> }<br /> return $block[$delta];<br /> }<br />}<br />
  13. 13. hotornot.module – part 2adding the block (b)<br />function hotornot_hotornotform(&$form_state) {<br />$form = array(); global $user;<br />$sql = "SELECT filelist.file_path AS filename, filelist.file_id AS file_id, filelist.title AS file_title FROM {hotornot_filelist} as filelist WHERE filelist.present_or_not > 0 AND (filelist.file_id not in (SELECT file_id FROM {hotornot_userchoice} WHERE uid=%d)) ORDER BY RAND() LIMIT 1";<br />$result = db_query($sql, $user->uid);<br /> $atleastoneexists = FALSE;<br /> while ($row = db_fetch_array($result)) {<br /> $atleastoneexists = TRUE;<br /> $form['my_fileid'] = array(<br /> '#type' => 'hidden',<br /> '#value' => $row['file_id']<br />);<br />
  14. 14. hotornot.module – part 2adding the block (c)<br /> $form['picture'] = array(<br /> '#type' => 'markup',<br /> '#value' => '<img width="100%" src="' . base_path() . variable_get('hotornot_folder', '/sites/default/files/hotornot') . '/' . $row['filename'] . '"/><br/><strong>...'. $row['file_title'] . ' ?</strong><br/>',<br /> );<br /> break;<br /> }<br />if ($atleastoneexists) {<br /> $form['ishot'] = array(<br /> '#type' => 'submit',<br /> '#value' => t('Yes')<br /> );<br /> $form['isnot'] = array(<br /> '#type' => 'submit',<br /> '#value' => t('No')<br /> );<br /> } else {<br /> $form['picture'] = array(<br /> '#type' => 'markup',<br /> '#value' => '<p>Currently, you have seen all the items. Thank you.</p>', <br /> );<br /> }<br /> return $form;<br />}<br />
  15. 15. hotornot.module – part 2adding the block (d)<br />function hotornot_hotornotform_submit(&$form, &$form_state) {<br /> global $user;<br /> if ($form_state['clicked_button']['#id'] == 'edit-ishot') {<br /> $ishot = 1;<br /> } else {<br /> $ishot = 0;<br /> }<br /> $fileid = $form_state['clicked_button']['#post']['my_fileid'];<br /> $isql = "REPLACE INTO {hotornot_userchoice} (file_id, uid, hot_or_not) VALUES (%d, %d, %d)";<br /> $iresult = db_query($isql, $fileid, $user->uid, $ishot);<br />}<br />
  16. 16. Things To Remember …<br />db_query function accepts an SQL statement as input, and executes it.<br />db_result(db_query($sql)) extracts the SINGLE value of the db_query result.<br />To get the rows of the query result in an iterator.<br />$result = db_query($sql); <br />while ($row = db_fetch_array($result)) {<br /> $val = $row[‘column_name’]<br />}<br />
  17. 17. hotornot.module – part 3adding a page to enter title/desc (a)<br />function hotornot_menu() {<br /> $items = array();<br /> // ...code...<br />$items['hotornot/administer'] = array(<br /> 'title' => t('Hot Or Not Administration'),<br /> 'description' => t('Add Or Edit Title And Descriptions to Hot Or Not Items'),<br /> 'page callback' => 'local_hotornot_administer_description_form',<br /> 'access arguments' => array('access content'),<br /> 'type' => MENU_CALLBACK,<br /> );<br /> // ...code...<br /> return $items;<br />}<br />function local_hotornot_administer_description_form() {<br /> return drupal_get_form('hotornot_administer_description_form');<br />}<br />
  18. 18. hotornot.module – part 3adding a page to enter title/desc (b)<br />function hotornot_administer_description_form(&$form_state) {<br /> $form = array();<br /> global $user;<br /> $form['blurb'] = array (<br /> '#type' => 'markup',<br /> '#value' => '<p>You will be shown one picture at a time that does not have any title or description. You just have to enter a title and description and hit submit.</p>' ,<br /> );<br /> $sql = "SELECT filelist.file_path AS filename, filelist.file_id AS file_id, filelist.title AS title FROM {hotornot_filelist} as filelist WHERE filelist.present_or_not > 0 AND filelist.title is NULL LIMIT 1";<br /> $result = db_query($sql);<br /> $atleastoneexists = FALSE;<br /> while ($row = db_fetch_array($result)) {<br />
  19. 19. hotornot.module – part 3adding a page to enter title/desc (c)<br /> $atleastoneexists = TRUE;<br /> $form['fileid'] = array(<br /> '#type' => 'hidden',<br /> '#value' => $row['file_id']<br /> );<br /> $form['picture'] = array(<br /> '#type' => 'markup',<br /> '#value' => '<imgsrc="' . base_path() . variable_get('hotornot_folder', '/sites/default/files/hotornot') . '/' . $row['filename'] . '"/>',<br /> );<br /> $form['title'] = array(<br /> '#type' => 'textfield',<br /> '#title' => 'Title',<br /> '#default_value' => $row['title'],<br /> );<br /> }<br /> if ($atleastoneexists) {<br /> $form['submit'] = array(<br /> '#type' => 'submit',<br /> '#value' => 'Submit',<br /> );<br />
  20. 20. hotornot.module – part 3adding a page to enter title/desc (d)<br /> } else {<br /> $form['picture'] = array(<br /> '#type' => 'markup',<br /> '#value' => '<p>Currently, you have seen all the items. Thank you.</p>',<br /> );<br /> }<br /> return $form;<br />}<br />function hotornot_administer_description_form_submit(&$form, &$form_state) {<br /> $fileid = $form_state['values']['fileid'];<br /> $title = $form_state['values']['title'];<br /> $isql = "UPDATE {hotornot_filelist} SET title='%s' WHERE file_id=%d";<br /> $iresult = db_query($isql, $title, $fileid);<br />}<br />
  21. 21. Summary<br />We learnt how to create a new table at the time of installing our module<br />How to use db_query, db_result, db_fetch_array<br />How to create user blocks and user pages<br />How to create Admin menus and define new variables<br />How to use Forms API<br />
  22. 22. Drupal 7 changes<br />Switch(db_type) does not work!<br />Db_result() is replaced with ->fetchField();<br />Db_query (“adb=%d,%s”, $a, $b) is replaced with<br />Db_query(“abd=:a,:b”, array(‘:a’=>$a, ‘:b’=>$b));<br />

×