SlideShare a Scribd company logo
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));

More Related Content

What's hot

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
camp_drupal_ua
 
Keeping It Simple
Keeping It SimpleKeeping It Simple
Keeping It Simple
Stephanie Leary
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 
Drupal Development (Part 2)
Drupal Development (Part 2)Drupal Development (Part 2)
Drupal Development (Part 2)
Jeff Eaton
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
Bernhard Schussek
 
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 ask
Andrea 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 site
references
 
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 Iusethis
Marcus Ramberg
 
Theme API
Theme APITheme API
Theme API
rolfvandekrol
 
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
Nuvole
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
Hugo Hamon
 
Propel sfugmd
Propel sfugmdPropel sfugmd
Propel sfugmd
iKlaus
 
$.Template
$.Template$.Template
$.Template
Dave Furfero
 
BEAR DI
BEAR DIBEAR DI
Refactoring using Codeception
Refactoring using CodeceptionRefactoring using Codeception
Refactoring using Codeception
Jeroen van Dijk
 
GHC Participant Training
GHC Participant TrainingGHC Participant Training
GHC Participant Training
AidIQ
 
Daily notes
Daily notesDaily notes
Daily notes
meghendra168
 

What's hot (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
 

Similar to Views notwithstanding

Drupal Lightning FAPI Jumpstart
Drupal Lightning FAPI JumpstartDrupal Lightning FAPI Jumpstart
Drupal Lightning FAPI Jumpstart
guestfd47e4c7
 
Render API - Pavel Makhrinsky
Render API - Pavel MakhrinskyRender API - Pavel Makhrinsky
Render API - Pavel Makhrinsky
DrupalCampDN
 
JQuery Basics
JQuery BasicsJQuery Basics
JQuery Basics
Alin Taranu
 
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
John Mertic
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
mussawir20
 
Php My Sql
Php My SqlPhp My Sql
Php My Sql
mussawir20
 
Introduction To Moco
Introduction To MocoIntroduction To Moco
Introduction To Moco
Naoya Ito
 
Jquery
JqueryJquery
Framework
FrameworkFramework
Framework
Nguyen Linh
 
WordPress as a Content Management System
WordPress as a Content Management SystemWordPress as a Content Management System
WordPress as a Content Management System
Valent 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
 
Ubi comp27nov04
Ubi comp27nov04Ubi comp27nov04
Ubi comp27nov04
mohamed ashraf
 
perl usage at database applications
perl usage at database applicationsperl usage at database applications
perl usage at database applications
Joe 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 php
Wade Womersley
 
HTML::FormHandler
HTML::FormHandlerHTML::FormHandler
HTML::FormHandler
bbeeley
 
Php Sq Lite
Php Sq LitePhp Sq Lite
Php Sq Lite
mussawir20
 
Testing persistence in PHP with DbUnit
Testing persistence in PHP with DbUnitTesting persistence in PHP with DbUnit
Testing persistence in PHP with DbUnit
Peter Wilcsinszky
 
jQuery Performance Rules
jQuery Performance RulesjQuery Performance Rules
jQuery Performance Rules
nagarajhubli
 
Introduction To Lamp
Introduction To LampIntroduction To Lamp
Introduction To Lamp
Amzad Hossain
 
Micro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicateMicro-ORM Introduction - Don't overcomplicate
Micro-ORM Introduction - Don't overcomplicate
Kiev ALT.NET
 

Similar to 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
 

Recently uploaded

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 

Recently uploaded (20)

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 

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));