Popolazione della select con tabelle del database per modulo generatore di codice e sql

Generatore di codice per Drupal 6.18. Questo codice funziona perfettamente. Il problema che ho incontrato consiste nella popolazione della select con il nome delle tabelle del database nonchè il valore passato. Ho risolto con $table_name = current($table_name); che restituisce l'elemento corrente di un array. Osservando moduli già fatti come db_maintenance ho potuto sviluppare questo modulo per la generazione di codice del tipo:

db_query("INSERT INTO {cache} (cid, data, expire, created, headers, serialized) VALUES ('%s', '%s', %d, %d, '%s', %d)", $cid, $data, $expire, $created, $headers, $serialized);

$result = db_query("SELECT cid, data, expire, created, headers, serialized FROM {cache} WHERE campo [= '%s'][LIKE '%%%s%%'] ORDER BY campo ASC", $valore);

db_query("UPDATE {cache} SET cid ='%s', data ='%s', expire =%d, created =%d, headers ='%s', serialized =%d WHERE cid = %d", $cid, $data, $expire, $created, $headers, $serialized);

db_query("DELETE FROM {cache} WHERE cid = %d", $cid);

PHP Code

Il codice del modulo è il seguente:

<?php
/**
* Display help and module information
*/
function informationphp_help($path, $arg) {
  $output = '';
  switch ($path) {
    case "admin/help#informationphp":
      $output = '<p>'.  t("Allows you to show phpinfo inside the site") .'</p>';
      break;
  }
  return $output;
}
function informationphp_init() {
  drupal_add_js(drupal_get_path('module', 'informationphp') .'/informationphp.js');
}
/**
* Valid permissions for this module
* @return array An array of valid permissions for the informationphp module
*/
function informationphp_perm() {
  //an administrator can define which roles have those permissions on the Administer » User management » Permissions page.
  return array('access informationphp');
}
function informationphp_menu() {
  $items = array();                                   //formtablespace
  $items['admin/settings/informationphp'] = array(
    'title' => t('PHP info'),
    'description' => t('Allows you to show phpinfo inside the site'),
    'page callback' => 'informationphp_showinfo_admin',
    'access arguments' => array('access informationphp'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 1,
   );
   $items['admin/settings/informationphp/drupalflushallcaches'] = array(
    'title' => t('PHP Cache'),
    'page callback' => 'informationphp_drupalflushallcaches',
    'access arguments' => array('access informationphp'),
    'weight' => 2,
    'type' => MENU_NORMAL_ITEM,
   );
   $items['admin/settings/informationphp/formtablespace'] = array(
    'title' => t('PHP Code'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('informationphp_formtablespace'),
    'access arguments' => array('access informationphp'),
    'weight' => 3,
    'type' => MENU_NORMAL_ITEM,
   );
  return $items;
}
function informationphp_showinfo_admin() {
  print phpinfo(); exit;
}
function informationphp_drupalflushallcaches() {
  drupal_flush_all_caches();
  drupal_set_message(t('Drupal flush all caches.'));
  drupal_goto('admin/settings');
}
function informationphp_formtablespace() {
global $isMysql, $isPostg, $db_name;
  $isMysql = FALSE; $isPostg = FALSE;
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
       $isMysql = TRUE;
    break;
    case 'pgsql':
       $isPostg = TRUE;
    break;
  }
   $form['#submit'][] = 'informationphp_formtablespace_submit';
   $form['feed'] = array(
      '#type' => 'fieldset',
      '#title' => t('Opzioni'),
      '#weight' => 1,
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
    );
    if ($isPostg) {
      $sql = db_query("SHOW datestyle");
      $datestylerow = pg_fetch_array($sql);
      $form['feed']['datestyle'] = array(
        '#value' => '<p align="center">DataStyle: <b>'.$datestylerow[0].'</b></p>',
      );
    }
    $table_names = array();
    if ($isMysql) {
      $result = db_query('SHOW TABLES');
    } elseif ($isPostg) {
      $result = db_query("SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' ORDER BY table_name");
    }
    while ($table_name = db_fetch_array($result)) {
      $table_name = current($table_name);                //Restituisce l'elemento corrente di un array
      $table_names[$table_name] = $table_name;
    }
    if ($result) {
            $form['feed']['tiposcript'] = array(
              '#type' => 'radios',
              '#title' => t('Tipo di script'),
              '#default_value' => variable_get('tiposcript', 0),
               '#options' => array(
                '0' => t('Genera SQL'),
                '1' => t('Genera codice per form'),
                '2' => t('Crea tabella dati'),
                '3' => t('Crea tabella ordinabile'),
              ),
            );
            $form['feed']['tablename'] = array(
              '#type' => 'select',
              '#title' => t('Seleziona'),
              '#options' => $table_names,
              '#description' => t('Seleziona la tabella per la generazione del codice'),
            );
            $form['feed']['submit'] = array(
              '#type' => 'submit',
              '#value' => t("Genera"),
            );
   } else {
      $form['feed']['information'] = array(
        '#value' => t('<p align="center">Non ci sono tabelle nel db <b>'.$db_name.'</b></p>'),
      );
   }
return $form;
}
function informationphp_formtablespace_submit($form, &$form_state) {
global $isMysql, $isPostg;
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
       $isMysql = TRUE;
    break;
    case 'pgsql':
       $isPostg = TRUE;
    break;
  }
   $tiposcript = $form_state['values']['tiposcript'];
   $table = $form_state['values']['tablename'];
   $table_no_prefix = ereg_replace("dr_","",$table);
   if ($tiposcript==0) {
           $res = db_query("SELECT * FROM {%s};", $table_no_prefix);
           if ($isPostg) $numfields = pg_num_fields($res);
           if ($isMysql) $numfields = mysql_num_fields($res);
            $dbquery_insertinto = "db_query("INSERT INTO {".$table_no_prefix."} (";
            $dbquery_select = "\$result = db_query("SELECT ";
            $dbquery_update = "db_query("UPDATE {".$table_no_prefix."} SET ";
            $dbquery_delete = "db_query("DELETE FROM {".$table_no_prefix."} WHERE cid = %d", \$cid);";
            $str_fieldnames = "";
            $str_valuepercent = "";
            $str_listvariables = "";
            $str_fieldnamesupdate = "";
            $str_array = "array(";
            for ($j = 0; $j < $numfields; $j++) {
                    if ($isPostg) $fieldname = pg_field_name($res, $j);
                    if ($isPostg) $fieldtype = pg_field_type($res, $j);
                    if ($isMysql) $fieldname = mysql_field_name($res, $j);
                    if ($isMysql) $fieldtype = mysql_field_type($res, $j);
                    $str_fieldnames .= "$fieldname, ";
                    switch ($fieldtype) {
                        case 'oid':
                        case 'serial':
                        case 'bool':
                        case 'numeric':
                        case 'interval':
                        case 'integer':
                        case 'int':
                        case 'int2':
                        case 'int4':
                        case 'int8':
                           $str_valuepercent .= "%d, ";
                           $str_valuepercent_update .= "%d, ";
                       break;
                        case 'float':
                        case 'float8':
                        case 'money':
                           $str_valuepercent .= "%f, ";
                           $str_valuepercent_update .= "%f, ";
                      break;
                        case 'bpchar':
                        case 'char':
                        case 'text':
                        case 'varchar':
                        case 'blob':
                           $str_valuepercent .= "'%s', ";
                           $str_valuepercent_update .= "'%s', ";
                      break;
                        case 'timestamp':
                        case 'datetime':
                        case 'date':
                        case 'time':
                           $str_valuepercent .= "'%s', ";
                           $str_valuepercent_update .= "'%s', ";
                      break;
                        default:
                           $str_valuepercent .= "'%s', ";
                           $str_valuepercent_update .= "'%s', ";
                        break;
                    }
                    $str_listvariables .= "$$fieldname, ";
                    $str_fieldnamesupdate .= "$fieldname =".$str_valuepercent_update.""; $str_valuepercent_update = '';
                    //$str_fieldnamesupdate .= "$fieldname ='%s', ";
                    $str_array .= "'$fieldname' => '$fieldname', ";
            }
            $str_fieldnames = substr($str_fieldnames,0,-2);
            $str_valuepercent = substr($str_valuepercent,0,-2);
            $str_listvariables = substr($str_listvariables,0,-2);
            $str_fieldnamesupdate = substr($str_fieldnamesupdate,0,-2);
            $str_array = substr($str_array,0,-2);
            $dbquery_insertinto .= $str_fieldnames.") VALUES (".$str_valuepercent.")", ".$str_listvariables.");";
            $dbquery_select .= $str_fieldnames." FROM {".$table_no_prefix."} WHERE campo [= '%s'][LIKE '%%%s%%'] ORDER BY campo ASC", \$valore);";
            $dbquery_update .= $str_fieldnamesupdate." WHERE cid = %d", ".$str_listvariables.");";
            $str_array .= ");";
            $str_fieldnames = "\n\n";
            $str_fieldnames .= "\$num_rows = FALSE;\n";
            $str_fieldnames .= "while(\$row = db_fetch_array(\$result)) {\n";
                          for ($j = 0; $j < $numfields; $j++) {
                              if ($isPostg) $fieldname = pg_field_name($res, $j);
                              if ($isMysql) $fieldname = mysql_field_name($res, $j);
                              $str_fieldnames .= "\$$fieldname = \$row['".$fieldname."'];\n";
                          }
                          $str_fieldnames .= "\$num_rows = TRUE;\n}\n\n";
                          for ($j = 0; $j < $numfields; $j++) {
                              if ($isPostg) $fieldname = pg_field_name($res, $j);
                              if ($isMysql) $fieldname = mysql_field_name($res, $j);
                              $str_fieldnames .= "<li><b>".t('".$fieldname."').":</b> \$$fieldname</li>\n";
                          }
           $outprint =  "<p align='center'><form name='formtableresult'><b>Generazione codice TBL per $table: </b><br>";
           $outprint .=  "<textarea name='content' cols='60' rows='25'>$dbquery_insertinto\n\n$dbquery_select\n\n$dbquery_update\n\n$dbquery_delete\n$str_fieldnames\n$str_array</textarea><br>";
           $outprint .=  "<input type='button' value='Indietro' onclick='history.go(1)'></form></p>";
     }
     //###############################################################
     if ($tiposcript==1) {
           $res = db_query("SELECT * FROM {%s};", $table_no_prefix);
           $numfields = pg_num_fields($res);
           $str_fieldnames = "";
            $str_fieldnames .= "\$form['#attributes']['enctype'] = 'multipart/form-data';\n";
            $str_fieldnames .= "\$form['#validate'][] = 'form_validate';\n";
            $str_fieldnames .= "\$form['#submit'][] = 'form_submit';\n";
           for ($j = 0; $j < $numfields; $j++) {
                    if ($isPostg) $fieldname = pg_field_name($res, $j);
                    if ($isPostg) $fieldtype = pg_field_type($res, $j);
                    if ($isPostg) $fieldlenght = pg_field_size($res, $j);
                    if ($isMysql) $fieldname = mysql_field_name($res, $j);
                    if ($isMysql) $fieldtype = mysql_field_type($res, $j);
                    if ($isMysql) $fieldlenght = mysql_field_size($res, $j);
$str_fieldnames .= "\$form['".$fieldname."'] = array(
  '#type' => 'textfield',
  '#title' => t('".$fieldname."'),
  '#maxlength' => 80,
  '#size' => 18,
  '#default_value' => \$$fieldname,
  '#required' => FALSE,
  '#description' => '',
);\n";
           }
           $str_fieldnames .= "\$form['submit'] = array('#type' => 'submit', '#value' => t("Next"), );\n";
           $str_fieldnames .= "\$form['#theme'] = 'form_draw';\n";
           $str_fieldnames .= "return \$form;\n";
           $str_fieldnames .="\n\n";
           for ($j = 0; $j < $numfields; $j++) {
              if ($isPostg) $fieldname = pg_field_name($res, $j);
              if ($isMysql) $fieldname = mysql_field_name($res, $j);
              $str_fieldnames .= "\$$fieldname = \$form_state['values']['".$fieldname."'];\n";
           }
$str_fieldnames .="\n\n";
$str_fieldnames .="\$rows[] = array(
  array('data' => drupal_render(\$form['campo']), 'colspan' => 3)
);
\$rows[] = array(
  drupal_render(\$form['campo']),
  drupal_render(\$form['campo']),
  drupal_render(\$form['campo']),
);
\$rows[] = array(
    array('data' => drupal_render(\$form['campo']), 'colspan' => 1),
    array('data' => drupal_render(\$form['campo']), 'colspan' => 2),
);";
           $outprint =  "<p align='center'><form name='formtableresult'><b>Generazione codice FORM per $table: </b><br>";
           $outprint .=  "<textarea name='content' cols='60' rows='25'>$str_fieldnames</textarea><br>";
           $outprint .=  "<input type='button' value='Indietro' onclick='history.go(1)'></form></p>";
     }
     //###############################################################
     if ($tiposcript==2) {
           $res = db_query("SELECT * FROM {%s};", $table_no_prefix);
           if ($isPostg) $numfields = pg_num_fields($res);
           if ($isMysql) $numfields = mysql_num_fields($res);
            $table_no_prefix = ereg_replace("dr_","",$table);
            $str_fieldnames = "";
            $str_fieldarray = "";
            $str_output = "function moduloname_show".$table_no_prefix."_admin() {\n";
            $str_output .= "  \$header = array(";
            for ($j = 0; $j < $numfields; $j++) {
                    if ($isPostg) $fieldname = pg_field_name($res, $j);
                    if ($isPostg) $fieldtype = pg_field_type($res, $j);
                    if ($isMysql) $fieldname = mysql_field_name($res, $j);
                    if ($isMysql) $fieldtype = mysql_field_type($res, $j);
                    $title = ucwords($fieldname);
                    $str_fieldnames .= "$fieldname, ";
                    $str_fieldarray .= "'$title', ";
            }
            $str_fieldarray = substr($str_fieldarray,0,-2) ;
            $str_fieldnames = substr($str_fieldnames,0,-2) ;
            $str_output .= $str_fieldarray.");\n";
            $str_output .= "  \$rows = array();\n";
            $str_output .= "  \$res = db_query('SELECT ".$str_fieldnames;
            $str_output .= " FROM {".$table_no_prefix."} ORDER BY nid');\n";
            $str_output .= "  \$num_rows = FALSE;\n";
            $str_output .= "  while (\$row = db_fetch_array(\$res)) {\n";
            $str_output .= "      \$rows[] = \$row;\n";
            $str_output .= "      \$num_rows = TRUE;\n";
            $str_output .= "  }\n\n";
            $str_output .= "  if (\$num_rows) {\n";
            $str_output .= "    \$output .= theme('table', \$header, \$rows);\n";
            $str_output .= "    print theme('page', \$output);\n";
            $str_output .= "    exit;\n";
            $str_output .= "  } else {\n";
            $str_output .= "    drupal_set_message(t("Nessun record per questa tabella."));\n";
            $str_output .= "  }\n";
            $str_output .= "}\n\n";
           $outprint =  "<p align='center'><form name='formtableresult'><b>Generazione codice TBL per $table: </b><br>";
           $outprint .=  "<textarea name='content' cols='60' rows='25'>$str_output</textarea><br>";
           $outprint .=  "<input type='button' value='Indietro' onclick='history.go(1)'></form></p>";
     }
     //###############################################################
     if ($tiposcript==3) {
           $res = db_query("SELECT * FROM {%s};", $table_no_prefix);
           if ($isPostg) $numfields = pg_num_fields($res);
           if ($isMysql) $numfields = mysql_num_fields($res);
            $table_no_prefix = ereg_replace("dr_","",$table);
            $fieldnamelist = "";
            $fieldrowlist = "";
            $str_output = "function moduloname_show_".$table_no_prefix."() {\n";
            $str_output .= "   global \$language;\n";
            $str_output .= "     \$header = array(\n";
                      for ($j = 0; $j < $numfields; $j++) {
                              if ($isMysql) $fieldname = mysql_field_name($res, $j);
                              if ($isMysql) $fieldtype = mysql_field_type($res, $j);
                              $fieldnamelist .= $fieldname.", ";
                              $fieldrowlist .= "\$row['".$fieldname."'], ";
                              $fieldnametitle = ucfirst($fieldname);
                              $str_output .= "      array('data' => t('".$fieldnametitle."'), 'field' => '".$fieldname."', 'sort' => 'asc'),\n";
                      }
                      $fieldnamelist = substr($fieldnamelist,0,-2);
                      $fieldrowlist = substr($fieldrowlist,0,-2);
            $str_output .= "     );\n";
            $str_output .= "     \$query = 'SELECT ".$fieldnamelist." FROM {".$table_no_prefix."}';\n";
            $str_output .= "     \$query .= tablesort_sql(\$header);\n";
            $str_output .= "     \$result = pager_query(\$query, 25);\n\n";
            $str_output .= "     while (\$row = db_fetch_array(\$result)) {\n";
            $str_output .= "       \$rows[] = \$row;\n";
            $str_output .= "       //\$rows[] = array(".$fieldrowlist.");\n";
            $str_output .= "     }\n";
            $str_output .= "     if (!\$rows) {\n";
            $str_output .= "       \$rows[] = array(array('data' => t('Non ci sono record in questa tabella'), 'colspan' => 3));\n";
            $str_output .= "     }\n";
            $str_output .= "     \$output = theme('table', \$header, \$rows);\n";
            $str_output .= "     \$output .= theme('pager', NULL, 25, 0);\n";
            $str_output .= "     print theme('page', \$output);\n";
            $str_output .= "     exit;\n";
            $str_output .= "}\n\n";
           $outprint =  "<p align='center'><form name='formtableresult'><b>Generazione codice TBL ordinabile per $table: </b><br>";
           $outprint .=  "<textarea name='content' cols='60' rows='25'>$str_output</textarea><br>";
           $outprint .=  "<input type='button' value='Indietro' onclick='history.go(1)'></form></p>";
     }
     print theme('page', $outprint);
}

Potete divertirvi a implementare il codice come preferite o utilizzarlo così come è.
Ciao da Danzisi

AllegatoDimensione
Package icon informationphp.zip4.52 KB
Image icon PHP Code.JPG18.53 KB

Argomenti: