scrivere sul database

Posts: 69
Iscritto il: 18 Giu 05
Redattore di Drupal Italia. Contribuisco a manuali

in un post precedente http://www.drupalitalia.org/?q=node/749, giannigiusti inseriva questo pezzo di codice, che restituisce una tabella ordinata:

// Costruisci i titoli da mostrare nella tabella
$header = array(
array('data' => t('Nome'), 'field' => 'name', 'sort' => 'asc'),
array('data' => t('Indirizzo'), 'field' => 'address'),
);
// Visualizza la lista nella tabella
$result = db_query("SELECT name,address FROM {gest_user}".tablesort_sql($header));
while ($dati = db_fetch_object($result)) {
$rows[] = array($dati->name, $dati->address,);
}
// Temizzazione della tabella e titoli
$output = theme('table', $header, $rows);
print $output;

La domanda è: come si fa a scrivere sulla tabella guest_user utilizzando un form direttamente dal sito.

Grazie anticipatamente.


Posts: 475
Iscritto il: 09 Giu 05
Sviluppatore DrupalDrupal Monkey. Mangio moduli e API a colazioneModeratore di Drupal ItaliaRedattore di Drupal Italia. Contribuisco a manuali

di seguito ti posto un esempio di gestione clienti/fornitori (inserimento/ricerca/cancellazione/modifica) in una tabella gest_soggetto.

Struttura tabella:
--
-- Struttura della tabella `gest_soggetto`
--

CREATE TABLE `gest_soggetto` (
`id` int(6) NOT NULL default '0',
`nome` varchar(50) binary NOT NULL default '',
`indirizzo` varchar(100) NOT NULL default '',
`citta` varchar(25) NOT NULL default '',
`provincia` varchar(5) default NULL,
`cap` varchar(10) default NULL,
`indirizzo2` varchar(100) default NULL,
`citta2` varchar(25) default NULL,
`cap2` varchar(10) default NULL,
`provincia2` varchar(5) default NULL,
`codicefiscale` varchar(16) binary default NULL,
`email` varchar(60) default NULL,
`telefono1` varchar(25) default NULL,
`telefono2` varchar(25) default NULL,
`fax` varchar(25) default NULL,
`note` text,
`comunenascita` varchar(40) default NULL,
`provincianascita` varchar(5) default NULL,
`datanascita` date default NULL,
PRIMARY KEY (`id`)
) TYPE=MyISAM;

modulo soggetto.module:

<?php
/* ---------------------------------------------------------------------

*         MODULO PER LA GESTIONE DEI SOGGETTI (CLIENTI/FORNITORI)

*                        v 0.1 14/11/2005

*                      Licenza Modulo GPL

* ---------------------------------------------------------------------- */





/*

----------------- FUNZIONI DI BASE PER IL MODULO -----------------------

*/



function soggetto_help($section='') {

$output = '';

switch (
$section) {

    case
"admin/modules#description":

   
$output = t("*** Amministrazione clienti/fornitori ***");

    break;
    case
"sogg/test":
   
$output = t("In questa pagina e' possibile aggiungere un Soggetto");
    break;   

    }

return
$output;

}
// function onthisdate_help



// Determiniamo gli accessi al modulo (dando poi i giusti permessi nell'amministrazione)

function soggetto_perm() {

return array(
'amministrazione soggetto','gestione soggetto');

}



function
soggetto_menu() {



   
$items = array();

   

   
// Principale (operazioni principali)

   
$items[] = array(

           
'path' => 'soggetto',

           
'title' => t('Soggetti (Clienti/Fornitori)'),

           
'callback' => 'soggetto_form',

           
'access' => user_access('gestione soggetto'),

           
'type' => MENU_NORMAL_ITEM );

           

   
// Inserimento

   
$items[] = array(

           
'path' => 'soggetto/inserisci',

           
'title' => t('Inserimento'),

           
'callback' => 'soggetto_form',

           
'access' => user_access('gestione soggetto'),

           
'type' => MENU_NORMAL_ITEM );

           

   
// Ricerca (operazioni di ricerca)

   
$items[] = array(

           
'path' => 'soggetto/ricerca',

           
'title' => t('Ricerca'),

           
'callback' => 'soggetto_form_ricerca',

           
'access' => user_access('gestione soggetto'),

           
'type' => MENU_NORMAL_ITEM );

                               
   
// Inserisci popup (non visibile nei menu)

   
$items[] = array(

           
'path' => 'soggetto/inserisci_popup',

           
'title' => t('Inserimento Soggetto'),

           
'callback' => 'soggetto_form',

           
'access' => user_access('gestione soggetto'),

           
'type' => MENU_CALLBACK );   

           

   
// Ricerca Soggetto con protocollo xmlrcp (non visibile nei menu)

   
$items[] = array(

           
'path' => 'soggetto/soggetto_ricerca_xmlrpc',

           
'title' => t('soggetto ricerca xmlrcp'),

           
'callback' => 'soggetto_form',

           
'access' => user_access('gestione soggetto'),

           
'type' => MENU_CALLBACK );                       


   
// Ricerca Soggetto con protocollo xmlrcp (non visibile nei menu)

   
$items[] = array(

           
'path' => 'soggetto/lista',

           
'title' => t('Lista Soggeti Trovati'),

           
'callback' => 'soggetto_lista',

           
'access' => user_access('gestione soggetto'),

           
'type' => MENU_CALLBACK );   
           
   
$items[] = array(

           
'path' => 'soggetto/autocomplete/nome',

           
'title' => t('Lista soggetto'),

           
'callback' => 'soggetto_autocomplete_nome',

           
'access' => user_access('gestione soggetto'),

           
'type' => MENU_CALLBACK );   
           
   
$items[] = array(

           
'path' => 'soggetto/autocomplete/codice',

           
'title' => t('Lista soggetto'),

           
'callback' => 'soggetto_autocomplete_codice',

           
'access' => user_access('gestione soggetto'),

           
'type' => MENU_CALLBACK );                   

   
// Menu Tab su dettaglio Soggetto (se non è selezionato un soggetto non mostrare i sottomenu)
   
if (arg(1)>0) {
       
       
// Cancella (non visibile nei menu)

       
$items[] = array(

               
'path' => 'soggetto/'.arg(1).'/modifica/cancella',

               
'title' => t('Cancella'),

               
'callback' => 'soggetto_cancella',

               
'access' => user_access('gestione soggetto'),

               
'type' => MENU_CALLBACK );       
           
           
// Menu Locale (tabulatori), richiamato quando sei su soggetto/modifica

           
$items[] = array(
               
'path' => 'soggetto/'.arg(1).'/modifica/anagrafica',
               
'title' => t('Soggetto'),
               
'access' => user_access('gestione soggetto'),
               
'callback' => 'soggetto_form',
               
'weight' => 3,       
               
'type' => MENU_LOCAL_TASK// Tabulatore attivo di default
               
);
               
                       
// SOTTOMENU DI ANAGRAFICA
                       
$items[] = array(
                           
'path' => 'soggetto/'.arg(1).'/modifica/anagrafica/dati',
                           
'title' => t('Dati Anagrafici'),
                           
'access' => user_access('gestione soggetto'),
                           
'callback' => 'soggetto_form',   
                           
'weight' => 3,           
                           
'type' => MENU_LOCAL_TASK,
                            );           
                           
                       
$items[] = array(
                           
'path' => 'soggetto/'.arg(1).'/modifica/anagrafica/contatto',
                           
'title' => t('Contatti'),
                           
'access' => user_access('gestione soggetto'),
                           
'callback' => 'soggetto_form_contatto',   
                           
'weight' => 5,           
                           
'type' => MENU_LOCAL_TASK// Tabulatore attivo di default
                           
);       

           
/*
            $items[] = array(
                'path' => 'soggetto/'.arg(1).'/modifica/documenti',
                'title' => t('Documenti'),
                'access' => user_access('gestione soggetto'),
                'callback' => 'soggetto_form',
                'weight' => 4,           
                'type' => MENU_LOCAL_TASK
                );
       
            // Visualizza Scheda Immagini

            $items[] = array(

                'path' => 'soggetto/'.arg(1).'/modifica/scadenze',

                'title' => t('Scadenze'),

                'callback' => 'soggetto_form',

                'access' => user_access('gestione soggetto'),
                'weight' => 5,           
                'type' => MENU_LOCAL_TASK
                );
               
            // Visualizza Scheda Immagini

            $items[] = array(

                'path' => 'soggetto/'.arg(1).'/modifica/schede',

                'title' => t('Schede Lav.'),

                'callback' => 'soggetto_form',

                'access' => user_access('gestione soggetto'),
                'weight' => 6,           
                'type' => MENU_LOCAL_TASK
                );
               
            // Visualizza Scheda schede di lavorazione

            $items[] = array(

                'path' => 'soggetto/'.arg(1).'/modifica/auto',

                'title' => t('Auto'),

                'callback' => 'soggetto_form',
                'access' => user_access('gestione soggetto'),       
                'weight' => 7,           

                'type' => MENU_LOCAL_TASK );       
            */
           
   
}


    return
$items;

}



/**
* Recupera dati di autocompletamento
*/
function soggetto_autocomplete_nome($string) {
 
$matches = array();
 
$result = db_query_range("SELECT nome, indirizzo, citta FROM {gest_soggetto} WHERE LOWER(nome) LIKE LOWER('%s%%')", $string, 0, 10);
  while (
$user = db_fetch_object($result)) {
   
$matches[$user->nome] = check_plain($user->nome.'-'.$user->indirizzo.'-'.$user->citta);
  }
  print
drupal_implode_autocomplete($matches);
  exit();
}

function
soggetto_autocomplete_codice($string) {
 
$matches = array();
 
$result = db_query_range("SELECT codicefiscale, nome, indirizzo, citta FROM {gest_soggetto} WHERE LOWER(codicefiscale) LIKE LOWER('%s%%')", $string, 0, 10);
  while (
$user = db_fetch_object($result)) {
   
$matches[$user->codicefiscale] = check_plain($user->codicefiscale.'-'.$user->nome.'-'.$user->indirizzo.'-'.$user->citta);
  }
  print
drupal_implode_autocomplete($matches);
  exit();
}


// ***********************************************
// ***** FORM E LISTA CONTATTI ******************

function soggetto_form_contatto()

{

   
// Verifica l'argomento 6 per verificare se siamo in modifica o cancella
   
if (arg(6)=='cancella') {
       
db_query('
            DELETE FROM
            {gest_contatto}

            WHERE
            id_soggetto = %d
            AND
            id = %d
            '
,
           
arg(1),
           
arg(5)
            );
    }
   
    if (
arg(6)=='modifica') {
       
$result = db_query('
            SELECT
            id,
            nome,
            telefono1,
            telefono2,
            email
            FROM
            {gest_contatto}

            WHERE
            id_soggetto = %d
            AND
            id = %d
            '
,
           
arg(1),
           
arg(5)
            );
       
$value = db_fetch_array($result);
    }   

   
// Form Inserimento / Modifica
   
$form['#method'] = 'post';
   
$form['#action'] = url('/soggetto/'.arg(1).'/modifica/anagrafica/contatto');

   
// Campo Nome
   
$form['id'] = array(
     
'#type' => 'hidden',
     
'#title' => t('Nome'),
     
'#default_value' => $value['id'],     
    );   

   
// Campo Nome
   
$form['nome'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Nome'),
     
'#size' => 30,
     
'#maxlength' => 50,
     
'#required' => TRUE,     
     
'#default_value' => $value['nome'],     
     
'#prefix' => '<table><tr><td>',
       
'#suffix' => '</td>',
    );   

   
$form['telefono1'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Telefono 1'),
     
'#size' => 16,
     
'#maxlength' => 25,
     
'#default_value' => $value['telefono1'],   
     
'#prefix' => '<td>',
       
'#suffix' => '</td>',
    );


   
$form['telefono2'] = array(

     
'#type' => 'textfield',

     
'#title' => t('Telefono 2'),

     
'#size' => 16,

     
'#maxlength' => 25,

     
'#default_value' => $value['telefono2'],

     
'#prefix' => '<td>',

       
'#suffix' => '</td>',

    );   



   
$form['email'] = array(

     
'#type' => 'textfield',

     
'#title' => t('Email'),

     
'#size' => 30,

     
'#maxlength' => 50,

     
'#default_value' => $value['email'],

     
'#prefix' => '<td>',

       
'#suffix' => '</td></tr></table>',

    );   
   
   
// Pulsante Ricerca
     
$form['search'] = array('#type' => 'submit', '#value' => t('Conferma'));

     
// Provvede a controllare il form completando eventuali valori omessi, costruisce e stampa il form
     
$output = drupal_get_form('soggetto_form_contatto', $form);


   
// Costruisci i titoli da mostrare

   
$header = array(

        array(
'data' => t('Nome'), 'field' => 'nome', 'sort' => 'desc'),

        array(
'data' => t('Telefono 1'), 'field' => 'telefono1'),

        array(
'data' => t('Telefono 2'), 'field' => 'telefono2'),
        array(
'data' => t('email'), 'field' => 'email'),

       
t('Mostra'),

       
t('Elimina'),      

    );   

   

   
// Costruisci la query

   
$sql = 'SELECT

            id,

            nome,

            telefono1,

            telefono2,
            email

            FROM
            {gest_contatto}

            WHERE
            id_soggetto = '
           
.arg(1)
            .
tablesort_sql($header)
            ;    



   
// Applica la query (paginata)

   
$result = pager_query($sql, 50);

       

    while (
$contatto = db_fetch_object($result)) {

     
$rows[] = array(

                   
$contatto->nome,

                   
$contatto->telefono1,

                   
$contatto->telefono2,
                   
$contatto->email

                   
l(t('Dettaglio'), '/soggetto/'.arg(1).'/modifica/anagrafica/contatto/'.$contatto->id.'/modifica', NULL ),

                   
l(t('Cancella'), '/soggetto/'.arg(1).'/modifica/anagrafica/contatto/'.$contatto->id.'/cancella', NULL ),

                    );

    }



   
// Temizzazione della tabella e titoli

   
$output .= theme('table', $header, $rows);



   
// Temizzazione della pagina

   
$output .= theme('pager', NULL, 10, 0, tablesort_pager());   



   
// print theme('page', $output);

   
return $output;
   
}

// INSERIMENTO CONTATTO

function soggetto_form_contatto_submit($form_id, $form_values) {

   


   
// Verifica l'operazione è una modifica
   
if ($form_values['id']>0) {
       
       
// Modifica Contatto
       
db_query("

            UPDATE {gest_contatto} SET  
            nome = '%s',
            telefono1 = '%s',
            telefono2 = '%s',
            email = '%s'
            WHERE
            id = %d

            "
,
           
drupal_strtoupper($form_values['nome']),
           
drupal_strtoupper($form_values['telefono1']),
           
drupal_strtoupper($form_values['telefono2']),
           
$form_values['email'],
           
$form_values['id']

            );
           
       
drupal_set_message(t('Contatto Modificato'),'error');   
    }
    else {

       
// Recupera l'ultimo id inserito

       
$id_contatto = db_next_id('gest_contatto_id');
   
       
// Inserisci Contatto
       
db_query("

            INSERT INTO  

            {gest_contatto}
            (
            id,
            id_soggetto,
            nome,
            telefono1,
            telefono2,
            email
            )
            VALUES
            (
            %d,
            %d,
            '%s',
            '%s',
            '%s',
            '%s'
            )

            "
,
           
$id_contatto,

           
arg(1),
           
drupal_strtoupper($form_values['nome']),
           
drupal_strtoupper($form_values['telefono1']),
           
drupal_strtoupper($form_values['telefono2']),
           
$form_values['email']

            );
       
drupal_set_message(t('Nuovo Contatto Inserito'),'error');
    }
   
drupal_goto('/soggetto/'.arg(1).'/modifica/anagrafica/contatto');   

}

/*
function soggetto_form_alter($form_id, &$form)
{
    if ($_POST['edit']['nome'] =='pippo')
        $form['nome']['#value'] = 'dgdg dg dg dfg dg d';   
}
*/


// FORM DA MOSTRARE PER INSERIMENTO/MODIFICA

function soggetto_form()

{
   
// Se l'argomento è maggiore di 0 significa che è selezionato un soggetto
    // Fai la query e mostra i dati
   
if (arg(1)>0) {
       
// Ricerca se esiste già un codice iva o codice fiscale esistente
       
$result = db_query('SELECT
            id,

            nome,

            indirizzo,

            citta,

            provincia,

            cap,

            indirizzo2,

            citta2,

            provincia2,

            cap2,               

            codicefiscale,

            email,

            telefono1,

            telefono2,

            fax,

            note,
            comunenascita,
            provincianascita,
            datanascita
            FROM
            {gest_soggetto}
            WHERE
            id = \'%s\'
            '
,
           
arg(1)
            );   
       
$value = db_fetch_array($result);   
       
       
// Gira la data in modo corretto

       
if ($value['datanascita']) {

           
$ArrayDataEsploso = explode ('-', $value['datanascita']);

           
$value['datanascita'] = array('day'=> $ArrayDataEsploso[2], 'month'=> $ArrayDataEsploso[1], 'year'=> $ArrayDataEsploso[0]);

        }       
    }
   

   
// Proprietà del form

   
$form['#method'] = 'post';

   
$form['#action'] = url($value['action']);

     
// );


    // Campo ID (Nascosto)   

   
$form['id'] = array(

     
'#type' => 'hidden',

     
'#size' => 10,

     
'#maxlength' => 10,

     
'#required' => FALSE,

     
'#value' => $value['id'],
     
'#prefix' => ''

    );



   
// Campo Nome/Ragione Sociale   

   
$form['nome'] = array(

     
'#type' => 'textfield',

     
'#title' => t('Nome'),

     
'#size' => 50,

     
'#maxlength' => 50,

     
'#required' => TRUE,

     
'#default_value' => $value['nome'],

     
'#prefix' => '<table><tr><td><table><tr><td>',

       
'#suffix' => '</td>',

    );   



   
// Campo Partita Iva

   
$form['codicefiscale'] = array(

     
'#type' => 'textfield',

     
'#title' => t('P.Iva/Cod.Fiscale'),

     
'#size' => 20,

     
'#maxlength' => 20,

     
'#required' => TRUE,

     
'#default_value' => $value['codicefiscale'],

     
'#prefix' => '<td>',

       
'#suffix' => '</td></tr></table></td></tr>',

    );


// Indirizzo (linea NON collasabile)
     
$form['dettaglionascita'] = array(
       
'#type' => 'fieldset',
       
'#title' => t('Dati Di Nascita'),
       
'#collapsible' => TRUE,

       
'#collapsed' => TRUE,          
         
'#prefix' => '<tr><td>',
           
'#suffix' => '',       
      );

   
// Campo indirizzo Nascita   
   
$form['dettaglionascita']['comunenascita'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Comune di Nascita'),
     
'#size' => 40,
     
'#maxlength' => 50,
     
'#default_value' => $value['comunenascita'],
     
'#prefix' => '<table><tr><td>',
       
'#suffix' => '</td>',
    );   

   
// Campo Provincia Nascita
   
$form['dettaglionascita']['provincianascita'] = array(
     
'#type' => 'textfield',
     
'#title' => t('Prov'),
     
'#size' => 5,
     
'#maxlength' => 5,
     
'#default_value' => $value['provincianascita'],
     
'#prefix' => '<td>',
       
'#suffix' => '</td>',     
    );
   
   
// Campo Data Nascita   
   
$form['dettaglionascita']['datanascita'] = array(
     
'#type' => 'date',
     
'#title' => t('Data'),
     
'#default_value' => $value['datanascita'],
     
'#prefix' => '<td>',
       
'#suffix' => '</td></tr></table></td></tr>',
    );

     
// Indirizzo (linea NON collasabile)

     
$form['dettaglio'] = array(

       
'#type' => 'fieldset',

       
'#title' => t('Indirizzo Principale'),

         
'#prefix' => '<tr><td>',

           
'#suffix' => '',       

      );



   
// Campo indirizzo   

   
$form['dettaglio']['indirizzo'] = array(

     
'#type' => 'textfield',

     
'#title' => t('Indirizzo'),

     
'#size' => 80,

     
'#maxlength' => 100,

     
'#required' => TRUE,

     
'#default_value' => $value['indirizzo'],

     
'#prefix' => '<table><tr><td colspan=3>',

       
'#suffix' => '</td></tr>',

    );   



   
// Campo CAP

   
$form['dettaglio']['cap'] = array(

     
'#type' => 'textfield',

     
'#title' => t('CAP'),

     
'#size' => 5,

     
'#maxlength' => 5,

     
'#required' => TRUE

     
'#default_value' => $value['cap'],

     
'#prefix' => '<td>',

       
'#suffix' => '</td>',     

    );

   

   
// Campo Città   

   
$form['dettaglio']['citta'] = array(

     
'#type' => 'textfield',

     
'#title' => t('Citta\''),

     
'#size' => 25,

     
'#maxlength' => 25,

     
'#required' => TRUE,    

     
'#default_value' => $value['citta'],

     
'#prefix' => '<td>',

       
'#suffix' => '</td>',

    );



   
// Campo Provincia

   
$form['dettaglio']['provincia'] = array(

     
'#type' => 'textfield',

     
'#title' => t('Provincia'),

     
'#size' => 5,

     
'#maxlength' => 5,

     
'#required' => TRUE,     

     
'#default_value' => $value['provincia'],

     
'#prefix' => '<td>',

       
'#suffix' => '</td></tr></table></td></tr>',

    );   



     
// Indirizzo Alternativo (linea collasabile)

     
$form['dettaglio1'] = array(

       
'#type' => 'fieldset',

       
'#title' => t('Indirizzo Secondario'),

       
'#collapsible' => TRUE,

       
'#collapsed' => TRUE,

         
'#prefix' => '<tr><td>',

           
'#suffix' => '',       

      );



   
// Campo indirizzo secondario   

   
$form['dettaglio1']['indirizzo2'] = array(

     
'#type' => 'textfield',

     
'#title' => t('Indirizzo'),

     
'#size' => 80,

     
'#maxlength' => 100,

     
'#required' => FALSE,

     
'#default_value' => $value['indirizzo2'],

     
'#prefix' => '<table><tr><td colspan=3>',

       
'#suffix' => '</td></tr>',       

    );   



   
// Campo CAP secondario

   
$form['dettaglio1']['cap2'] = array(

     
'#type' => 'textfield',

     
'#title' => t('CAP'),

     
'#size' => 5,

     
'#maxlength' => 5,

     
'#required' => FALSE

     
'#default_value' => $value['cap2'],

     
'#prefix' => '<tr><td>',

       
'#suffix' => '</td>',     

    );

   

   
// Campo Città secondario   

   
$form['dettaglio1']['citta2'] = array(

     
'#type' => 'textfield',

     
'#title' => t('Citta\''),

     
'#size' => 25,

     
'#maxlength' => 25<