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

Contenu connexe

Tendances

Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011camp_drupal_ua
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в MagentoMagecom Ukraine
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)Jeff Eaton
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)brockboland
 
Everything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askEverything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askAndrea Giuliano
 
Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5성일 한
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress sitereferences
 
Simple Ways To Be A Better Programmer (OSCON 2007)
Simple Ways To Be A Better Programmer (OSCON 2007)Simple Ways To Be A Better Programmer (OSCON 2007)
Simple Ways To Be A Better Programmer (OSCON 2007)Michael Schwern
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
First Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentNuvole
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmdiKlaus
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using CodeceptionJeroen van Dijk
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant TrainingAidIQ
 

Tendances (20)

Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
Nickolay Shmalenuk.Render api eng.DrupalCamp Kyiv 2011
 
Keeping It Simple
Keeping It SimpleKeeping It Simple
Keeping It Simple
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)Drupal is Stupid (But I Love It Anyway)
Drupal is Stupid (But I Love It Anyway)
 
Everything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to askEverything you always wanted to know about forms* *but were afraid to ask
Everything you always wanted to know about forms* *but were afraid to ask
 
Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5Laravel 로 배우는 서버사이드 #5
Laravel 로 배우는 서버사이드 #5
 
Gail villanueva add muscle to your wordpress site
Gail villanueva   add muscle to your wordpress siteGail villanueva   add muscle to your wordpress site
Gail villanueva add muscle to your wordpress site
 
Simple Ways To Be A Better Programmer (OSCON 2007)
Simple Ways To Be A Better Programmer (OSCON 2007)Simple Ways To Be A Better Programmer (OSCON 2007)
Simple Ways To Be A Better Programmer (OSCON 2007)
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Theme API
Theme APITheme API
Theme API
 
First Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven DevelopmentFirst Steps in Drupal Code Driven Development
First Steps in Drupal Code Driven Development
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
 
$.Template
$.Template$.Template
$.Template
 
BEAR DI
BEAR DIBEAR DI
BEAR DI
 
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
 
Daily notes
Daily notesDaily notes
Daily notes
 

Similaire à Views notwithstanding

Drupal Lightning FAPI Jumpstart
Drupal Lightning FAPI JumpstartDrupal Lightning FAPI Jumpstart
Drupal Lightning FAPI Jumpstartguestfd47e4c7
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel MakhrinskyDrupalCampDN
 
SugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
SugarCon 2010 - Best Practices for Creating Custom Apps in SugarSugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
SugarCon 2010 - Best Practices for Creating Custom Apps in SugarJohn Mertic
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Securitymussawir20
 
Introduction To Moco
Introduction To MocoIntroduction To Moco
Introduction To MocoNaoya Ito
 
WordPress as a Content Management System
WordPress as a Content Management SystemWordPress as a Content Management System
WordPress as a Content Management SystemValent Mustamin
 
Smarter Interfaces with jQuery (and Drupal)
Smarter Interfaces with jQuery (and Drupal)Smarter Interfaces with jQuery (and Drupal)
Smarter Interfaces with jQuery (and Drupal)aasarava
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applicationsJoe Jiang
 
Building a horizontally scalable API in php
Building a horizontally scalable API in phpBuilding a horizontally scalable API in php
Building a horizontally scalable API in phpWade Womersley
 
HTML::FormHandler
HTML::FormHandlerHTML::FormHandler
HTML::FormHandlerbbeeley
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitPeter Wilcsinszky
 
jQuery Performance Rules
jQuery Performance RulesjQuery Performance Rules
jQuery Performance Rulesnagarajhubli
 
Introduction To Lamp
Introduction To LampIntroduction To Lamp
Introduction To LampAmzad Hossain
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateKiev ALT.NET
 

Similaire à Views notwithstanding (20)

Drupal Lightning FAPI Jumpstart
Drupal Lightning FAPI JumpstartDrupal Lightning FAPI Jumpstart
Drupal Lightning FAPI Jumpstart
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel Makhrinsky
 
JQuery Basics
JQuery BasicsJQuery Basics
JQuery Basics
 
SugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
SugarCon 2010 - Best Practices for Creating Custom Apps in SugarSugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
SugarCon 2010 - Best Practices for Creating Custom Apps in Sugar
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
 
Php My Sql
Php My SqlPhp My Sql
Php My Sql
 
Introduction To Moco
Introduction To MocoIntroduction To Moco
Introduction To Moco
 
Jquery
JqueryJquery
Jquery
 
Framework
FrameworkFramework
Framework
 
WordPress as a Content Management System
WordPress as a Content Management SystemWordPress as a Content Management System
WordPress as a Content Management System
 
Smarter Interfaces with jQuery (and Drupal)
Smarter Interfaces with jQuery (and Drupal)Smarter Interfaces with jQuery (and Drupal)
Smarter Interfaces with jQuery (and Drupal)
 
Ubi comp27nov04
Ubi comp27nov04Ubi comp27nov04
Ubi comp27nov04
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
 
Building a horizontally scalable API in php
Building a horizontally scalable API in phpBuilding a horizontally scalable API in php
Building a horizontally scalable API in php
 
HTML::FormHandler
HTML::FormHandlerHTML::FormHandler
HTML::FormHandler
 
Php Sq Lite
Php Sq LitePhp Sq Lite
Php Sq Lite
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
 
jQuery Performance Rules
jQuery Performance RulesjQuery Performance Rules
jQuery Performance Rules
 
Introduction To Lamp
Introduction To LampIntroduction To Lamp
Introduction To Lamp
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Dernier (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Views notwithstanding

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