chiusura connessione database.

Discussioni e problematiche sul linguaggio PHP

Moderatori: maurizio, markdesign

Regole del forum
Per scrivere del codice all'interno di ogni post, utilizzare il tag: [syntax=il_linguaggio]codice[/syntax] sostituendo "il_linguaggio" con il linguaggio del codice che dovete inserire, ad esempio: html, css, javascript, php, asp, ecc...

chiusura connessione database.

Messaggioda gigi » martedì 24 maggio 2011, 21:30

Salve, ho questa classe , ma mi sa che gli manca qualcosa tipo la chiusura $db->close();
Mi dite come posso farla?

Si come che con questa classe ho già un'area riservata completa e non la vorrei cambiare...

vi posto il codice:
Sintassi: php [ Scarica ] [ Nascondi ]
  1. <?php
  2.         // ==================================================================
  3.         //  Author: Justin Vincent (justin@visunet.ie)
  4.         //      Web:    http://www.justinvincent.com
  5.         //      Name:   ezSQL
  6.         //      Desc:   Class to make it very easy to deal with mySQL database connections.
  7.         // ==================================================================
  8.         //      ezSQL Constants
  9.         define("EZSQL_VERSION","1.01");
  10.         define("OBJECT","OBJECT",true);
  11.         define("ARRAY_A","ARRAY_A",true);
  12.         define("ARRAY_N","ARRAY_N",true);
  13.  
  14.         // ==================================================================
  15.         //      The Main Class
  16.        
  17.         class db {
  18.        
  19.                 // ==================================================================
  20.                 //      DB Constructor - connects to the server and selects a database
  21.                
  22.                 function db($dbuser, $dbpassword, $dbname, $dbhost)
  23.                 {
  24.        
  25.                         $this->dbh = @mysql_connect($dbhost,$dbuser,$dbpassword);
  26.                        
  27.                         if ( ! $this->dbh )
  28.                         {
  29.                                 $this->print_error("<ol><b>Error establishing a database connection!</b><li>Are you sure you have the correct user/password?<li>Are you sure that you have typed the correct hostname?<li>Are you sure that the database server is running?</ol>");
  30.                         }
  31.                        
  32.                                
  33.                         $this->select($dbname);
  34.                
  35.                 }
  36.                
  37.                 // ==================================================================
  38.                 //      Select a DB (if another one needs to be selected)
  39.                
  40.                 function select($db)
  41.                 {
  42.                         if ( !@mysql_select_db($db,$this->dbh))
  43.                         {
  44.                                 $this->print_error("<ol><b>Error selecting database <u>$db</u>!</b><li>Are you sure it exists?<li>Are you sure there is a valid database connection?</ol>");
  45.                         }
  46.                 }
  47.        
  48.                 // ==================================================================
  49.                 //      Print SQL/DB error.
  50.        
  51.                 function print_error($str = "")
  52.                 {
  53.                        
  54.                         if ( !$str ) $str = mysql_error();
  55.                        
  56.                         // If there is an error then take note of it
  57.                         print "<blockquote><font face=arial size=2 color=ff0000>";
  58.                         print "<b>SQL/DB Error --</b> ";
  59.                         print "[<font color=000077>$str</font>]";
  60.                         print "</font></blockquote>";  
  61.                 }
  62.        
  63.                 // ==================================================================
  64.                 //      Basic Query     - see docs for more detail
  65.                
  66.                 function query($query, $output = OBJECT)
  67.                 {
  68.                        
  69.                         // Log how the function was called
  70.                         $this->func_call = "\$db->query(\"$query\", $output)";         
  71.                        
  72.                         // Kill this
  73.                         $this->last_result = null;
  74.                         $this->col_info = null;
  75.        
  76.                         // Keep track of the last query for debug..
  77.                         $this->last_query = $query;
  78.                        
  79.                         // Perform the query via std mysql_query function..
  80.                         $this->result = mysql_query($query,$this->dbh);
  81.        
  82.                         if ( mysql_error() )
  83.                         {                              
  84.                                 // If there is an error then take note of it..
  85.                                 $this->print_error();
  86.                                 return FALSE;  
  87.                         }
  88.                         else {
  89.        
  90.                                 // In other words if this was a select statement..
  91.                                 if ( $this->result )
  92.                                 {
  93.        
  94.                                         // =======================================================
  95.                                         // Take note of column info
  96.                                        
  97.                                         $i=0;
  98.                                         while ($i < @mysql_num_fields($this->result))
  99.                                         {
  100.                                                 $this->col_info[$i] = @mysql_fetch_field($this->result);
  101.                                                 $i++;
  102.                                         }
  103.        
  104.                                         // =======================================================                             
  105.                                         // Store Query Results
  106.                                        
  107.                                         $i=0;
  108.                                         while ( $row = @mysql_fetch_object($this->result) )
  109.                                         {
  110.        
  111.                                                 // Store relults as an objects within main array
  112.                                                 $this->last_result[$i] = $row;
  113.                                                
  114.                                                 $i++;
  115.                                         }
  116.                                        
  117.                                         @mysql_free_result($this->result);
  118.                                 }
  119.                                
  120.                                 return TRUE;
  121.        
  122.                         }
  123.                 }
  124.                
  125.                 // ==================================================================
  126.                 //
  127.                
  128.                 function RecordCount ( $query )
  129.                 {
  130.                         return mysql_num_rows ( mysql_query ( $query ) );
  131.                 }
  132.                
  133.                 // ==================================================================
  134.                 //
  135.                
  136.                 function Mresult ( $query, $a, $b )
  137.                 {
  138.                         return mysql_result ( mysql_query ( $query ), $a, $b );
  139.                 }
  140.                
  141.                 /**
  142.                  * Correctly quotes a string so that all strings are escape coded.
  143.                  *
  144.                  * @param string                        the string to quote
  145.                  * @param [magic_quotes]        if $s is GET/POST var, set to get_magic_quotes_gpc().
  146.                  */
  147.  
  148.                 function qstr ( $string, $magic_quotes = false )
  149.                 {
  150.                         if (!$magic_quotes) {
  151.                                 if (strnatcmp(PHP_VERSION, '4.3.0') >= 0) {
  152.                                         return "'" . mysql_real_escape_string($string) . "'";
  153.                                 }
  154.                                 $string = str_replace("'", "\\'" , str_replace('\\', '\\\\', str_replace("\0", "\\\0", $string)));
  155.                                 return  "'" . $string . "'";
  156.                         }
  157.                         return "'" . str_replace('\\"', '"', $string) . "'";
  158.                 }
  159.        
  160.                 // ==================================================================
  161.                 //      Get one variable from the DB - see docs for more detail
  162.                
  163.                 function get_var($query=null,$x=0,$y=0)
  164.                 {
  165.                        
  166.                         // Log how the function was called
  167.                         $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  168.                        
  169.                         // If there is a query then perform it if not then use cached results..
  170.                         if ( $query )
  171.                         {
  172.                                 $this->query($query);
  173.                         }
  174.                        
  175.                         // Extract var out of cached results based x,y vals
  176.                         if ( $this->last_result[$y] )
  177.                         {
  178.                                 $values = array_values(get_object_vars($this->last_result[$y]));
  179.                         }
  180.                        
  181.                         // If there is a value return it else return null
  182.                         return $values[$x]?$values[$x]:null;
  183.                 }
  184.        
  185.                 // ==================================================================
  186.                 //      Get one row from the DB - see docs for more detail
  187.                
  188.                 function getRow($query=null,$y=0,$output=OBJECT)
  189.                 {
  190.                        
  191.                         // Log how the function was called
  192.                         $this->func_call = "\$db->getRow(\"$query\",$y,$output)";
  193.                        
  194.                         // If there is a query then perform it if not then use cached results..
  195.                         if ( $query )
  196.                         {
  197.                                 $this->query($query);
  198.                         }
  199.        
  200.                         // If the output is an object then return object using the row offset..
  201.                         if ( $output == OBJECT )
  202.                         {
  203.                                 return $this->last_result[$y]?$this->last_result[$y]:null;
  204.                         }
  205.                         // If the output is an associative array then return row as such..
  206.                         elseif ( $output == ARRAY_A )
  207.                         {
  208.                                 return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;    
  209.                         }
  210.                         // If the output is an numerical array then return row as such..
  211.                         elseif ( $output == ARRAY_N )
  212.                         {
  213.                                 return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;
  214.                         }
  215.                         // If invalid output type was specified..
  216.                         else
  217.                         {
  218.                                 $this->print_error(" \$db->getRow(string query,int offset,output type) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N ");     
  219.                         }
  220.        
  221.                 }
  222.        
  223.                 // ==================================================================
  224.                 //      Function to get 1 column from the cached result set based in X index
  225.                 // se docs for usage and info
  226.        
  227.                 function get_col($query=null,$x=0)
  228.                 {
  229.                        
  230.                         // If there is a query then perform it if not then use cached results..
  231.                         if ( $query )
  232.                         {
  233.                                 $this->query($query);
  234.                         }
  235.                        
  236.                         // Extract the column values
  237.                         for ( $i=0; $i < count($this->last_result); $i++ )
  238.                         {
  239.                                 $new_array[$i] = $this->get_var(null,$x,$i);
  240.                         }
  241.                        
  242.                         return $new_array;
  243.                 }
  244.        
  245.                 // ==================================================================
  246.                 // Return the the query as a result set - see docs for more details
  247.                
  248.                 function get_results($query=null, $output = OBJECT)
  249.                 {
  250.                        
  251.                         // Log how the function was called
  252.                         $this->func_call = "\$db->get_results(\"$query\", $output)";
  253.                        
  254.                         // If there is a query then perform it if not then use cached results..
  255.                         if ( $query )
  256.                         {
  257.                                 $this->query($query);
  258.                         }              
  259.        
  260.                         // Send back array of objects. Each row is an object           
  261.                         if ( $output == OBJECT )
  262.                         {
  263.                                 return $this->last_result;
  264.                         }
  265.                         elseif ( $output == ARRAY_A || $output == ARRAY_N )
  266.                         {
  267.                                 if ( $this->last_result )
  268.                                 {
  269.                                         $i=0;
  270.                                         foreach( $this->last_result as $row )
  271.                                         {
  272.                                                
  273.                                                 $new_array[$i] = get_object_vars($row);
  274.                                                
  275.                                                 if ( $output == ARRAY_N )
  276.                                                 {
  277.                                                         $new_array[$i] = array_values($new_array[$i]);
  278.                                                 }
  279.        
  280.                                                 $i++;
  281.                                         }
  282.                                
  283.                                         return $new_array;
  284.                                 }
  285.                                 else
  286.                                 {
  287.                                         return null;   
  288.                                 }
  289.                         }
  290.                 }
  291.        
  292.        
  293.                 // ==================================================================
  294.                 // Function to get column meta data info pertaining to the last query
  295.                 // see docs for more info and usage
  296.                
  297.                 function get_col_info($info_type="name",$col_offset=-1)
  298.                 {
  299.        
  300.                         if ( $this->col_info )
  301.                         {
  302.                                 if ( $col_offset == -1 )
  303.                                 {
  304.                                         $i=0;
  305.                                         foreach($this->col_info as $col )
  306.                                         {
  307.                                                 $new_array[$i] = $col->{$info_type};
  308.                                                 $i++;
  309.                                         }
  310.                                         return $new_array;
  311.                                 }
  312.                                 else
  313.                                 {
  314.                                         return $this->col_info[$col_offset]->{$info_type};
  315.                                 }
  316.                        
  317.                         }
  318.                        
  319.                 }
  320.        
  321.        
  322.                 // ==================================================================
  323.                 // Dumps the contents of any input variable to screen in a nicely
  324.                 // formatted and easy to understand way - any type: Object, Var or Array
  325.        
  326.                 function vardump($mixed)
  327.                 {
  328.  
  329.                         echo "<blockquote><font color=000090>";
  330.                         echo "<pre><font face=arial>";
  331.                        
  332.                         if ( ! $this->vardump_called )
  333.                         {
  334.                                 echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
  335.                         }
  336.        
  337.                         print_r($mixed);       
  338.                         echo "\n\n<b>Last Query:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
  339.                         echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
  340.                         echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
  341.                         echo "</font></pre></font></blockquote>";
  342.                         echo "\n<hr size=1 noshade color=dddddd>";
  343.                        
  344.                         $this->vardump_called = true;
  345.  
  346.                 }
  347.        
  348.                 // Alias for the above function
  349.                 function dumpvars($mixed)
  350.                 {
  351.                         $this->vardump($mixed);
  352.                 }
  353.        
  354.                 // ==================================================================
  355.                 // Displays the last query string that was sent to the database & a
  356.                 // table listing results (if there were any).
  357.                 // (abstracted into a seperate file to save server overhead).
  358.                
  359.                 function debug()
  360.                 {
  361.                        
  362.                         echo "<blockquote>";
  363.        
  364.                         // Only show ezSQL credits once..
  365.                         if ( ! $this->debug_called )
  366.                         {
  367.                                 echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
  368.                         }
  369.                         echo "<font face=arial size=2 color=000099><b>Query --</b> ";
  370.                         echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  371.        
  372.                                 echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  373.                                 echo "<blockquote>";
  374.                                
  375.                         if ( $this->col_info )
  376.                         {
  377.                                
  378.                                 // =====================================================
  379.                                 // Results top rows
  380.                                
  381.                                 echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  382.                                 echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  383.        
  384.        
  385.                                 for ( $i=0; $i < count($this->col_info); $i++ )
  386.                                 {
  387.                                         echo "<td nowrap align=left valign=top><font size=1 color=555599 face=arial>{$this->col_info[$i]->type} {$this->col_info[$i]->max_length}<br><font size=2><b>{$this->col_info[$i]->name}</b></font></td>";
  388.                                 }
  389.        
  390.                                 echo "</tr>";
  391.        
  392.                                 // ======================================================
  393.                                 // print main results
  394.        
  395.                         if ( $this->last_result )
  396.                         {
  397.        
  398.                                 $i=0;
  399.                                 foreach ( $this->get_results(null,ARRAY_N) as $one_row )
  400.                                 {
  401.                                         $i++;
  402.                                         echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  403.        
  404.                                         foreach ( $one_row as $item )
  405.                                         {
  406.                                                 echo "<td nowrap><font face=arial size=2>$item</font></td>";   
  407.                                         }
  408.        
  409.                                         echo "</tr>";                          
  410.                                 }
  411.        
  412.                         } // if last result
  413.                         else
  414.                         {
  415.                                 echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";                      
  416.                         }
  417.        
  418.                         echo "</table>";               
  419.        
  420.                         } // if col_info
  421.                         else
  422.                         {
  423.                                 echo "<font face=arial size=2>No Results</font>";                      
  424.                         }
  425.                        
  426.                         echo "</blockquote></blockquote><hr noshade color=dddddd size=1>";
  427.                        
  428.                        
  429.                         $this->debug_called = true;
  430.                 }
  431.        
  432.        
  433.         }
  434.  
  435. ?>


e si richiama cosi:
$db = new db ( DBUSER, DBPASS, DATABASE, HOSTNAME );

Mi dite come posso aggiungergli $db->Close(); ??

grazie mille.
gigi

Avatar utente
 
Messaggi: 66
Iscritto il: sabato 24 aprile 2010, 12:09
Località: Massa(MS)

Re: chiusura connessione database.

Messaggioda xXDangerous » martedì 21 giugno 2011, 18:22

Salve

Generalmente MySQL chiude le connessione aperte automaticamente al termine di ogni procedura.

Peró preferisco personalmente le maniere piú "formali".

Riguardo il tuo problema, la soluzione é abbastanza semplice.

Devi definire una nuova funzione all'interno della classe che richiami attraverso "$db".
E all'interno della quale, definisci le funzioni che devo essere eseguiti, nel tuo caso: mysql_close().

Esempio:

Sintassi: php [ Scarica ] [ Nascondi ]
  1. class db {
  2.         function Close() {
  3.               return mysql_close($this->dbh);
  4.         }
  5. }
  6.  


Aggiungi questa funzione all'interno della classe, e potrai eseguire $db->Close();

Spero che non ho fatto qualche errore :P

xXDangerous
xXDangerous

Avatar utente
 
Messaggi: 1
Iscritto il: martedì 21 giugno 2011, 18:10


Torna a PHP