Moderator |
|
Inspiratie - ik gebruik deze functie voor het uitvoeren van queries, en het loggen van mogelijke fouten:
<?php
function query($query, $fetch_method="assoc", $die=0, $log=1, $redirect=1) {
global $cfg;
// $cfg['mod'] = hoofdpagina waar je op zit
// $cfg['sub'] = subpagina waar je op zit
$ret = array();
$res = @mysql_query($query);
if(mysql_error() != "") {
// error handling
$err = array();
$err[] = "INSERT INTO mysql_log(`date`, `mod`, `sub`, `err_no`, `err_text`, `query`) ";
$err[] = "VALUES(";
$err[] = time().", ";
$err[] = "'".$cfg['mod']."', ";
$err[] = "'".$cfg['sub']."', ";
$err[] = mysql_errno().", "; // 999-1175
// if mysql_errno is 0 this could indicatie wrong username/pass when connecting to or selecting db
$err[] = "'".addslashes(htmlentities(mysql_error()))."', "; // possible javascript inserts
$err[] = "'".addslashes(htmlentities($query))."'"; // for readability
$err[] = ")";
// die?
if($die) {
die("<pre>".print_r($err, 1)."</pre>");
}
// log?
if($log) {
@mysql_query(implode("", $err)); // assume this query DOES get executed correctly ;)
}
// mail administrator or take some other action? use mysql_insert_id for the logged error
// ...
// relocate to some neat errorpage?
if($redirect) {
header("Location: /index/error/database");
}
} else {
// any results?
if(mysql_num_rows($res)) {
// fetch results
switch($fetch_method) {
// fetch row
case "row":
while($row = mysql_fetch_row($res)) $ret[] = $row;
break;
// fetch assoc - is also default
case "assoc":
default:
while($row = mysql_fetch_assoc($res)) $ret[] = $row;
}
// free results
mysql_free_result($res);
}
}
// return results
return $ret;
}
?>
<?php function query($query, $fetch_method="assoc", $die=0, $log=1, $redirect=1) { // $cfg['mod'] = hoofdpagina waar je op zit // $cfg['sub'] = subpagina waar je op zit // error handling $err[] = "INSERT INTO mysql_log(`date`, `mod`, `sub`, `err_no`, `err_text`, `query`) "; $err[] = "VALUES("; $err[] = "'".$cfg['mod']."', "; $err[] = "'".$cfg['sub']."', "; // if mysql_errno is 0 this could indicatie wrong username/pass when connecting to or selecting db $err[] = ")"; // die? if($die) { } // log? if($log) { } // mail administrator or take some other action? use mysql_insert_id for the logged error // ... // relocate to some neat errorpage? if($redirect) { header("Location: /index/error/database"); } } else { // any results? // fetch results switch($fetch_method) { // fetch row case "row": break; // fetch assoc - is also default case "assoc": default: } // free results } } // return results return $ret; } ?>
|