• User

    script per inserimento dati in database

    Salve a tutti! (di nuovo..)

    vi interpello per un problemuccio che mi è sorto dopo un interminabile pomeriggio di programmazione :arrabbiato:

    ho fatto una pagina in php con un form per l'inserimento dei dati in un database da me creato in locale, ma purtroppo non funziona. Non mi dilungo in spiegazioni, dico solo che vanno riempite 2 tabelle e quindi richiamo 2 volte la stessa funzione con parametri diversi. lascio parlare il codice al posto mio:

    FORM:

    [HTML]<form action="upload.php" method="post" enctype="multipart/form-data">
    <h1>Informazioni Generali</h1>
    <!-- NOME ARTICOLO -->
    <input class="articolo" name="nome" type="text" placeholder="Inserisci il nome dell'articolo" onclick="this.placeholder='';" onblur="if (this.placeholder=='') this.placeholder='Inserisci il nome dell'articolo';" />
    <!-- DESCRIZIONE ARTICOLO -->
    <textarea name="descrizione" cols="50" rows="100" placeholder="Inserisci la descrizione dell'oggetto" onclick="this.placeholder='';" onblur="if (this.placeholder=='') this.placeholder='Inserisci la descrizione dell'oggetto';"></textarea>
    <!-- INSERISCI IMMAGINE -->
    <input class="file" name="immagine" type="file" /><br /><br />
    <!-- CONDIZIONE DELL'ARTICOLO -->
    <label class="checklabel"><span class="label_title">Condizione:</span><br />
    <input class="checkbox" type="radio" name="condizione" value="nuovo" /><span class="label_check">Nuovo</span><br />
    <input class="checkbox" type="radio" name="condizione" value="usato" /><span class="label_check">Usato</span><br />
    <input class="checkbox" type="radio" name="condizione" value="offerta" /><span class="label_check">Offerta</span><br />
    </label>
    <!-- TIPO DI ARTICOLO -->
    <label class="checklabel"><span class="label_title">Tipo:</span><br />
    <input class="checkbox" type="radio" name="tipo" value="bici" /><span class="label_check">Bici</span>
    <input class="checkbox" type="radio" name="tipo" value="componenti" /><span class="label_check">Componenti</span>
    <input class="checkbox" type="radio" name="tipo" value="mtb" /><span class="label_check">MTB</span><br />
    <input class="checkbox" type="radio" name="tipo" value="telai" /><span class="label_check">Telai</span>
    <input class="checkbox" type="radio" name="tipo" value="abbigliamento" /><span class="label_check">Abbigliamento</span>
    <input class="checkbox" type="radio" name="tipo" value="accessori" /><span class="label_check">Accessori</span><br />
    </label>
    <div class="clear"></div>
    <!-- SOTTOTIPO ARTICOLO -->
    <label class="checklabel"><span class="label_title">Sottotipo:</span><br />
    <input class="checkbox" type="radio" name="sottotipo" value="corsa" /><span class="label_check">Corsa</span>
    <input class="checkbox" type="radio" name="sottotipo" value="triathlon" /><span class="label_check">Triathlon</span>
    <input class="checkbox" type="radio" name="sottotipo" value="ruote-cyclo-cross" /><span class="label_check">Ruote Cyclo-Cross</span>
    <input class="checkbox" type="radio" name="sottotipo" value="ruote-mtb" /><span class="label_check">Ruote MTB</span>
    <input class="checkbox" type="radio" name="sottotipo" value="ruote-pista" /><span class="label_check">Ruote Pista</span><br />
    <input class="checkbox" type="radio" name="sottotipo" value="ruote-strada" /><span class="label_check">Ruote Strada</span>
    <input class="checkbox" type="radio" name="sottotipo" value="mtb-all-mountain" /><span class="label_check">MTB All-mountain</span>
    <input class="checkbox" type="radio" name="sottotipo" value="mtb-cross-country" /><span class="label_check">MTB Cross-Country</span>
    <input class="checkbox" type="radio" name="sottotipo" value="mtb-enduro" /><span class="label_check">MTB Enduro</span>
    <input class="checkbox" type="radio" name="sottotipo" value="mtb-gravity" /><span class="label_check">MTB Gravity</span><br />
    </label>
    <div class="clear"></div>
    <div class="separatore"></div>
    <h1 class="nomarginbottom">Informazioni Specifiche/Tecniche</h1>
    <h3>È possibile lasciare i campi vuoti</h3>
    <div class="cont_spec">
    <span class="label_title">Gruppo:</span><br />
    <input class="specifiche" nome="gruppo" type="text" /><br />
    <span class="label_title">Ruote:</span><br />
    <input class="specifiche" nome="ruote" type="text" /><br />
    <span class="label_title">Attacco:</span><br />
    <input class="specifiche" nome="attacco" type="text" /><br />
    <span class="label_title">Piega:</span><br />
    <input class="specifiche" nome="piega" type="text" /><br />
    <span class="label_title">Sella:</span><br />
    <input class="specifiche" nome="sella" type="text" /><br />
    <span class="label_title">Reggisella:</span><br />
    <input class="specifiche" nome="reggisella" type="text" /><br />
    <span class="label_title">Telaio:</span><br />
    <input class="specifiche" nome="telaio" type="text" /><br />
    </div> <!-- cont_spec -->
    <div class="cont_spec">
    <span class="label_title">Forcella:</span><br />
    <input class="specifiche" nome="forcella" type="text" /><br />
    <span class="label_title">Guarnitura:</span><br />
    <input class="specifiche" nome="guarnitura" type="text" /><br />
    <span class="label_title">Comandi:</span><br />
    <input class="specifiche" nome="comandi" type="text" /><br />
    <span class="label_title">Cassetta:</span><br />
    <input class="specifiche" nome="cassetta" type="text" /><br />
    <span class="label_title">Deragliatore:</span><br />
    <input class="specifiche" nome="deragliatore" type="text" /><br />
    <span class="label_title">Cambio:</span><br />
    <input class="specifiche" nome="cambio" type="text" /><br />
    </div> <!-- cont_spec -->
    <div class="cont_spec">
    <span class="label_title">Ammortizzatore:</span><br />
    <input class="specifiche" nome="ammortizzatore" type="text" /><br />
    <span class="label_title">Coperture:</span><br />
    <input class="specifiche" nome="coperture" type="text" /><br />
    <span class="label_title">Freni:</span><br />
    <input class="specifiche" nome="freni" type="text" /><br />
    <span class="label_title">Mozzi:</span><br />
    <input class="specifiche" nome="mozzi" type="text" /><br />
    <span class="label_title">Cerchi:</span><br />
    <input class="specifiche" nome="cerchi" type="text" /><br />
    <span class="label_title">Colori disponibili:</span><br />
    <input class="specifiche" nome="colori" type="text" /><br />
    </div> <!-- cont_spec -->
    <div class="clear"></div>
    <input class="button_send" name="upload" type="submit" value="Carica" />
    <input class="button_del" name="cancella" type="reset" value="Reset" />
    </form>[/HTML]

    upload.php:

    [PHP]<?php

    // valorizzazione delle variabili con i parametri dal form
    if(isset($_POST['upload'])&&($_POST['upload']=="Carica")){

    if(isset($_POST['nome'])){
    $nome = addslashes(filter_var($_POST['nome'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['descrizione'])){
    $descrizione = addslashes(filter_var($_POST['descrizione'], FILTER_SANITIZE_STRING));
    $descrizione = nl2br($_POST['descrizione']);
    }
    if(isset($_POST['condizione'])){
    $condizione = addslashes(filter_var($_POST['condizione'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['tipo'])){
    $tipo = addslashes(filter_var($_POST['tipo'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['sottotipo'])){
    $sottotipo = addslashes(filter_var($_POST['sottotipo'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['gruppo'])){
    $gruppo = addslashes(filter_var($_POST['gruppo'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['ruote'])){
    $ruote = addslashes(filter_var($_POST['ruote'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['attacco'])){
    $attacco = addslashes(filter_var($_POST['attacco'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['piega'])){
    $piega = addslashes(filter_var($_POST['piega'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['sella'])){
    $sella = addslashes(filter_var($_POST['sella'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['reggisella'])){
    $reggisella = addslashes(filter_var($_POST['reggisella'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['telaio'])){
    $telaio = addslashes(filter_var($_POST['telaio'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST)){
    $colori = addslashes(filter_var($_POST, FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['forcella'])){
    $forcella = addslashes(filter_var($_POST['forcella'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['guarnitura'])){
    $guarnitura = addslashes(filter_var($_POST['guarnitura'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['comandi'])){
    $comandi = addslashes(filter_var($_POST['comandi'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['cassetta'])){
    $cassetta = addslashes(filter_var($_POST['cassetta'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['deragliatore'])){
    $deragliatore = addslashes(filter_var($_POST['deragliatore'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['cambio'])){
    $cambio = addslashes(filter_var($_POST['cambio'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['ammortizzatore'])){
    $ammortizzatore = addslashes(filter_var($_POST['ammortizzatore'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['coperture'])){
    $coperture = addslashes(filter_var($_POST['coperture'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['freni'])){
    $freni = addslashes(filter_var($_POST['freni'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['mozzi'])){
    $mozzi = addslashes(filter_var($_POST['mozzi'], FILTER_SANITIZE_STRING));
    }
    if(isset($_POST['cerchi'])){
    $cerchi = addslashes(filter_var($_POST['cerchi'], FILTER_SANITIZE_STRING));
    }

    //////////////////////////// UPLOAD IMMAGINE ////////////////////////////////

    do {
    if (is_uploaded_file($_FILES['image']['tmp_name'])) {
    // Controllo che il file non superi i 18 KB
    if ($_FILES['image'] > 18432000) {
    $msg = "<p>Il file non deve superare i 18 KB!!</p>";
    break;
    }
    // Ottengo le informazioni sull'immagine
    list($width, $height, $type, $attr) = getimagesize($_FILES['image']['tmp_name']);
    // Controllo che il file sia in uno dei formati GIF, JPG o PNG
    if (($type!=1) && ($type!=2) && ($type!=3)) {
    $msg = "<p>Formato non corretto!!</p>";
    break;
    }
    // Verifico che sul sul server non esista già un file con lo stesso nome
    // In alternativa potrei dare io un nome che sia funzione della data e dell'ora
    if (file_exists('upload_img/'.$_FILES['image']['name'])) {
    $msg = "<p>File già esistente sul server. Rinominarlo e riprovare.</p>";
    break;
    }
    list($ihwidth,$ihheight) = explode('x',$grandezza);
    //IMPOSTO UN MASSIMALE PER LE IMMAGINI
    $am = "319";
    $lm = "689";

    if($ihwidth > $lm or $ihheight > $am) {
    $eliminarel = $ihwidth - $lm;
    $eliminarea = $ihheight - $am;
    if ($eliminarel >= $eliminarea) { $perc = round(($eliminarel100)/$ihwidth);
    $ihw = round(($ihwidth/100)
    $perc);
    $ihwidth1 = $ihwidth-$ihw;
    $ihh = round(($ihheight/100)$perc);
    $ihheight1 = $ihheight - $ihh;
    }
    else if ($eliminarel < $eliminarea) { $perc = round(($eliminarea
    100)/$ihheight);
    $ihw = round(($ihwidth/100)$perc);
    $ihwidth1 = $ihwidth-$ihw;
    $ihh = round(($ihheight/100)
    $perc);
    $ihheight1 = $ihheight - $ihh;
    }
    }
    else {
    $ihwidth1 = $ihwidth;
    $ihheight1 = $ihheight;
    }
    // Sposto il file nella cartella da me desiderata
    if (!move_uploaded_file($_FILES['image']['tmp_name'], 'upload_img/'.$_FILES['image']['name'])) {
    $msg = "<p>Errore nel caricamento dell'immagine!!</p>";
    break;
    }
    }
    } while (false);
    echo $msg;

    $file = $_FILES['image']['name'];

    // inclusione del file della classe
    include "funzioni_mysql.php";
    // istanza della classe
    $data = new MysqlClass();
    // chiamata alla funzione di connessione
    $data->connetti();
    $t = "annuncio"; # nome della tabella
    $v = array ($nome,$descrizione,$file,$condizione,$tipo,$sottotipo); # valori da inserire
    $r = "nome,descrizione,immagine,condizione,tipo,sottotipo"; # campi da popolare

    // chiamata alla funzione per l?inserimento dei dati
    $data->inserisci($t,$v,$r);

    // nuovo inserimento
    $t = "specifiche_annunci";
    $v = array ($gruppo,$ruote,$attacco,$piega,$sella,$reggisella,$telaio,$forcella,$guarnitura,$comandi,$cassetta,$deragliatore,$cambio,$ammortizzatore,$coperture,$freni,$mozzi,$cerchi,$colori);
    $r = "gruppo,ruote,attacco,piega,sella,reggisella,telaio,forcella,guarnitura,comandi,cassetta,deragliatore,cambio,ammortizzatore,coperture,freni,mozzi,cerchi,colori";
    $data->inserisci($t,$v,$r);
    echo "Articolo inserito con successo.";    
    

    } else echo "Articolo non inserito";
    $data->disconnetti();
    ?>[/PHP]

    funzioni_mysql.php:

    [PHP]<?phpclass MysqlClass
    {
    // variabili per la connessione al database
    private $nomehost = "localhost:8889";
    private $nomeuser = "root";
    private $password = "root";
    private $nomedb = "ciclistimoli_prodotti";

    // controllo sulle connessioni attive
    private $attiva = false;
    
    
    // funzione per la connessione a MySQL
    public function connetti()
    {
        if(!$this->attiva)
        {
         if($connessione = mysql_connect($this->nomehost,$this->nomeuser,$this->password) or die (mysql_error()))
         {
         $selezione = mysql_select_db($this->nomedb,$connessione) or die (mysql_error());
         }
        }else{
         return true;
        }
    }
    
    //funzione per l'esecuzione delle query 
    

    public function query($sql)
    {
    if(isset($this->attiva))
    {
    $sql = mysql_query($sql) or die (mysql_error());
    return $sql;
    }else{
    return false;
    }
    }

    //funzione per l'inserimento dei dati in tabella
    public function inserisci($t,$v,$r = null)
    {
    if(isset($this->attiva))
    {
    $istruzione = 'INSERT INTO '.$t;
    if($r != null)
    {
    $istruzione .= ' ('.$r.')';
    }

            for($i = 0; $i < count($v); $i++)
            {
                if(is_string($v*))
                    $v* = '"'.$v*.'"';
            }
            $v = implode(',',$v);
            $istruzione .= ' VALUES ('.$v.')';
    
    
            $query = mysql_query($istruzione) or die (mysql_error());
    
    
            }else{
                return false;
            }
        }
    

    //funzione per l'estrazione dei record
    public function estrai($risultato)
    {
    if(isset($this->attiva))
    {
    $r = mysql_fetch_object($risultato);
    return $r;
    }else{
    return false;
    }
    }

    // funzione per la chiusura della connessione
    public function disconnetti()
    {
    if($this->attiva)
    {
    if(mysql_close())
    {
    $this->attiva = false;
    return true;
    }else{
    return false;
    }
    }
    }

    }
    ?>[/PHP]

    Quando sul form clicco sul pulsante "Carica" mi esce questo messaggio:

    "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"usato","componenti","triathlon")' at line 1"

    potrebbe essere nei radio-button il problema? (io ho richiamato i dati come quelli delle aree input type="text" perche comunque penso che si trattino come testo, a me serve che passi il valore di testo che c'è scritto nei radio-button).


  • User Attivo

    Dovreste abituarvi a fare sempre un echo della query prima di inviarla al DB, notereste subito se ci sono degli errori. In questo caso immagino tu debba fare un echo della variabile $istruzione presente nel metodo "inserisci". Senza sapere cosa viene passato al db è difficile risalire all'errore.

    Non ho provato lo script e a occhio vedo solo un errore per quanto riguarda l'HTML. E' sbagliato l'attributo "nome" invece di "name". Al momento il form non passa nessuna variabile "specifiche/tecniche".

    Ciao.


  • User

    Ok ho inserito l'echo della query ma non mi visualizza nulla a schermo.. Come mai? L'ho inserito nella funzione inserisci nel file funzioni_mysql prima dell'esecuzione della query quindi prima di

    $query = mysql_query($istruzione) or die (mysql_error());

    giusto? Però la pagina resta bianca, non visualizza nemmeno uno dei due messaggi che ho impostato alla fine per vedere se va a buon fine o non va a buon fine...


  • User Attivo

    Prova a mettere queste funzioni all'inizio del file upload.php
    [PHP]
    <?php
    error_reporting(E_ALL);
    ini_set("display_errors", 1);
    [/PHP]
    poi riprova.

    Scrivici anche lo script con la modifica echo che hai fatto. Inoltre hai cambiato "nome" in "name", vero?


  • User

    si ho cambiato nome in name infatti non dà più quell'errore che scrivevo prima... ora provo in quel modo..

    Quello che ho modificato è la funzione "inserisci" nel file funzioni_mysql.php:

    [PHP]//funzione per l'inserimento dei dati in tabella public function inserisci($t,$v,$r = null)
    {
    if(isset($this->attiva))
    {
    $istruzione = 'INSERT INTO '.$t;
    if($r != null)
    {
    $istruzione .= ' ('.$r.')';
    }

            for($i = 0; $i < count($v); $i++)
            {
                if(is_string($v*))
                    $v* = '"'.$v*.'"';
            }
            $v = implode(',',$v);
            $istruzione .= ' VALUES ('.$v.')';
            
            echo $istruzione;
    
    
            $query = mysql_query($istruzione) or die (mysql_error());
    
    
            }else{
                return false;
            }
        }[/PHP]
    

    Ora provo a fare come hai detto tu..


  • User

    ok... sono comparsi diversi errori, questo è quello che visualizzo:

    **Warning: mysql_connect(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in **F:\Sito CicliStimoli\Sito Ciclistimoli\funzioni_mysql.php on line **22

    **Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in **F:\Sito CicliStimoli\Sito Ciclistimoli\funzioni_mysql.php on line **22

    **Warning: MysqlClass::inserisci(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in **F:\Sito CicliStimoli\Sito Ciclistimoli\funzioni_mysql.php on line **62

    **Fatal error: Undefined constant 'n' in **F:\Sito CicliStimoli\Sito Ciclistimoli\funzioni_mysql.php on line **62

    ************************l'ultimo è perchè avevo dimenticato le virgolette.


  • User Attivo

    I primi 3 errori ci interessano relativamente. Non influiscono, al momento, sul corretto funzionamento del codice.
    L'ultimo errore invece è quello che conta. Una volta risolto quello devi vedere se ce ne sono altri e cosa ti restiruiscono gli echo delle varie query, risolvere gli inghippi e andare avanti :smile5:


  • User

    ci sono riuscito 😄 l'errore era nel richiamo dell'immagine.. cercava un campo con name="image" e invece l'input era con name="immagine".

    Grazie mille per l'aiuto! 😄


  • User Attivo

    Ottimo! Una volta che il sito è on-line (e immagino che tu stia già lavorando in remoto) ricordati di togliere le due funzioni che visualizzano gli errori. Potrebbero fornire informazioni per bucarti il sito.
    Ciao.