Jump to content

kickassamd

Members
  • Posts

    102
  • Joined

  • Last visited

    Never

Everything posted by kickassamd

  1. Its been a bit since I have done anything like that with *nix but in Windows in order to create folders within folders you have to have write permissions on that folder in order for PHP to be able to create the folders. Have you checked this? CHMOD 777
  2. Post the errors.
  3. i recommend that you use addslashes() or mysql_real_escape_string().
  4. There is actually an error in my code... $this->mysqli = $mysqli; needs to be $this->_mysqli = $mysqli; $result = $this->mysqli->query($query); needs to be $result = $this->_mysqli->query($query);
  5. Works in IE Maxthon Opera and Prints of here in Firefox...
  6. 1 your synax is incorrect should be date("m/d/Y") read the PHP manual for the date function. http://us3.php.net/date
  7. You need to assign $mysqli to a class variable. var $_mysqli; and assign $mysqli to that when you connect... $mysql = new mysqli(); $this->mysqli = $mysql; then in your function use $this->mysqli->query(); etc etc; I believe in the other functions you can also just do global $mysqli; You should learn the newer and PHP5 way of classes using Private, Protection public etc etc. <?php class OpenRead { var $name; private $_mysqli; function OpenDB($localhost,$username,$password,$database) { $mysqli = new mysqli($localhost, $username, $password, $database); $this->mysqli = $mysqli; } function GetName() { $query = "select * from test where id='1'"; $result = $this->mysqli->query($query); $row = $result->fetch_assoc(); $this->name = $row["name"]; } } ?>
  8. I use PHPmailer for all my projects that need mailing capabilites. http://sourceforge.net/project/showfiles.php?group_id=26031
  9. Ah, this isnt too bad...
  10. Looking for a online preferabbly free way to document my classes and functions for a CMS I am working on. I have downloaded and used the wiki junk and do not like it so if anyone has any other options please let me know
  11. Yes I am seen a number of hosts who do not have the PDO extensions enabled, this class was ORIGINALLY built when PHP 5 was very beta, i just adapted it to run with 5, next one will use mysqli extensions.
  12. lol. Sure Also all my functions do work together to achieve the same goal, the purpose of this class was to aid in debugging mySQL queries, errors and other items. Also in OOP you are not supposed to allow direct access to your variables hense why I use functions to set them. You do not find it usefull that is fine, many others do.
  13. Just seeing what everyone thinks of my updated mySQL class. Post suggestions, thoughts etc etc about it <? /******************************************************************************* * MySQL Database Class ******************************************************************************* * Author: Chris York (KickassAMD) * Email: [email protected] * Website: http://www.kickassamd.com * * File: mysqldb.class.php * Version: v1.1.2 * Copyright: (c) 2006 - Chris York * You are free to use, distribute, and modify this software * under the terms of the GNU General Public License. * ******************************************************************************* * VERSION HISTORY: * * v1.0.0 [06.08.2006] - Initial Version. * * v1.0.2 [10.02.2006] - Rewrote Class Completely. * - Updated Functions. * - New debugging system in place aswell. * - PHP 5 Will be required for usage of this class. * * v1.0.3 [10.08.2006] - Small Changes To getLoggedQueries() function. * - Added new function execCreateDatabase(). * - Added new function execDropDatabase(). * - Added new function optimizeTable(). * * v1.0.4 [10.09.2006] - Added new function execQueryFromFile(). * * v1.0.5 [01.15.2007] - Removed class constructer. New functions to set * SQL connection information via set(). * * v1.0.6 [02.06.2007] - Removed strtolower() from all query functions * as it caused issues with case sensitive information. * - Added email function to mail a error report on SQL * errors. * * v1.0.7 [03.14.2007] - Added new function getNumFields() * - Added new function getDatabaseList() * - Added new function getTableList() * - Added new function getFieldName() * - Added new function getFieldType() * - Added new function getFieldLength() * - Added new function getFieldFlag() * * v1.0.8 [04.15.2007] - Small change within execSafeQuery() * * v1.0.9 [09.14.2007] - execQueryFromFile() Now adds table prefixes to table names. * - Small changes to execQuery() & execSafeQuery() * * * v1.1.0 [09.15.2007] - execQueryFromFile() Now removes comments from file based queries * * v1.1.1 [09.16.2007] - Improvements to addPrefixToFile() and stripComments(). * - Removed eMail error reporting functionality. * - Changes to getLoggedErrors() & getLoggedQueries(). * * v1.1.2 [10.10.2007] - Added new function execFormatedQuery() * - Added new function formatTimeStamp() * - Added new function formatDateTime() * - Added new function execQuery2XML() * - Added new function getObject() * ******************************************************************************* * DESCRIPTION: * * This class aids in MySQL database connectivity. It was written with * my specific needs in mind. It simplifies the database tasks I most * often need to do thus reducing redundant code. It is also written * with the mindset to provide easy means of debugging erronous sql and * data during the development phase of a web application. * * The future may call for adding a slew of other features, however, at * this point in time it just has what I often need. I'm not trying to * re-write phpMyAdmin or anything. Hope you find it useful. * ******************************************************************************* */ /** * @author Chris York (KickassAMD) * @link http://www.kickassamd.com * @version v1.1.2 * @name MySQL Server Database Class * @package Core Functions For SQL Usage */ class mysqlDatabase { /** * Class Constructor */ public function __construct() { } /** * Class Destructer */ public function __destruct() { $this->terminateConn(); } /////////////////////////////////////////////////////////////////////////// ///////////////////// Below is MySQL Configuration Values ///////////////// ///////////////////// These values cannot be set directly ///////////////// //////////////// And must be set using the set() fuctions ///////////////// /////////////////////////////// v1.0.6 //////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * SQL Server Database Username * @var String */ private $_dbUsername; /** * SQL Server Database Password * @var String */ private $_dbPassword; /** * SQL Server Hostname \ IP Address * @var String */ private $_dbServerHost; /** * SQL Server Database Name * @var String */ private $_dbSelectName; /** * SQL Server Database Table Prefix (If Any) * @var String */ private $_dbTblPrefix; /** * Maintain Persistant Connection To SQL Server * @var boolean */ private $_dbUsePersistantConn; /** * SQL Server Connection Resource * @var Resource */ private $_dbResource; /** * SQL Server Query Logger * @var Array() */ private $_dbQueryLogger = array(); /** * SQL Server Error Logger * @var Array() */ private $_dbErrorLogger = array(); /////////////////////////////////////////////////////////////////////////// ////////////////// Below is MySQL Configuration Functions ///////////////// /////////////////////////////// v1.0.6 //////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * Set Database Username * * @param string $Username */ public function setUsername($Username) { $this->_dbUsername = $Username; } /** * Set Database Password * * @param string $Password */ public function setPassword($Password) { $this->_dbPassword = $Password; } /** * Set Database IP \ HostName * * @param string $Host */ public function setServerDSN($Host) { $this->_dbServerHost = $Host; } /** * Set Database For Use * * @param string $DbName */ public function setDatabase($DbName) { $this->_dbSelectName = $DbName; } /** * Use persistant connection to database * * @param boolean $Persistant */ public function setPersistant($Persistant = false) { $this->_dbUsePersistantConn = $Persistant; } /** * Sets Table Prefix * * @param String $tablePrefix (Name Of Prefix) * @param String $prefixSeperator (Symbol That Separates Prefix From Table _ Is Default) */ public function setTblPrefix($tablePrefix, $prefixSeperator = "_") { $this->_dbTblPrefix = $tablePrefix.$prefixSeperator; } /////////////////////////////////////////////////////////////////////////// ///////////////////// Below is Functions Needed For MySQL ///////////////// /////////////////////////////// v1.0.6 //////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * Connect To SQL Server And Select Database * * @param boolean $selectDb Select Database For Use? True | False * @return boolean */ public function getConnected($selectDb = true) { if ($this->_dbUsePersistantConn) { $this->_dbResource = @mysql_pconnect($this->_dbServerHost, $this->_dbUsername, $this->_dbPassword); } else { $this->_dbResource = @mysql_connect($this->_dbServerHost, $this->_dbUsername, $this->_dbPassword); } if ($this->_dbResource) { if ($selectDb) { if (@mysql_select_db($this->_dbSelectName)) { return true; } else { $this->logError($this->getError(), $this->getErrorNum()); return false; } } else { $this->logError("Connected To Server, No Database Selected","????"); return false; } } else { $this->logError($this->getError(),$this->getErrorNum()); return false; } } /** * Create Database On SQL Server * If $dbName is not defined, Function will use one defined in class constructor. * * @param String $dbName * @return boolean */ public function execCreateDatabase($dbName) { if ($this->_dbResource) { if ($dbName != '') { $sql = "create database `$dbName`"; } else { $sql = "create database `".$this->_dbSelectName."`"; } $this->execQuery($sql); } else { $this->logQuery($sql, "No Connection To Server", "x123"); return false; } } /** * Drop Database On SQL Server * If $dbName is not defined, Function will use one defined in class constructor * * @param String $dbName * @return boolean */ public function execDropDatabase($dbName) { if ($this->_dbResource) { if ($dbName != '') { $sql = "drop database `$dbName`"; } else { $sql = "drop database `".$this->_dbSelectName."`"; } $this->execQuery($sql); } else { $this->logQuery($sql, "No Connection To Server", "x123"); return false; } } /** * Execute SQL Query On Database * * @param String $sql * @param Boolean $execQuery (Execute Query = True) * @param Boolean $printSQL (Echo SQL To Screen = True) * @return Boolean */ public function execQuery($sql, $execQuery = true, $printSQL = false) { if ($this->_dbResource) { $sql = trim($sql); if ($execQuery) { if ($result = @mysql_query($sql, $this->_dbResource)) { $this->logQuery($sql, $this->getError(), $this->getErrorNum()); return $result; } else { $this->logQuery($sql, $this->getError(), $this->getErrorNum()); return false; } } else { $this->logQuery($sql, "Query Not Executed!", "x124"); return false; } if ($printSQL) { echo $sql."<br />"; } } else { $this->logQuery($sql, "No Connection To Server", "x123"); return false; } } /** * Only Allow 'SELECT' SQL Statements To Be Executed On Database * * @param String $sql * @param Boolean $execQuery (Execute Query = True) * @param Boolean $printSQL (Echo SQL To Screen = True) * @return Boolean */ public function execSafeQuery($sql, $execQuery = true, $printSQL = false) { if ($this->_dbResource) { $sql = trim($sql); if (substr(strtolower($sql), 0, 6) == 'select') { return $this->execQuery($sql, $execQuery, $printSQL); } else { $this->logQuery($sql, "Tried Executing An Unsafe Query!", "x127"); return false; } } else { $this->logQuery($sql, "No Connection To Server", "x123"); return false; } } /** * Splits A Large SQL File Into Smaller Queries And Executes Them * * @param string $file (Path to SQL file to execute from) * @param boolean $execQuery */ public function execQueryFromFile($file, $execQuery = true) { if ($fp = @fopen($file, "r")) { $fr = trim(fread($fp, filesize($file))); // Remove Comments $preg = $this->stripComments($fr); $sql_queries = explode(";", $preg); foreach ($sql_queries as $query) { if ($query != "") { $query = trim($query); // Add Prefix To Table $query = $this->addPrefixToFile($query); $this->execQuery($query, $execQuery); } } } else { $this->logError("File <i>$file</i> was not found check file path and try again", "x126"); } } /** * Format Query For Safe Execution On Database Server * This WILL execute query on server * * @param String $query * @param Boolean $execute * @return Boolean || String */ public function execFormatedQuery($query) { $args = func_get_args(); $query = array_shift($args); $query = str_replace("?", "%s", $query); $args = array_map('mysql_real_escape_string', $args); array_unshift($args,$query); $query = call_user_func_array('sprintf',$args); return $this->execQuery($query); } /** * Add Table Prefix To The Beginning Of A Table * * @param String $tableName * @return String */ public function addTblPrefix($tableName = '') { if ($tableName != '') { return $this->_dbTblPrefix.$tableName; } else { return $this->_dbTblPrefix; } } /** * Add Table Prefix To Existing File Based Query * Can only handle CREATE | INSERT | DROP | ALTER statements. * * @param String $string * @return String */ private function addPrefixToFile($string) { if (stristr($string, "CREATE TABLE")) { $result = preg_replace('/CREATE\\sTABLE\\s`(\\b.*\\b)`/', 'CREATE TABLE `'.$this->_dbTblPrefix.'\\1`', $string); } elseif (stristr($string, "INSERT INTO")) { $result = preg_replace('/INSERT\\sINTO\\s`(\\b.*\\b)`/', 'INSERT INTO `'.$this->_dbTblPrefix.'\\1`', $string); } elseif (stristr($string, "DROP TABLE")) { $result = preg_replace('/DROP\\sTABLE\\s`(\\b.*\\b)`/', 'DROP TABLE `'.$this->_dbTblPrefix.'\\1`', $string); } elseif (stristr($string, "DROP TABLE IF EXISTS")) { $result = preg_replace('/DROP\\sTABLE\\sIF\\sEXISTS\\s`(\\b.*\\b)`/', 'DROP TABLE IF EXISTS `'.$this->_dbTblPrefix.'\\1`', $string); } elseif (stristr($string, "ALTER TABLE")) { $result = preg_replace('/ALTER\\sTABLE\\s`(\\b.*\\b)`/', 'ALTER TABLE `'.$this->_dbTblPrefix.'\\1`', $string); } elseif (stristr($string, "DROP VIEW IF EXISTS")) { $result = preg_replace('/DROP\\sVIEW\\sIF\\sEXISTS\\s`(\\b.*\\b)`/', 'DROP VIEW IF EXISTS `'.$this->_dbTblPrefix.'\\1`', $string); } elseif (stristr($string, "DROP VIEW")) { $result = preg_replace('/DROP\\sVIEW\\s`(\\b.*\\b)`/', 'DROP VIEW `'.$this->_dbTblPrefix.'\\1`', $string); } elseif (stristr($string, "CREATE VIEW")) { $result = preg_replace('/`\b(\w+)\b`/', '`'.$this->_dbTblPrefix.'\\1`', $string); } else { $result = $string; } return $result; } /** * Removes All Comments From File Based Query * NOTE: Does not actually remove comments from file * It only removed comments from the string being based to it. * * @param String $string * @return String */ private function stripComments($string) { $result = preg_replace('%(?>(?>--|#).*|\/\*.*?\*\/)%', '', $string); return $result; } /** * Optimize Tables On SQL Server * * @param String $tableName Can be an array to optimize multiple tables at once * @return boolean */ public function optimizeTable($tableName) { if ($this->_dbResource) { if (is_array($tableName)) { foreach ($tableName as $optimize) { $sql = "optimize table `$optimize`"; $this->execQuery($sql); } } else { $sql = "optimize table `$tableName`"; $this->execQuery($sql); } } else { $this->logQuery($sql, "No Connection To Server", "x123"); return false; } } /** * Clean Database String * * @param Stromg $string * @return String */ public function cleanString($string) { return @mysql_real_escape_string($string, $this->_dbResource); } /** * Execute A Query Then Output Results To XML Document * * @param String $query */ public function execQuery2XMLOutput($query) { $result = $this->execSafeQuery($query); $xml = '<?xml version="1.0" encoding="ISO-8859-1"?>'; $xml .= '<output>'; // Loop Over Rows while ($row = $this->getObject($result)) { $xml .= "<data>"; // Loop Over Columns for ($i = 0; $i < $this->getNumFields($result); $i++) { $fieldName = $this->getFieldName($result, $i); $xml .= "<$fieldName>"; if (!empty($row->$fieldName)) { $xml .= "{$row->$fieldName}"; } $xml .= "</$fieldName>"; } $xml .= "</data>"; } $xml .= "</output>"; if (!headers_sent()) { header("Content-Type: application/xml"); } echo $xml; } /** * Returns ID Given From 'Insert' Queries * * @return Integer */ public function getInsertId() { return @mysql_insert_id($this->_dbResource); } /** * Return Number Of Rows Returned From 'select' Query * * @param Resource $result (MySQL Query Result) * @return Integer */ public function getNumRows($result) { return @mysql_num_rows($result); } /** * Return Number Of Fields In Table * * @param Resource $result * @return integer */ public function getNumFields($result) { return @mysql_num_fields($result); } /** * Retuned Number Of Affected Rows From 'insert' or 'update' Query * * @return Integer */ public function getAffectedRows() { return @mysql_affected_rows($this->_dbResource); } /** * Get a result row as an enumerated array * * @param Resource $result (MySQL Query Result) * @return String (Array) */ public function getRow($result) { $returnArray = array(); while ($dbArray = @mysql_fetch_row($result)) { $returnArray[] = $dbArray; } return $returnArray; } /** * Fetch a result row as an associative array * * @param Resource $result (MySQL Query Result) * @return String (Array) */ public function getArray($result) { $returnArray = array(); while ($dbArray = @mysql_fetch_assoc($result)) { $returnArray[] = $dbArray; } return $returnArray; } /** * Fetch a result in enumerated & associative array * * @param Resource $result (MySQL Query Result) * @return String (Array) */ public function getBoth($result) { $returnArray = array(); while ($dbArray = @mysql_fetch_array($result, MYSQL_BOTH)) { $returnArray[] = $dbArray; } return $returnArray; } /** * Get a list of all databases available to this user * * @return String (array) */ public function getDatabaseList() { $databases = @mysql_list_dbs($this->_dbResource); $returnArray = array(); while ($row = mysql_fetch_object($databases)) { $returnArray[] = $row->Database; } } /** * Get a list of all tables in a specified database * If database isnt defined, script will use one defined in class. * * @param String $database * @return string (array) */ public function getTableList($database = "") { // Use Function defined database... Or class defined if ($database != "") { $listTable = @mysql_list_tables($database, $this->_dbResource); } else { $listTable = @mysql_list_tables($this->_dbSelectName, $this->_dbResource); } // Get array list of tables $oddArray = $this->getRow($listTable); $returnArray = array(); // For() loop to make array nicer for ($i = 0; $i < sizeof($oddArray); $i++) { $returnArray[] = $oddArray[$i][0]; } return $returnArray; } /** * Get a list of all fields (columns) in a specified table. * * @param resource $result * @param Int $i * @return String (array) */ public function getFieldName($result, $i) { return @mysql_field_name($result, $i); } /** * Return field (column) type in a specified table * * @param resource $result * @param Int $i * @return String (array) */ public function getFieldType($result, $i) { return @mysql_field_type($result, $i); } /** * Return field (column) length * * @param resource $result * @param Int $i * @return integer (array) */ public function getFieldLength($result, $i) { return @mysql_field_len($result, $i); } /** * Returns field (column) flags * ie.. primary key, auto_increment etc etc. * * @param resource $result * @param Int $i * @return string (array) */ public function getFieldFlag($result, $i) { return @mysql_field_flags($result, $i); } /** * Get MySQL Object * * @param Resource $result * @return Object */ public function getObject($result) { return @mysql_fetch_object($result); } /** * Format TIMESTAMP Column Datatype To Human Format * * @param TimeStamp $timestamp * @param String $format * @return String */ public function formatTimeStamp($timestamp, $format = "F j, Y, g:i a") { $year = strval(substr($timestamp, 0, 4)); $month = strval(substr($timestamp, 4, 2)); $day = strval(substr($timestamp, 6, 2)); $hour = strval(substr($timestamp, 8, 2)); $minute = strval(substr($timestamp, 10, 2)); return date($format, mktime($hour, $minute, 0, $month, $day, $year)); } /** * Format DATETIME Column Datatype to Human Format * * @param DateTime $dateTime * @param String $format * @return String */ public function formatDateTime($dateTime, $format = "F j, Y, g:i a") { $year = strval(substr($dateTime, 0, 4)); $month = strval(substr($dateTime, 5, 2)); $day = strval(substr($dateTime, 8, 2)); $hour = strval(substr($dateTime, 11, 2)); $minute = strval(substr($dateTime, 14, 2)); return date($format, mktime($hour, $minute, 0, $month, $day, $year)); } /** * Get Number Of Queries Executed * * @return Int */ public function getQueryCount() { return count($this->_dbQueryLogger); } /** * Return MySQL Error String * * @return String */ private function getError() { return @mysql_error(); } /** * Return MySQL Error Number * * @return Integer */ private function getErrorNum() { return @mysql_errno(); } /** * Add A Query To Logger System * * @param string $sql * @param string $error * @param integer $errno */ private function logQuery($sql, $error = null, $errno = null) { $this->_dbQueryLogger[] = array("sql" => $sql, "error" => $error, "errno" => $errno); } /** * Add Error To Logger System * * @param string $message */ private function logError($error = null, $errno = null) { $this->_dbErrorLogger[] = array("error" => $error, "errno" => $errno); } /** * Return All Logged Queries In HTML Format * * @return String */ public function getLoggedQueries() { $return = '<table width="100%" cellspacing="1"><tr><th>Queries Logged</th></tr>'; foreach ($this->_dbQueryLogger as $query) { if ($query['error'] != null) { $return .= '<tr><td><span style="color:#ff0000;">'.htmlspecialchars($query['sql']).'<br /><b>Error number: </b>'.htmlspecialchars($query['errno']).'<br /><b>Error message: </b>'.htmlspecialchars($query['error']).'</span></td></tr>'; $return .= '<tr><td><hr color="#CCCCCC" /></td></tr>'; } else { $return .= '<tr><td><span style="color:#009933;">'.htmlspecialchars($query['sql']).'</span></td></tr>'; $return .= '<tr><td><hr color="#CCCCCC" /></td></tr>'; } } $return .= '<tr><td>Total Queries: <span style="color:#009933;">'.count($this->_dbQueryLogger).'</span></td></tr>'; $return .= '</table>'; echo $return; } /** * Return All Logged Errors In HTML Format * * @return String */ public function getLoggedErrors() { $return = '<table width="100%" cellspacing="1"><tr><th>Errors Logged</th></tr>'; foreach ($this->_dbErrorLogger as $error) { $return .= '<tr><td><span style="color:#ff0000;"><br /><b>Error number: </b>'.htmlspecialchars($error['errno']).'<br /><b>Error message: </b>'.htmlspecialchars($error['error']).'</span></td></tr>'; $return .= '<tr><td><hr color="#CCCCCC" /></td></tr>'; } $return .= '<tr><td>Total Errors: <span style="color:#009933;">'.count($this->_dbErrorLogger).'</span></td></tr>'; $return .= '</table>'; echo $return; } /** * Terminate Connection To SQL Server * */ public function terminateConn() { @mysql_close($this->_dbResource); $this->logError("Connection To The Server Was Terminated By The User", "x125"); } } ?>
  14. I take it you have never used Smarty? No you dont have to use parentheses.
  15. I have an array that looks like this Array ( [0] => Array ( [name] => Account [submenu] => Array ( [0] => Array ( [name] => Create Account [link] => ) [1] => Array ( [name] => Manage Account [link] => ) [2] => Array ( [name] => Cancel Account [link] => ) ) ) ) And im trying to use it in smarty like so <{foreach from=$ACMS_MENU item=menu}> <div class="sidebox"> <h1 class="clear"><{$menu.name}></h1> <ul class="sidemenu"> <{foreach from=$ACMS_MENU.submenu item=subitem}> <li><a href="<{$ACMS_URL}><{$subitem.link}>" class="top"><{$subitem.name}></a></li> <{/foreach}> </ul> </div> <{/foreach}> So far no luck... Any ideas? The first foreach loop works, the second that prints the subitems does not.
  16. replace your line 13 with while(($row = mysql_fetch_array($rs, MYSQL_ASSOC)) != false)
  17. Not 100% sure on your real question but avoid using long variables like HTTP_POST_VARS etc etc use, $_POST. $_GET etc etc.
  18. No i just want to view files...
  19. Was wondering if anyone has already built something that can list all files and directories \ sub directories.. I can list files and directories, But im wanting to do it with a twist... DIRA --filename.txt --filenameb.txt DIRb --something.jpg --subDIR ----filename.txt I would like to list them in some sort of tree view instead of listing the flat out... Any ideas? Or pre-written scripts?
  20. Ive fixed it, there is a f-cgi setting in an config files that you can set how many processes you want launched... I just changed from 10 to 2. No it wasnt IIS at all, just a setting in Zend Core I overlooked! Thanks!
  21. Ive installed Zend Core 2 on my IIS v5.5... Very very cool might I add love this software... Till i noticed 10 php-cgi.exe's runnng using 10MB a piece... If i manually end one, it just starts right back up... Does anyone know how to limt to number of these that start once a PHP process is called?
  22. People around here would give you more help if you actually tried on your own, No one is just going to do all the work for you.... Try and if you cant get it, ask questions then. A better place to start is maybe with Word Press forums then selves, most CMS engines have a WIKI that gives all the information about variables, classes, and functions and how they work and what they are used for.
  23. no one else?
  24. Thank you very much for taking the time to comment! -- Yeah next one will have a diffrent naming scheme -- I see what you mean about the HTML... this was developed for my personal use at first but now im hopping to allow mass use of it. So im going to remove the HTML stuff -- Yeah documentation is also very important to me as sometimes i get lost in my own code...
  25. I built this over a period of time just looking to see what the "experts" have to say about it... Im thinking of redoing it because my knowledge of PHP and PHP5 has changed... All coments good, bad, horrible welcome! <?php /******************************************************************************* * MySQL Database Class ******************************************************************************* * Author: Chris York (KickassAMD) * Email: [email protected] * Website: http://www.kickassamd.com * * File: mysqldb.class.php * Version: v1.0.7 * Copyright: (c) 2006 - Chris York * You are free to use, distribute, and modify this software * under the terms of the GNU General Public License. * ******************************************************************************* * VERSION HISTORY: * * v1.0.0 [06.08.2006] - Initial Version. * v1.0.2 [10.02.2006] - Rewrote Class Completely. * - Updated Functions. * - New debugging system in place aswell. * - PHP 5 Will be required for usage of this class. * v1.0.3 [10.08.2006] - Small Changes To getLoggedQueries() function. * - Added new function execCreateDatabase(). * - Added new function execDropDatabase(). * - Added new function optimizeTable(). * v1.0.4 [10.09.2006] - Added new function execQueryFromFile(). * * v1.0.5 [1.15.2007] - Removed class constructer. New functions to set * SQL connection information via set(). * * v1.0.6 [2.6.2007] - Removed strtolower() from all query functions * as it caused issues with case sensitive information. * - Added email function to mail a error report on SQL * errors. * * v1.0.7 [3.14.2007] - Added * ******************************************************************************* * DESCRIPTION: * * This class aids in MySQL database connectivity. It was written with * my specific needs in mind. It simplifies the database tasks I most * often need to do thus reducing redundant code. It is also written * with the mindset to provide easy means of debugging erronous sql and * data during the development phase of a web application. * * The future may call for adding a slew of other features, however, at * this point in time it just has what I often need. I'm not trying to * re-write phpMyAdmin or anything. Hope you find it useful. * ******************************************************************************* * MISC NOTES: * * The function execQueryFromFile() currently does not add table prefixes * to table names, I am hopping to fix that in a later version. * * The email system uses the built in PHP mail function to send the logs. * Newer version will support sendmail or an equivalent. * You can enable it via setEmailAlerts() to true. And set() functions for * email address and subject name. ******************************************************************************* */ /** * @author Chris York (KickassAMD) * @link http://www.kickassamd.com * @version v1.0.7 * @name MySQL Server Database Class * @package Core Functions For SQL Usage */ class sqldatabase_factory { /////////////////////////////////////////////////////////////////////////// ///////////////////// Below is MySQL Configuration Values ///////////////// ///////////////////// These values cannot be set directly ///////////////// //////////////// And must be set using the set() fuctions ///////////////// /////////////////////////////// v1.0.6 //////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * SQL Server Database Username * @var String */ private $_dbUsername; /** * SQL Server Database Password * @var String */ private $_dbPassword; /** * SQL Server Hostname \ IP Address * @var String */ private $_dbServerHost; /** * SQL Server Database Name * @var String */ private $_dbSelectName; /** * SQL Server Database Table Prefix (If Any) * @var String */ private $_dbTblPrefix; /** * Maintain Persistant Connection To SQL Server * @var boolean */ private $_dbUsePersistantConn; /** * SQL Server Connection Resource * @var Resource */ private $_dbResource; /** * SQL Server Query Logger * @var Array() */ private $_dbQueryLogger = array(); /** * SQL Server Error Logger * @var Array() */ private $_dbErrorLogger = array(); /////////////////////////////////////////////////////////////////////////// /////////////////// Below is Email Alert Configuration //////////////////// /////////////////// These values cannot be set directly /////////////////// //////////////// And must be set using the set() fuctions ///////////////// /////////////////////////////// v1.0.0 //////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * Enable Email Alerts On SQL Errors * * @param Boolean */ private $_enabledEmailAlerts = false; /** * Email Address To Send Alerts To If Enabled * * @param String */ private $_emailAlertAddress; /** * Title of Alert email * * @param String */ private $_emailAlertSubject; /////////////////////////////////////////////////////////////////////////// ////////////////// Below is MySQL Configuration Functions ///////////////// /////////////////////////////// v1.0.6 //////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * Set Database Username * * @param string $Username */ public function setUsername($Username) { $this->_dbUsername = $Username; } /** * Set Database Password * * @param string $Password */ public function setPassword($Password) { $this->_dbPassword = $Password; } /** * Set Database IP \ HostName * * @param string $Host */ public function setServerDSN($Host) { $this->_dbServerHost = $Host; } /** * Set Database For Use * * @param string $DbName */ public function setDatabase($DbName) { $this->_dbSelectName = $DbName; } /** * Use persistant connection to database * * @param boolean $Persistant */ public function setPersistant($Persistant = false) { $this->_dbUsePersistantConn = $Persistant; } /////////////////////////////////////////////////////////////////////////// ////////////////// Below is Email Configuration Functions ///////////////// /////////////////////////////// v1.0.6 //////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * Enable Email Alerts * Disabled by default, only enable if needed. * * @param boolean $enable */ public function setEmailAlerts($enable) { $this->_enabledEmailAlerts = $enable; } /** * Set Email Address To Send Alerts Too * This is optional and only needs to be set if server is not on "localhost" * * @param String */ public function setEmailAlertAddress($emailAddress) { $this->_emailAlertAddress = $emailAddress; } /** * Set Email Title * * @param String $emailTitle */ public function setEmailAlertSubject($emailSubject) { $this->_emailAlertSubject = $emailSubject; } /////////////////////////////////////////////////////////////////////////// ///////////////////// Below is Functions Needed For MySQL ///////////////// /////////////////////////////// v1.0.6 //////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * Connect To SQL Server And Select Database * * @param boolean $selectDb Select Database For Use? True | False * @return boolean */ public function getConnected($selectDb = true) { if ($this->_dbUsePersistantConn) { $this->_dbResource = @mysql_pconnect($this->_dbServerHost, $this->_dbUsername, $this->_dbPassword); } else { $this->_dbResource = @mysql_connect($this->_dbServerHost, $this->_dbUsername, $this->_dbPassword); } if ($this->_dbResource) { if ($selectDb) { if (@mysql_select_db($this->_dbSelectName)) { return true; } else { $this->logError($this->getError(), $this->getErrorNum()); return false; } } else { $this->logError("Connected To Server, No Database Selected","????"); return false; } } else { $this->logError($this->getError(),$this->getErrorNum()); return false; } } /** * Create Database On SQL Server * If $dbName is not defined, Function will use one defined in class constructor. * * @param String $dbName * @return boolean */ public function execCreateDatabase($dbName) { if ($this->_dbResource) { if ($dbName != '') { $sql = "create database `$dbName`"; } else { $sql = "create database `".$this->_dbSelectName."`"; } $this->execQuery($sql); } else { $this->logQuery($sql, "No Connection To Server", "x123"); return false; } } /** * Drop Database On SQL Server * If $dbName is not defined, Function will use one defined in class constructor * * @param String $dbName * @return boolean */ public function execDropDatabase($dbName) { if ($this->_dbResource) { if ($dbName != '') { $sql = "drop database `$dbName`"; } else { $sql = "drop database `".$this->_dbSelectName."`"; } $this->execQuery($sql); } else { $this->logQuery($sql, "No Connection To Server", "x123"); return false; } } /** * Execute SQL Query On Database * * @param String $sql * @param Boolean $execQuery (Execute Query = True) * @param Boolean $printSQL (Echo SQL To Screen = True) * @return Boolean */ public function execQuery($sql, $execQuery = true, $printSQL = false) { if ($this->_dbResource) { $sql = ltrim($sql); if ($execQuery) { if ($result = @mysql_query($sql, $this->_dbResource)) { $this->logQuery($sql, $this->getError(), $this->getErrorNum()); return $result; } else { if ($this->_enabledEmailAlerts) { $this->sendMySQLError($sql, $this->getError(), $this->getErrorNum()); } $this->logQuery($sql, $this->getError(), $this->getErrorNum()); return false; } } else { $this->logQuery($sql, "Query Not Executed!", "x124"); return false; } if ($printSQL) { echo $sql."<br />"; } } else { $this->logQuery($sql, "No Connection To Server", "x123"); return false; } } /** * Only Allow 'SELECT' SQL Statements To Be Executed On Database * * @param String $sql * @param Boolean $execQuery (Execute Query = True) * @param Boolean $printSQL (Echo SQL To Screen = True) * @return Boolean */ public function execSafeQuery($sql, $execQuery = true, $printSQL = false) { if ($this->_dbResource) { $sql = ltrim($sql); if (substr($sql, 0, 6) == 'select' || substr($sql, 0, 6) == "SELECT") { return $this->execQuery($sql, $execQuery, $printSQL); } else { $this->logQuery($sql, "Tried Executing An Unsafe Query!", "x127"); return false; } } else { $this->logQuery($sql, "No Connection To Server", "x123"); return false; } } /** * Splits A Large SQL File Into Smaller Queries And Executes Them * * NOTE: SQL File Must Not Contain Comments (Working On Fixing That) * NOTE: Function does not yet add table prefixes to queries * * @param string $file (Path to SQL file to execute from) * @param boolean $execQuery */ public function execQueryFromFile($file, $execQuery = true) { if ($fp = @fopen($file, "r")) { $fr = trim(fread($fp, filesize($file))); $sql_queries = explode(";", $fr); foreach ($sql_queries as $query) { if ($query != "") { $query = trim($query); $this->execQuery($query, $execQuery); } } } else { $this->logError("File <i>$file</i> was not found check file path and try again", "x126"); } } /** * Sets Table Prefix * * @param String $tablePrefix (Name Of Prefix) * @param String $prefixSeperator (Symbol That Separates Prefix From Table _ Is Default) */ public function setTblPrefix($tablePrefix, $prefixSeperator = "_") { $this->_dbTblPrefix = $tablePrefix.$prefixSeperator; } /** * Add Table Prefix To The Beginning Of A Table * * @param String $tableName * @return String */ public function addTblPrefix($tableName = '') { if ($tableName != '') { return $this->_dbTblPrefix.$tableName; } else { return $this->_dbTblPrefix; } } /** * Optimize Tables On SQL Server * * @param String $tableName Can be an array to optimize multiple tables at once * @return boolean */ public function optimizeTable($tableName) { if ($this->_dbResource) { if (is_array($tableName)) { foreach ($tableName as $optimize) { $sql = "optimize table `$optimize`"; $this->execQuery($sql); } } else { $sql = "optimize table `$tableName`"; $this->execQuery($sql); } } else { $this->logQuery($sql, "No Connection To Server", "x123"); return false; } } /** * Returns ID Given From 'Insert' Queries * * @return Integer */ public function getInsertId() { return @mysql_insert_id($this->_dbResource); } /** * Return Number Of Rows Returned From 'select' Query * * @param Resource $result (MySQL Query Result) * @return Integer */ public function getNumRows($result) { return @mysql_num_rows($result); } /** * Return Number Of Fields In Table * * @param Resource $result * @return integer */ public function getNumFields($result) { return @mysql_num_fields($result); } /** * Retuned Number Of Affected Rows From 'insert' or 'update' Query * * @return Integer */ public function getAffectedRows() { return @mysql_affected_rows($this->_dbResource); } /** * Get a result row as an enumerated array * * @param Resource $result (MySQL Query Result) * @return String (Array) */ public function getRow($result) { $returnArray = array(); while ($dbArray = @mysql_fetch_row($result)) { $returnArray[] = $dbArray; } return $returnArray; } /** * Fetch a result row as an associative array * * @param Resource $result (MySQL Query Result) * @return String (Array) */ public function getArray($result) { $returnArray = array(); while ($dbArray = @mysql_fetch_assoc($result)) { $returnArray[] = $dbArray; } return $returnArray; } /** * Fetch a result in enumerated & associative array * * @param Resource $result (MySQL Query Result) * @return String (Array) */ public function getBoth($result) { $returnArray = array(); while ($dbArray = @mysql_fetch_array($result, MYSQL_BOTH)) { $returnArray[] = $dbArray; } return $returnArray; } /** * Get a list of all databases available to this user * * @return String (array) */ public function getDatabaseList() { $databases = mysql_list_dbs($this->_dbResource); $returnArray = array(); while ($row = mysql_fetch_object($databases)) { $returnArray[] = $row->Database; } } /** * Get a list of all tables in a specified database * If database isnt defined, script will use one defined in class. * * @param String $database * @return string (array) */ public function getTableList($database = "") { // Use Function defined database... Or class defined if ($database != "") { $listTable = @mysql_list_tables($database, $this->_dbResource); } else { $listTable = @mysql_list_tables($this->_dbSelectName, $this->_dbResource); } // Get array list of tables $oddArray = $this->getRow($listTable); $returnArray = array(); // For() loop to make array nicer for ($i = 0; $i < sizeof($oddArray); $i++) { $returnArray[] = $oddArray[$i][0]; } return $returnArray; } /** * Get a list of all fields (columns) in a specified table. * * @param String $userTable * @return String (array) */ public function getFieldName($userTable) { $fieldList = array(); // Get all columns.. $sql = "SELECT * FROM `$userTable`"; $result = $this->execSafeQuery($sql); $count = $this->getNumFields($result); // Loop through columns and assign to an array() for ($i = 0; $i < $count; $i++) { $fieldList[] = @mysql_field_name($result, $i); } return $fieldList; } /** * Return field (column) type in a specified table * * @param String $userTable * @return String (array) */ public function getFieldType($userTable) { $fieldType = array(); $sql = "SELECT * FROM `$userTable`"; $result = $this->execSafeQuery($sql); $count = $this->getNumFields($result); for ($i = 0; $i < $count; $i++) { $fieldType[] = @mysql_field_type($result, $i); } return $fieldType; } /** * Return field (column) length * * @param string $userTable * @return integer (array) */ public function getFieldLength($userTable) { $fieldLen = array(); $sql = "SELECT * FROM `$userTable`"; $result = $this->execSafeQuery($sql); $count = $this->getNumFields($result); for ($i = 0; $i < $count; $i++) { $fieldLen[] = @mysql_field_len($result, $i); } return $fieldLen; } /** * Returns field (column) flags * ie.. primary key, auto_increment etc etc. * * @param string $userTable * @return string (array) */ public function getFieldFlag($userTable) { $fieldFlag = array(); $sql = "SELECT * FROM `$userTable`"; $result = $this->execSafeQuery($sql); $count = $this->getNumFields($result); for ($i = 0; $i < $count; $i++) { $fieldFlag[] = @mysql_field_flags($result, $i); } return $fieldFlag; } /** * Return MySQL Error String * * @return String */ private function getError() { return @mysql_error(); } /** * Return MySQL Error Number * * @return Integer */ private function getErrorNum() { return @mysql_errno(); } /** * Add A Query To Logger System * * @param string $sql * @param string $error * @param integer $errno */ private function logQuery($sql, $error = null, $errno = null) { $this->_dbQueryLogger[] = array("sql" => $sql, "error" => $error, "errno" => $errno); } /** * Add Error To Logger System * * @param string $message */ private function logError($error = null, $errno = null) { $this->_dbErrorLogger[] = array("error" => $error, "errno" => $errno); } /** * Return All Logged Queries In HTML Format * * @return String */ public function getLoggedQueries() { $return = '<table width="100%" cellspacing="1"><tr><th>Queries Logged</th></tr>'; foreach ($this->_dbQueryLogger as $query) { if ($query['error'] != null) { $return .= '<tr><td><span style="color:#ff0000;">'.htmlspecialchars($query['sql']).'<br /><b>Error number: </b>'.htmlspecialchars($query['errno']).'<br /><b>Error message: </b>'.htmlspecialchars($query['error']).'</span></td></tr>'; $return .= '<tr><td><hr color="#CCCCCC" /></td></tr>'; } else { $return .= '<tr><td><span style="color:#009933;">'.htmlspecialchars($query['sql']).'</span></td></tr>'; $return .= '<tr><td><hr color="#CCCCCC" /></td></tr>'; } } $return .= '<tr><td>Total Queries: <span style="color:#009933;">'.count($this->_dbQueryLogger).'</span></td></tr>'; echo $return; } /** * Return All Logged Errors In HTML Format * * @return String */ public function getLoggedErrors() { $return = '<table width="100%" cellspacing="1"><tr><th>Errors Logged</th></tr>'; foreach ($this->_dbErrorLogger as $error) { $return .= '<tr><td><span style="color:#ff0000;"><br /><b>Error number: </b>'.htmlspecialchars($error['errno']).'<br /><b>Error message: </b>'.htmlspecialchars($error['error']).'</span></td></tr>'; $return .= '<tr><td><hr color="#CCCCCC" /></td></tr>'; } $return .= '<tr><td>Total Queries: <span style="color:#009933;">'.count($this->_dbErrorLogger).'</span></td></tr>'; echo $return; } /** * Terminate Connection To SQL Server * */ public function terminateConn() { @mysql_close($this->_dbResource); $this->logError("Connection To The Server Was Terminated By The User", "x125"); } /////////////////////////////////////////////////////////////////////////// ////////////// Below is Functions Needed For Email Alerts ///////////////// /////////////////////////////// v1.0.0 //////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /** * Email SQL Errors to Administrator \ Or Email Address In Class. * * @return boolean */ private function sendMySQLError($sql, $error, $errno) { // Config Values $sendTo = $this->_emailAlertAddress; $subject = $this->_emailAlertSubject; // Email Headers $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // // Email Body $body = '<html> <head> <title>'.$subject.'</title> <style type="text/css"> <!-- .errorDiv{ font-style:italic; font-size:smaller; color:#CC0000; } .queryDiv{ font-style:italic; font-size:smaller; color:#CC0000; } .subDiv { color:#000000; font-size:small; font-weight:normal; } .titleDiv { border: thin solid #CC0000; width: 75%; padding: 5px; } .mainDiv { text-align:center; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: small; font-weight:bold; color:#000000; } --> </style> </head> <body> <div class="mainDiv"> An SQL error has occurred and this email has been sent to notify you of the error and its description. <br /> <br /> <div class="titleDiv"> <div class="subDiv"> --- Query Details --- <div class="queryDiv"> '.$sql.' </div> <br /> --- Error Details --- <div class="errorDiv"> '.$error.' </div> <br /> --- Error Number --- <div class="errorDiv"> '.$errno.' </div> <br /> --- Time \ Date --- <div class="errorDiv"> '.date("F j, Y, g:i a").' </div> </div> </div> </div> </body> </html>'; // // Send The Email $mailer = mail($sendTo, $subject, $body, $headers); // if (!$mailer) { $this->logError("Failed sending mail", "x128"); } } } ?>
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.