MySQL Database Manager v1.0
Gepost door Skyce ... op 14-11-2010 20:04.
Had een MySQL manager nodig. Misschien heeft iemand er wat aan. Sinds de opschoning van PFZ zijn er nog maar weinig goede managers over.
Hier een simpel voorbeeldje, zitten nog meer functies in maar lijkt me toch altijd verstandig eerst naar de classe te kijken voordat je er wat mee doen op je server. Dan kom je de overige functies vanzelf tegen.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <?php
define('dbServer', 'localhost');
define('dbUser', 'user');
define('dbPassword', 'password');
define('dbDatabase', 'database');
define('logFileSql', '/absolute/path/to/log_file.txt'); // Give write permissions
require_once('class.MySQLManager.php');
/* Select Record */
$db = new MySQLManager();
$db->query("SELECT * FROM table");
echo $db->numRows();
while ($data = $db->nextRecord('array', MYSQL_ASSOC) )
{
echo '<pre>';
var_dump($data);
echo '</pre>';
}
/* Insert Record*/
$db2 = new MySQLManager();
$db2->insert('table', array('field1' => 'value1', 'field2' => "value2"), true);
echo $db3->insertId();
/* Update Record */
$db3 = new MySQLManager();
$db3->update('table', array('field1' => 'value1', 'field2' => 'value2'), array('field1' => 'condition1', 'field2' => 'condition2'), 'AND', true);
?> |
Bestanden van dit script
class.MySQLManager.php
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | <?php
/**
* MySQLDatabase
*
* Creates MySQL database connection and execute queries, inserts, updates, deletes etc.
*
* Following constants need to be defined before including this class:
* dbServer - Database server adres (usually localhost)
* dbUser - Database user
* dbPassword - Database password
* dbDatabase - Database name
* sqlLogFile - Path + filename (txt) of SQL queries log
*
* @since 10-11-2010
*/
class MySQLManager
{
/**
* Contains MySQL link identifier
* @var mixed
*/
private $_connection;
/**
* Contains SQL result resource
* @var mixed
*/
private $_result;
/**
* Contains debug info
* @var mixed
*/
private $_caller;
/**
* Creates database connection
*
* @param string $dbServer Database server adres (usually localhost)
* @param string $dbUser Database user
* @param string $dbPassword Database password
* @param string $dbDatabase Database name
* @return void
*/
function __construct($dbServer = null, $dbUser = null, $dbPassword = null, $dbDatabase = null)
{
$this->_caller = debug_backtrace();
if ( empty($dbServer) )
{
$dbServer = dbServer;
}
if ( empty($dbUser) )
{
$dbUser = dbUser;
}
if ( empty($dbPassword) )
{
$dbPassword = dbPassword;
}
if ( empty($dbDatabase) )
{
$dbDatabase = dbDatabase;
}
$this->_connection = @mysql_connect($dbServer, $dbUser, $dbPassword);
if (!$this->_connection)
{
$this->triggerError('Connection error in __construct()', 'ERROR');
}
$selectDb = @mysql_select_db($dbDatabase);
if (!$selectDb)
{
$this->triggerError('Cannot select database in __construct()', 'ERROR');
}
}
/**
* Creates error messages with caller file and line unlike trigger_error() does
*
* @param string $errorMessage Error message
* @param string $errorType Type of error (ERROR / WARNING / NOTICE)
* @return void
*/
private function triggerError($errorMessage, $errorType)
{
if ( !empty($errorMessage) && ( $errorType == 'ERROR' || $errorType == 'WARNING' || $errorType == 'NOTICE' ) )
{
$errorTitle = '';
switch ($errorType)
{
case 'ERROR':
$errorTitle = 'Fatal error';
break;
case 'WARNING':
$errorTitle = 'Warning';
break;
case 'NOTICE':
$errorTitle = 'Notice';
break;
}
echo '<br /><strong>'.$errorTitle.':</strong> Class MySQLDatabase - '.$errorMessage.' in <strong>'.$this->_caller[0]['file'].'</strong> on line <strong>'.$this->_caller[0]['line'].'</strong><br />';
if ($errorType == 'ERROR')
{
exit();
}
}
else
{
$this->triggerError('Invalid error type or empty error message for triggerError()','ERROR');
}
}
/**
* Executes any SQL query and log query in text file
*
* @param string $sql SQL query to execute
* @param boolean $print Print query
* @return boolean
*/
public function query($sql, $print = false)
{
if ( !empty($sql) )
{
if ($print)
{
echo $sql.'<br />';
}
/* Log query in log-file */
$currentLogFile = file_get_contents(logFileSql);
$currentLogFile .= "[".date('d-M-Y H:i:s')."] SQL query: ".$sql." in ".$this->_caller[0]['file']." on line ".$this->_caller[0]['line']."\n";
file_put_contents(logFileSql, $currentLogFile);
$this->_result = mysql_query($sql, $this->_connection);
if (!$this->_result)
{
$this->triggerError('Cannot execute SQL query in query() ('.mysql_error($this->_connection).')', 'ERROR');
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
/**
* Free result memory
*
* @return void
*/
public function freeResult()
{
$freeResult = @mysql_free_result ($this->_result);
if (!$freeResult)
{
$this->triggerError('Invalid result resource for freeResult()', 'WARNING');
}
}
/**
* Returns an object with properties or an array that corresponds to the fetched row and moves the internal data pointer ahead
*
* @param string $fetchType The way to return a result row (object / array)
* @param constant $resultType The type of array that is to be fetched (MYSQL_ASSOC / MYSQL_NUM / MYSQL_BOTH - only when $fetchType is 'array')
* @return mixed
*/
public function nextRecord($fetchType = 'object', $resultType = MYSQL_ASSOC)
{
if ( ($fetchType == 'array' || $fetchType == 'object') && ($resultType == MYSQL_ASSOC || $resultType == MYSQL_NUM || $resultType == MYSQL_BOTH) )
{
$data = '';
switch ($fetchType)
{
case 'object':
$data = @mysql_fetch_object($this->_result);
break;
case 'array':
$data = @mysql_fetch_array($this->_result, $resultType);
break;
}
return $data;
}
else
{
$this->triggerError('Invalid fetch type or result type for nextRecord()', 'ERROR');
return false;
}
}
/**
* Returns the number of rows from a result set of SELECT or SHOW
* To retrieve the number of rows from a INSERT, UPDATE, REPLACE or DELETE use affected_rows()
*
* @return integer
*/
public function numRows()
{
$num_rows = @mysql_numrows($this->_result);
if (!$num_rows)
{
$this->triggerError('Invalid result resource for numRows()', 'WARNING');
}
else
{
return $num_rows;
}
}
/**
* Returns the number of affected rows by the last INSERT, UPDATE, REPLACE or DELETE
*
* @return integer
*/
public function affectedRows()
{
$affected_rows = @mysql_affected_rows($this->_connection);
if ($affected_rows == -1)
{
$this->triggerError('Invalid resource link identifier for affectedRows()', 'WARNING');
}
else
{
return $affected_rows;
}
}
/**
* Executes INSERT query
*
* @param string $table Database table
* @param array $data Array with fieldname as key and data as value
* @param boolean $print Print query
* @return boolean
*/
public function insert($table, $data, $print = false)
{
if ( !empty($table) && is_array($data))
{
$fields = array();
$values = array();
foreach ($data as $fieldName => $value)
{
$fields[] = mysql_real_escape_string($fieldName);
$values[] = mysql_real_escape_string($value);
}
$sql = "INSERT INTO `".mysql_real_escape_string($table)."` (`".implode("`,`", $fields)."`) VALUES ('".implode("','", $values)."');";
$this->query($sql, $print);
return true;
}
else
{
$this->triggerError('Invalid data array or table for insert()', 'ERROR');
return false;
}
}
/**
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT)
*
* @return mixed
*/
public function insertId() {
$insertId = @mysql_insert_id($this->_connection);
if (!$insertId)
{
$this->triggerError('Invalid resource link identifier insertId()', 'WARNING');
return false;
}
else
{
return $insertId;
}
}
/**
* Updates a record based on conditions
*
* @param string $table Database table
* @param array $data Array with fieldname as key and data as value
* @param array $conditions Array with fieldname as key and condition as value
* @param string $operator SQL operator (AND / OR)
* @param boolean $print Print query
* @return boolean
*/
public function update($table, $data, $conditions, $operator, $print = false)
{
if ( !empty($table) && is_array($data) && is_array($conditions) && ($operator == 'AND' || $operator == 'OR' ) )
{
$tempData = array();
foreach ($data as $fieldName => $value)
{
$tempData[] = mysql_real_escape_string($fieldName)."` = '".mysql_real_escape_string($value);
}
$tempConditions = array();
foreach ($conditions as $fieldName => $value)
{
$tempConditions[] = mysql_real_escape_string($fieldName)."` = '".mysql_real_escape_string($value);
}
$sql = "UPDATE `".mysql_real_escape_string($table)."` SET `".implode("', `", $tempData)."' WHERE `".implode("' ".$operator." `", $tempConditions)."';";
$this->query($sql, $print);
return true;
}
else
{
$this->triggerError('Invalid table, data array, conditions array or operator for update()', 'ERROR');
return false;
}
}
/**
* Removes a record based on conditions
*
* @param string $table Database table
* @param array $conditions Array with field as key and condition as value
* @param string $operator SQL operator (AND / OR)
* @param boolean $print Print query
* @return boolean
*/
public function delete($table, $conditions, $operator, $print = false)
{
if ( !empty($table) && is_array($conditions) && ($operator == 'AND' || $operator == 'OR' ) )
{
$tempConditions = array();
foreach ($conditions as $fieldName => $value)
{
$tempConditions[] = mysql_real_escape_string($fieldName)."` = '".mysql_real_escape_string($value);
}
$sql = "DELETE FROM `".mysql_real_escape_string($table)."` WHERE `".implode("' ".$operator." `", $tempConditions)."';";
$this->query($sql, $print);
return true;
}
else
{
$this->triggerError('Invalid table or conditions array for delete()', 'ERROR');
return false;
}
}
/**
* Checks if data exists in given table based on conditions
*
* @param string $table Database table
* @param string $primaryKey Primery key for selection
* @param array $conditions Array with field as key and condition as value
* @param string $operator SQL operator (AND / OR)
* @param boolean $print Print query
* @return boolean
*/
public function dataExists($table, $primaryKey, $conditions, $operator, $print = false)
{
if ( !empty($table) && !empty($primaryKey) && is_array($conditions) && ($operator == 'AND' || $operator == 'OR' ) )
{
$tempConditions = array();
foreach ($conditions as $fieldName => $value)
{
$tempConditions[] = mysql_real_escape_string($fieldName)."` = '".mysql_real_escape_string($value);
}
$sql = "SELECT `".mysql_real_escape_string($primaryKey)."` FROM `".mysql_real_escape_string($table)."` WHERE `".implode("' ".$operator." `", $tempConditions)."';";
$this->query($sql, $print);
if ($this->numRows() > 0)
{
return true;
}
else
{
return false;
}
}
else
{
$this->triggerError('Invalid table, primary key or conditions array for dataExists()', 'ERROR');
return false;
}
}
/**
* Returns detailed information about the last query
*
* @return mixed
*/
public function sqlInfo() {
$sqlInfo = mysql_info($this->_connection);
if (!$sqlInfo)
{
$this->triggerError('Invalid resource link identifier for sqlInfo()', 'WARNING');
}
else
{
return $sqlInfo;
}
}
/**
* Returns the current server status
*
* @return mixed
*/
public function sqlStats() {
$sqlStats = @mysql_stat($this->_connection);
if ($sqlStats != NULL)
{
return $sqlStats;
}
else
{
$this->triggerError('Invalid resource link identifier for sqlStats()', 'WARNING');
return false;
}
}
}
?>
|
Commentaar
15-11-2010 02:17
16-11-2010 20:20
16-11-2010 22:35


