Visualizzazione risultati 1 fino 17 di 17

Discussione: Perdita connessione al Database con una classe php

  1. #1
    Guest

    Predefinito Perdita connessione al Database con una classe php

    Ho iniziato a lavorara con la programmazione orientata agli oggetti da poco tempo e per allenamento sto creandomi una classe per la gestione dei dati nel database mysql, ma mi sono bloccato nella gestione delle query. Ecco la classe:
    Codice PHP:
    class Database {

    private
    $db_name = 'name';
    private
    $db_user = 'user';
    private
    $db_host = 'localhost';
    private
    $db_pass = '******';

    function
    Database($db_name = null, $db_user = null, $db_host = null, $db_pass = null)
    {
    if(
    $this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass))
    {
    mysql_select_db($db_name, $this->connection);
    }
    else
    {
    $this->error(true);
    }

    }

    function
    query($sql)
    {
    if(!empty(
    $sql))
    {
    $result = @mysql_query(&$sql, $this->connection);
    if(!(
    $result))
    {
    $this->error(true);
    $result = false;
    }
    return
    $result;
    }
    else
    {
    trigger_error('Sql empty', E_USER_WARNING);
    }
    }


    function
    close()
    {
    if(
    $this->connection)
    {
    @
    mysql_close($this->connection);
    }
    }
    Poi faccio:
    Codice PHP:
    $db = new Database();
    $row = $db->query('SELECT * FROM ' . USERS_TABLE);
    Ma mi viene restituito 1046: No database selected.

    Consigli, suggerimenti, correzioni?

  2. #2
    Guest

    Predefinito

    La variabile connection non è presente tra gli attributi della classe.
    Inoltre questa riga è errata
    Codice PHP:
    $result = @mysql_query(&$sql, $this->connection);
    dovrebbe essere
    Codice PHP:
    $result = @mysql_query($sql, $this->connection);

  3. #3
    Guest

    Predefinito

    Ho aggiunto dopo le private questo:
    Codice PHP:
    var $connection;
    Modificato come mi hai detto, ma mi restituisce sempre quel 1046

  4. #4
    Guest

    Predefinito

    Codice PHP:
    mysql_select_db($db_name, $this->connection);
    Devi cambiarlo in
    Codice PHP:
    mysql_select_db($this->db_name, $this->connection);
    Comunque usare il costruttore con il nome della classe potrebbe essere sconveniente, le prossime release del php potrebbero cambiare questa cosa (di fatto si usa __costruct per definire il costruttore, il nome del costruttore uguale alla classe mi sembra che sta li per retrocompatibilità, ma potrei sbagliarmi, in ogni caso meglio __construct).

    Inoltre se metti i parametri al costruttore con quella scrittura che hai messo tu prenderai sempre le variabili membro della classe e non i parametri passati al costruttore.
    Ultima modifica di stoner : 09-09-2009 alle ore 18.55.38

  5. #5
    Guest

    Predefinito

    Grazie dei consigli, puoi spiegarmi meglio la seconda parte? Cioè, io vorrei fare in modo che le variabili per la connessione sia definite all'interno della classe, però se voglio inziializzare la classe con altri dati per connettermi, mi prenda quella passati alla classe quando la inizializzo

  6. #6
    Guest

    Predefinito

    stoner dice che se tu fai:
    Codice PHP:
    $db = new Database("nome_db","User_db"/*....*/);
    vengono utilizzati comunque i dati che già hai memorizzato nelle variabili di classe.
    Inoltre, dal php5, il costruttore della classe (il tuo metodo Database()) si deve chiamare per forza __construct(). L'errore ti viene restituito, credo, perchè php interpreta la tua classe come una classe senza costruttore, e quando esegui la chiamata a mysql_query spunta. Inoltre manca la parentesi } di chiusura della classe. Mi sono permesso di modificarti il codice:
    Codice PHP:
    <?php
    class Database {
    private
    $db_name, $db_user, $db_host, $db_pass;
    public function
    __construct($db_name, $db_user, $db_host, $db_pass) {
    $this->db_name = $this->db_name;
    $this->db_user = $this->db_user;
    $this->db_host = $this->db_host;
    $this->db_pass = $this->db_pass;
    if(
    $this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass))
    mysql_select_db($db_name, $this->connection);
    else
    $this->error(true);
    }
    function
    query($sql) {
    if(!empty(
    $sql)) {
    $result = @mysql_query($sql, $this->connection);
    if(!(
    $result)) {
    $this->error(true);
    $result = false;
    }
    return
    $result;
    } else
    trigger_error('Sql empty', E_USER_WARNING);
    }
    function
    close() {
    if(
    $this->connection)
    @
    mysql_close($this->connection);
    }
    }
    ?>
    (non l'ho testato).
    Ultima modifica di gabryhacker : 09-09-2009 alle ore 19.38.20 Motivo: Svista nel codice.

  7. #7
    Guest

    Predefinito

    Usando la tua classe non mi si connette, mi dice 1045: Access denied for user 'ODBC'@'localhost' (using password: NO)

    Mancava una parentesi perchè in locale ho altro codice che non serviva qui.

    Comunque eccola completamente:
    Codice PHP:
    <?php

    class Database {
    private
    $db_name, $db_user, $db_host, $db_pass;
    var
    $connection;
    var
    $query_result;

    function
    __costruct($db_name, $db_user, $db_host, $db_pass)
    {
    if(
    $this->connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass))
    {
    mysql_select_db($this->db_name, $this->connection);
    $this->db_security('unset');
    }
    else
    {
    $this->db_security('unset');
    $this->error(true);
    }

    }

    function
    close()
    {
    if(
    $this->connection)
    {
    @
    mysql_close($this->connection);
    }
    }

    function
    query($sql)
    {
    if(!empty(
    $sql))
    {
    $result = @mysql_query($sql, $this->connection);
    if(!
    $result)
    {
    $this->error($query = true);
    $result = false;
    }
    return
    $result;
    }
    else
    {
    trigger_error('Sql empty', E_USER_WARNING);
    }
    }

    function
    fetch_row(&$sql)
    {
    @
    mysql_fetchrow($sql);
    }

    function
    error($query = false)
    {
    global
    $lang;

    $debug = debug_backtrace();

    $output = '';
    foreach(
    $debug as $number => $trace)
    {
    if(
    $number > 0)
    {
    $output .= '<br />';
    $output .= '<b>FILE:</b> ' . htmlspecialchars($trace['file']) . '<br />';
    $output .= '<b>LINE:</b> ' . ((!empty($trace['line'])) ? $trace['line'] : '') . '<br />';
    $output .= '<b>CALL:</b> ' . htmlspecialchars($trace['class'] . $trace['type'] . $trace['function']) . '()<br />';
    }
    }

    $message = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
    $message .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="it-it" lang="it-it">';
    $message .= '<head><title>' . $lang['ERROR']['GENERAL'] . '</title>';
    $message .= '<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /><meta name="author" content="FedericoBiccheddu" />';
    $message .= '<meta name="robots" content="noindex, nofollow" /><link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />';
    $message .= '<style type="text/css"> /* <![CDATA[ */';
    $message .= '* { margin: 0; padding: 0; } html { font-size: 100%; height: 100%; margin-bottom: 1px; background-color: #E4EDF0; } body { font-family: "Lucida Grande", Verdana, Helvetica, Arial, sans-serif; color: #536482; background: #E4EDF0; font-size: 62.5%; margin: 0; padding: 15px;} ';
    $message .= 'a:link, a:active, a:visited { color: #006699; text-decoration: none; } a:hover { color: #DD6900; text-decoration: underline; } ';
    $message .= '#page-footer { clear: both; padding: 5px; font-size: 1em; text-align: center; border-top: 1px solid #CCCCCC; } ';
    $message .= '.panel { padding: 10px; margin: 5px 0; background-color: #FFFFFF; border: solid 1px #A9B8C2; } ';
    $message .= '#error #content h1 { line-height: 1em; margin-bottom: 0; color: #DF075C; } ';
    $message .= '#error #content { color: #333333; font: bold 1.2em "Lucida Grande", Arial, Helvetica, sans-serif; text-decoration: none; text-align: left; } ';
    $message .= ' /* ]]> */';
    $message .= '</style></head>';
    $message .= '<body id="error">';
    $message .= '<div id="content" class="panel">';
    $message .= '<h1>' . $lang['ERROR']['GENERAL'] . '</h1>';
    $message .= '<div>';
    $message .= $output . (($sql !== false) ? mysql_errno() . ': ' . mysql_error() : '') . '</div>';
    $message .= '<div id="page-footer">&copy; 2009 Federico Biccheddu</div></div></body></html>';
    die(
    $message);
    }

    private function
    db_security($mode = null)
    {
    switch(
    $mode)
    {
    case
    'unset':
    unset(
    $this->db_name);
    unset(
    $this->db_user);
    unset(
    $this->db_host);
    unset(
    $this->db_pass);
    break;

    default:
    return;
    }
    }
    }

    ?>
    Istanzio ed uso così:
    Codice PHP:
    $db = new Database('db_name', 'db_root', 'db_host', 'db_pass');
    $query = $db->query('SELECT * FROM ' . USERS_TABLE);
    Non mi restituisce nessun errore di mysql però

  8. #8
    Guest

    Predefinito

    Ma funziona o non funziona?
    EDIT: se non funziona, prova a togliere la @ davanti a mysql_query()
    Ultima modifica di gabryhacker : 09-09-2009 alle ore 20.20.33

  9. #9
    Guest

    Predefinito

    Gestisco gli errori grazie a set_error_handler(), e mi restituisce:
    Codice:
    Warning [2] mysql_query() expects parameter 2 to be resource, null given
    Quindi non funziona

  10. #10
    Guest

    Predefinito

    Quando nel costruttore chiami $this->variabile. Viene richiamato il membro della classe, quando chiami $variabile, viene chiamato il parametro
    Codice PHP:
    <?php

    class a {
    private
    $a = "bb";
    public
    __construct($a="cc") {
    echo
    $this->a;
    }
    }

    class
    b {
    private
    $a = "bb";
    public
    __construct($a="cc") {
    echo
    $a;
    }
    }
    $r = new a();
    $g = new b();
    ?>
    In quel caso vai a richiamarei membri della classe, che non sono inizializzati, quindi vuoti, non può connettersi, e quindi da errore.

    In quel caso dovresti modificare così il costruttore
    Codice PHP:
    function __costruct($db_name, $db_user, $db_host, $db_pass)
    {
    if(
    $this->connection = mysql_connect($db_host, $db_user, $db_pass))
    {
    mysql_select_db($db_name, $this->connection);
    $this->db_security('unset');
    }
    else
    {
    $this->db_security('unset');
    $this->error(true);
    }

    }

  11. #11
    Guest

    Predefinito

    Siccome non mi volevo complicare la vita risolto così, grazie lo stesso a tutti e due:
    Codice PHP:
    class Database {
    var
    $connection;

    function
    __construct($db_name, $db_user, $db_host, $db_pass)
    {
    $this->connection = @mysql_connect($db_host, $db_user, $db_pass);
    if(
    $this->connection)
    {
    @
    mysql_select_db($db_name, $this->connection);
    }
    else
    {
    #Eventuali messaggi di errore.
    }
    }
    }
    Se va tutto bene ok e vi ringrazio ancora, altrimenti dove sbaglio?

  12. #12
    Guest

    Predefinito

    Cioè? L'hai provato se funziona o no?

  13. #13
    Guest

    Predefinito

    Si, funziona, però magari c'è qualche errore, come prima. Questa è la classe che utilizzo:
    Codice PHP:
    <?php

    class Database {
    var
    $connection;
    var
    $query_result = '';

    function
    __construct($db_name, $db_user, $db_host, $db_pass)
    {
    $this->connection = @mysql_connect($db_host, $db_user, $db_pass);
    if(
    $this->connection)
    {
    @
    mysql_select_db($db_name, $this->connection);
    $this->db_security('unset');
    }
    else
    {
    $this->db_security('unset');
    $this->error(true);
    }
    }

    function
    query(&$sql)
    {
    if(!(
    $this->query_result = mysql_query($sql, $this->connection)))
    {
    echo
    $this->error(true);
    }

    return
    $this->query_result;

    }

    function
    fetch_row(&$sql)
    {
    return
    mysql_fetch_row($sql);
    }

    function
    fetch_array(&$sql)
    {
    return
    mysql_fetch_array(&$sql, MYSQL_ASSOC);
    }

    function
    error($query = false)
    {
    global
    $lang;

    $debug = debug_backtrace();

    $output = '';
    foreach(
    $debug as $number => $trace)
    {
    if(
    $number > 0)
    {
    $output .= '<br />';
    $output .= '<b>FILE:</b> ' . htmlspecialchars($trace['file']) . '<br />';
    $output .= '<b>LINE:</b> ' . ((!empty($trace['line'])) ? $trace['line'] : '') . '<br />';
    $output .= '<b>CALL:</b> ' . htmlspecialchars($trace['class'] . $trace['type'] . $trace['function']) . '()<br />';
    }
    }

    $message = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
    $message .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="it-it" lang="it-it">';
    $message .= '<head><title>' . $lang['ERROR']['GENERAL'] . '</title>';
    $message .= '<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /><meta name="author" content="FedericoBiccheddu" />';
    $message .= '<meta name="robots" content="noindex, nofollow" /><link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />';
    $message .= '<style type="text/css"> /* <![CDATA[ */';
    $message .= '* { margin: 0; padding: 0; } html { font-size: 100%; height: 100%; margin-bottom: 1px; background-color: #E4EDF0; } body { font-family: "Lucida Grande", Verdana, Helvetica, Arial, sans-serif; color: #536482; background: #E4EDF0; font-size: 62.5%; margin: 0; padding: 15px;} ';
    $message .= 'a:link, a:active, a:visited { color: #006699; text-decoration: none; } a:hover { color: #DD6900; text-decoration: underline; } ';
    $message .= '#page-footer { clear: both; padding: 5px; font-size: 1em; text-align: center; border-top: 1px solid #CCCCCC; } ';
    $message .= '.panel { padding: 10px; margin: 5px 0; background-color: #FFFFFF; border: solid 1px #A9B8C2; } ';
    $message .= '#error #content h1 { line-height: 1em; margin-bottom: 0; color: #DF075C; } ';
    $message .= '#error #content { color: #333333; font: bold 1.2em "Lucida Grande", Arial, Helvetica, sans-serif; text-decoration: none; text-align: left; } ';
    $message .= ' /* ]]> */';
    $message .= '</style></head>';
    $message .= '<body id="error">';
    $message .= '<div id="content" class="panel">';
    $message .= '<h1>' . $lang['ERROR']['GENERAL'] . '</h1>';
    $message .= '<div>';
    $message .= $output . (($sql !== false) ? mysql_errno() . ': ' . mysql_error() : '') . '</div>';
    $message .= '<div id="page-footer">&copy; 2009 Federico Biccheddu</div></div></body></html>';
    die(
    $message);
    }


    function
    close()
    {
    if(
    $this->connection)
    {
    @
    mysql_close($this->connection);
    }
    }

    private function
    db_security($mode = null)
    {
    switch(
    $mode)
    {
    case
    'unset':
    unset(
    $this->db_name);
    unset(
    $this->db_user);
    unset(
    $this->db_host);
    unset(
    $this->db_pass);
    break;

    default:
    return;
    }
    }
    }

    ?>

  14. #14
    Guest

    Predefinito

    Mi spieghi perchè passi i parametri per riferimento se non vengono mai modificati dalla funzione?
    Codice PHP:
    function query(&$sql)
    {
    if(!(
    $this->query_result = mysql_query($sql, $this->connection)))
    {
    echo
    $this->error(true);
    }

    return
    $this->query_result;

    }

    function
    fetch_row(&$sql)
    {
    return
    mysql_fetch_row($sql);
    }

    function
    fetch_array(&$sql)
    {
    return
    mysql_fetch_array(&$sql, MYSQL_ASSOC);
    }
    ...
    Codice PHP:
    function query($sql)
    {
    if(!(
    $this->query_result = mysql_query($sql, $this->connection)))
    {
    echo
    $this->error(true);
    }

    return
    $this->query_result;

    }

    function
    fetch_row($sql)
    {
    return
    mysql_fetch_row($sql);
    }

    function
    fetch_array($sql)
    {
    return
    mysql_fetch_array($sql, MYSQL_ASSOC);
    }

  15. #15
    Guest

    Predefinito

    L'& favanti alla variabile, non voleva dire che li prendeva direttamente dalla memoria in modo da velocizzare leggermente?

  16. #16
    Guest

    Predefinito

    No

    Significa che passi il parametro per riferimento, questo implica che se effettui modifiche all'interno della funzione su quel parametro (parametro formale), le modifiche si riperquoto anche sul parametro attuale (quello che passi quando richiami la funzione).

  17. #17
    Guest

    Predefinito

    Ahn capito, scusami

Regole di scrittura

  • Non puoi creare nuove discussioni
  • Non puoi rispondere ai messaggi
  • Non puoi inserire allegati.
  • Non puoi modificare i tuoi messaggi
  •