[PHP] mySQL-Klasse schreiben
-
Was muss eine gute mySQL-Klasse können? Wie baue ich die überhaupt auf - was kriegt der User zu sehen? Direkt das $row-Array? Welche Formatierungsmöglichkeiten bietet ihr immer?
Also sowas hab ich mir gedacht:
class sql constructor ($host, $user, $pass, $db) function close () // PHP4 kennt ja imho keine Destruktoren?! function query ($sqlcmd) function fetchrow () // Liefert ein Array zurück das den aktuellen Datensatz enthält function fetchcol ($id) // Liefert den Wert des aktuellen Datensatzes mit der ID $id zurück function fetchrowcol ($id) // Ruft nacheinander beide oberen Werte auf
Ist sowas total unbrauchbar? Imho ja
Also wie siehts bei euch aus?
MfG SideWinder
-
Ich hab meine eigene gemacht, ich hab sie aber noch nicht nicht in sourceforge angemeldet, werd ich demnächst tun, hier die Sources.
Ich glaube, es kommt immer darauf an, was du machen willst. Diese Klasse habe ich so angepasst, dass ich damit am besten arbeiten kann. Dabei habe ich die Variable $content so angepasst, als hätte ich die Einträge eines LDAP Servers bekommen. Das finde ich viel bequemer als der ganze Kram mit mysql_fetch_row.
<?php /******************************************************** * The source code is the source code of a free software * * and may be used under the term of the general public * * license (GPL) of the free software fundation. * * * * Author: Pablo Yanez Trujillo * * Filename: admin/class.SqlQuery.php * * Date: 05.06.04 * *********************************************************/ /* File description: SQL Queries for the board */ /** * * SqlQuery connects to a SQL Server and manages the * SQL queries. if you use command such as SELECT, you get * an array with the data in the table. * * * @author Pablo Yanez Trujillo <rex@supertux.homelinux.org> * @copyright (c) 2004 by Pablo Yanez Trujillo * @version 0.0.2 * @package SqlQuery */ class SqlQuery { /** * * The variable saves the SQL query to be executed. * Don't change the variable by yourself * * @var string * @access public * @see setQuery */ var $sql_query; /** * * If mysql_query fails, the errno flags are set * * @var int * @access private * @see mysql_query */ var $errno; /** * * If mysql_query fails, the error flags are set * * @var string * @access public */ var $error; /** * * Contains an array with the result of the SQL query. * If the SQL command doesn't generate an output, then * $content will be an empty array. * * @var array * @access private * @see execute */ var $content; /** * * The connection ID from the connected SQL sevrer. * DON'T CHANGE THIS VARIABLE BY YOURSELF! * * @var mixed * @access private * @see SqlQuery, change_id */ var $connID; /** * * This variable contains the time needed by the excution * of a SQL query. The variable is automaically set by execute, * Yoz may use this variable. * * @var mixed * @access public * @see execute, get_microtime */ var $time; /** * Description of the Variable * @var string * @access private */ var $db; /* End of Variables, functions */ /** * * return the microtime. * * @return mixed float * @access public * @see microtime */ function get_microtime() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } /** * * Contrsuctor of the class. Tries to create a connection to the SQL * sever "$server" with user name "$user" and password "$password". The other * are new_connection and client_flags. For more information about this, * read the mysql_connect from the PHP manual. * * You must choose a database after connecting with the database. The error * number must be 0 if the connection suceess. Use selectDB to choose the database. * * * @access public * @see mysql_connect, closeConnection, selectDB, getError */ function SqlQuery($server="", $user="", $password="", $new_connection="", $client_flags="") { $this->connID = NULL; $this->sql_query = ""; $connID = @mysql_connect($server, $user, $password, $new_connection, $client_flags); if(!$connID) { $this->error = mysql_error(); $this->errno = mysql_errno(); return; } $this->connID = $connID; $this->error=""; $this->errno=0; } /** * * Close the connection of the MySQL Server * * @return void * @access public * @see SqlQuery, mysql_connect */ function closeConnection() { if ($this->connID) @mysql_close($this->connID); } /** * * Set the SQL query with this function. * * * @access public * @see execute, getSqlQuery */ function setSqlQuery($sql) { $this->sql_query = $sql; } /** * * return the actual SQL query * * @return String * @access public * @see setSqlQuery / function getSqlQuery() { return $this->sql_query; } /** * * If you want to use your own connection ID, you can * use this function for this. * * @access public */ function setConnID(&$connID) { $this->connID = &$connID; } /** * * Return the microsecond your SQL needs to be excuted * * @return float * @access public * @see ?? */ function getTime() { return $this->time; } /** * * Returns an array with the error number and the * error string. * array ( * [errno] => error number [error] => error string ) * * @return mixed Description * @access public * @see ?? */ function getError() { return array ( 'errno' => $this->errno, 'error' => $this->error); } /** * * Selects the database for the current connID * * @return bool * @access public * @see SqlQuery */ function selectDB($db) { $this->errno=0; $this->error=""; if (!@mysql_select_db($db, $this->connID)) { $this->errno=mysql_errno($this->connID); $this->error=mysql_error($this->connID); return FALSE; } $this->db = $db; return TRUE; } /** * * This funtionn returns the array with the elemtes fetched * from the MySQL server, when functions like SELECT are used. * * The array conatains two key key with the number of cells * and the number of rows. The third key is an array with * the a the whole table. * * Example: SELECT * FROM users; * * aray ( * 'rows' => 3 * 'cols' => 4 * 'data' => array ( * [0] => id * 'id' => array ( * [0] => 1 * [1] => 2 * [2] => 3 * ) * [1] => nick * 'nick' => array ( * [0] => 'Nick' * [1] => 'Mei' * [2] => 'Yugi' * ) * [2] => passwd * 'passwd' => array ( * [0] => 's3x' * [1] => 'sup3r' * [2] => 'machomen' * ) * [3] => name * 'name' => array ( * [0] => 'Alexander' * [1] => 'Michael' * [2] => 'Daniela' * ) * ) * ) * * When the table is: * * +========================================+ * | id | nick | passwd | name | * |-------+--------+----------+------------+ * |-------+--------+----------+------------+ * | 1 | Nick | s3x | Alexander | * |-------+--------+----------+------------+ * | 2 | Mei | sup3r | Michael | * |-------+--------+----------+------------+ * | 3 | Yugi | machomen | Daniela | * +========================================+ * * When you use function like INSERT then you will get * an empty array. * * @return array * @access public * @see execute */ function getData() { return $this->content; } /** * * This function executes the SQL query and creates the content array. * The only parameter is optional. If $num is set the array won't be craeted, * only the number of rows ans cells will be written in the array. * * If the SQL query succes you will get TRUE, FALSE otherwise * * @return bool * @access public * @see setSqlQuery, getData, mysql_query */ function execute($num=0) { if ($this->sql_query=="") return FALSE; $this->content = array(); $this->error = ""; $this->errno = 0; $t1 = $this->get_microtime(); $result = @mysql_query($this->sql_query, $this->connID); $t2 = $this->get_microtime(); $this->time = (float) ((float) $t2 - (float) $t1); if (!$result) { $this->errno = mysql_errno($this->connID); $this->error = mysql_error($this->connID); return FALSE; } elseif ($result===TRUE) return TRUE; else { $rows = mysql_num_rows($result); $cols = mysql_num_fields($result); $this->content['rows'] = $rows; $this->content['cols'] = $cols; if ($num) return TRUE; /* create columns */ $this->content['data'] = array(); for($i=0; $i<$cols; ++$i) { $fn = mysql_field_name($result, $i); $this->content['data'][$fn] = array(); $this->content['data'][$i] = $fn; } /* create rows */ for($i=0; $i<$rows; ++$i) { $row = mysql_fetch_row($result); for($j=0; $j<$cols; ++$j) { $this->content['data'][$this->content['data'][$j]][$i] = $row[$j]; } } return TRUE; } } /** * * @return mixed Description * @access private * @see ?? */ function createArray($result) { $rows = mysql_num_rows($result); $arr = array('count' => $rows); for($i=0; $i<$rows; ++$i) { $a = mysql_fetch_row($result); $arr[$i] = $a[0]; } return $arr; } /** * * returns an arry like that from getData with all databases * * @return array * @access public * @see getData */ function getDataBases() { $result = mysql_list_dbs($this->connID); return $this->createArray($result); } /** * * returns an arry like that from getData with all tables of * the database * * @return array * @access public * @see getData */ function getTables($db="") { if ($db=="") $db = $this->db; $result = mysql_list_tables($db, $this->connID); return $this->createArray($result); } } ?>
Und so sieht es eine Anwendung von meiner Klasse:
<?php /* Beispielanwendung der Klasse SqlQuery */ include_once("class.SqlQuery.php"); //header("Content-type: text/plain"); //print_r($_SERVER); $host = "localhost"; $uname = "root"; $passwort="************"; /* das muss man richtig setzen */ $sql = new SqlQuery($host, $uname, $passwort); $err = $sql->getError(); if ($err['errno']) { $err_txt = "Exting with error $err[errno]: <i>$err[error]</i>"; die($err_txt); } echo '<?xml version="1.0" encoding="iso-8859-1"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' . "\n"; ?> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Beispiel für die Klasse SqlQuery</title> <meta name="author" content="Pablo Yanez Trujillo" /> <meta name="Audience" content="Alle" /> <meta name="Expires" content="0" /> <meta http-equiv="Expires" content="0" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="pragma" content="no-cache" /> <meta name="Robots" content="INDEX,FOLLOW" /> <meta name="Revisit-After" content="5 days" /> <style type="text/css"> a:link, a:visited { color: #006BB6; text-decoration: none; } a:active { color: #B9D9F0; text-decoration: underline; } a:hover { color: #006BB6; text-decoration: underline; } </style> </head> <body text="#0000AA" bgcolor="#E7F5FE"> <p>Hallo, dieses Skript ist ein Beispiel für die Benutzung der Klasse <b>SqlQuery</b>. Diese Klasse vereinfacht den Umgang mit einer Datebank eines <a href="http://dev.mysql.com" target="_blank" title="MySQL Homepage">MySQL</a> Serves.</p> <div align="left"> <ul> <li><a href="<?php echo $_SERVER['PHP_SELF']; ?>?showdatabases=1">Alle Datenbanken anzeigen</a></li> <li>Alle Tabellen sehen vom: <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <?php $data = $sql->getDataBases(); if(!$data['count']) echo "\t<b>Sie koönnen keine Datenbak sehen</b>"; else { echo "\t<select name=\"formDBs\">\n"; for($i=0; $i<$data['count']; ++$i) { echo "\t<option value=\"$data[$i]\">" . htmlentities($data[$i]) ."</option>\n"; } echo "\t</select>\n"; echo "\t<input type=\"submit\" name=\"formSelDBSubmit\" />\n"; } ?> </form></li> </ul> </div> <?php /* ok, jetzt sehen wir, was wir denn so alles ausgeben müssen */ $color = array(0 => 'a0cae4', 1 => '6dbaea'); if (isset($_GET['showdatabases']) and $_GET['showdatabases']) { /* Datenbanken brauchen wir nicht mehr zu lesen, sie sind bereits in data */ if(!$data['count']) echo "Sie können keine Datenbank sehen"; else { echo "<center>\n"; echo "<table border=\"0\">\n"; echo "<tr style=\"background: #aacae4\">\n <th>Datenbanken</th>\n</tr>\n"; for($i=0; $i<$data['count']; ++$i) { echo "<tr style=\"background: #" . $color[$i % 2] . "\">\n"; echo " <td>" . htmlentities($data[$i]) . "</td>\n</tr>\n"; } echo "</table>\n"; echo "</center>\n"; } } elseif (isset($_POST['formSelDBSubmit'])) { /* submit Knopf */ $db_name = $_POST['formDBs']; $data = $sql->getTables($db_name); if (!$data['count']) echo "Die Datenbank <i>$db_name</i> ist leer."; else { echo "Die Tabellen von <b>$db_name</b><p />\n"; echo "<center>\n"; echo "<table border=\"0\">\n"; echo "<tr style=\"background: #aacae4\">\n <th>Tabellen</th>\n</tr>\n"; for($i=0; $i<$data['count']; ++$i) { echo "<tr style=\"background: #" . $color[$i % 2] . "\">\n"; echo " <td>"; echo "<a href=\"$_SERVER[PHP_SELF]?db_name=$db_name&table=$data[$i]\">"; echo htmlentities($data[$i]) . "</a></td>\n</tr>\n"; } echo "</table>\n"; echo "</center>\n"; echo "<b>Um den ganzen Inhalt einer Tabelle sehen zu können, müssen Sie auf den Namen einer Tabelle klicken</b>\n"; } } elseif (isset($_GET['db_name']) and isset($_GET['table'])) { $db_name = $_GET['db_name']; $table = $_GET['table']; if (!$sql->selectDB($db_name)) { $err = $sql->getError(); $err_txt = "Exting with error $err[errno]: <i>$err[error]</i>"; die($err_txt); } $sql->setSqlQuery("SELECT * FROM $table"); if(!$sql->execute()) { $err = $sql->getError(); $err_txt = "Exting with error $err[errno]: <i>$err[error]</i>"; die($err_txt); } $data = $sql->getData(); echo "Inhalt der Tabelle <b>$table</b> der Datenbank <b>$db_name</b><p />\n"; if(!$data['rows']) echo "Die Tabelle ist leer"; else { echo "<center>\n"; echo "<table border=\"0\">\n"; /* Erzeugung der Titel-Reihe */ echo "<tr style=\"background: #aacae4\">\n"; for($i=0; $i<$data['cols']; ++$i) echo " <th>" . htmlentities($data['data'][$i]) . "</th>\n"; echo "</tr>\n"; for($j=0; $j<$data['rows']; ++$j) { echo "<tr style=\"background: #" . $color[$j % 2] . "\">\n"; for($i=0; $i<$data['cols']; ++$i) { $cell_name = $data['data'][$i]; $cell_cont = trim($data['data'][$cell_name][$j]); if ($cell_cont=="") $cell_cont = " "; else $cell_cont = htmlentities($cell_cont); echo " <td>$cell_cont</td>\n"; } echo "</tr>\n"; } echo "</table>\n"; echo "</center>"; } } ?> <p> <a href="<?php echo $_SERVER['PHP_SELF']; ?>">Zurück zum Anfang</a> </p> <p> <a href="http://validator.w3.org/check?uri=referer" target="_blank"> <img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0!" height="31" width="88" /></a> <a href="http://jigsaw.w3.org/css-validator/check/referer" target="_blank"> <img style="border:0;width:88px;height:31px" src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!" /> </a> </p> </body> </html>
-
hi
meine hat noch eine persistent/nicht persistent abfrage mit drin
//konstruktor function mysql_db($server,$user,$pwd,$database,$debug=0,$persistent="n") { $this->debug_flag=$debug; $this->database=$database; if ($persistent=="n"){ $this->conn = mysql_connect ($server,$user, $pwd); } else { $this->conn = mysql_pconnect ($server,$user, $pwd); } .... ...
nur als idee..
desweiteren möchte ich sie umarbeiten für php5, und das close in den destruktor hauen.
es gibt ebenso fetch_rows.., send_sql... und solche sachen, eine easy tabelle zum testen (die umstritten ist, und vielleicht wieder rauskommt), und einen error_out für die errorausgaben mit zeit und allem wichtigen drum und dran.
die klasse ist klein und übersichtlich.
darüber hinaus ist ein debug eingebaut, daß über konstruktor auf on oder off eingestellt werden kann.na ja, reicht, und hat sich bewährt.
-
Diese Klasse verwende ich um auf MySql zu zugreifen: ezSQL
-
Schon mal die von phpBB angesehen.
-
Unix-Tom schrieb:
Schon mal die von phpBB angesehen.
nein. Warum? Ist sie besonders gut? (das nehme ich an)
-
Unix-Tom schrieb:
Schon mal die von phpBB angesehen.
Ja auch die von phpNuke bereits angesehen. Haut mich beides nicht vom Stuhl - viel zu viel Overhead für mich.
MfG SideWinder
-
zustimm
ich kenne mich bei php in meinen klassen lieber gut aus... schreibe solche kleinen dinge wie eine mysql db klasse also selber.
klar, wenn ich in ein bestehendes projekt komme, passe ich mich an, aber bei kleinen aufträgen, sprich: ich programmiere alleine, hat sich das bewährt.
-
Kann ich nur zustimmen. Baue mir solch simple Sachen grundsätzlich selber, bzw. passe meine eigenen Klassen schnell an.
-
SideWinder schrieb:
Unix-Tom schrieb:
Schon mal die von phpBB angesehen.
Ja auch die von phpNuke bereits angesehen. Haut mich beides nicht vom Stuhl - viel zu viel Overhead für mich.
MfG SideWinder
Ich frage ich wo du bei der Klasse vom phpBB Overhead siehst.