|
Posted by windandwaves on 08/12/05 02:56
windandwaves wrote:
Here is another bunch of functions that I think may benefit from being in a
class, but I am not sure how...
The file is called mysql.php and it is part of my library.
<?php
//this file provides basic sql functions that are used by other scripts
//you have to be careful with SQL because it can screw with your data
//therefore, never use " quotes but always use ' to encapsulate queries
//also, encapsulate fields and tables with ` symbols
//actual values (e.g. `ID` = "3") to be inserted should be encapsulated with
"-style quotes
//it does not make much difference, but it definitely protects against basic
SQL injection.
//used for action queries (delete, insert, update)
function sqler($s) {
sqllog($s);
$query = mysql_query($s);
if($query){
return 1;
}
else {
sqllog("error in previous entry");
return 0;
}
}
//allows you to select the first field of the first row in a query (can have
only one row)
//e.g. $s = select d from final where id =1;
function mysql_zz($s) {
sqllog($s);
$query = mysql_query($s);
if($query) {
if (mysql_num_rows($query) != 1) {
sqllog("error in previous entry");
return false;
}
return mysql_result($query, 0,0);
}
else {
sqllog("error in previous entry");
}
}
//return value in table (t) for field (f) where (id)
function look($t, $f, $id) {
return mysql_zz('SELECT `'.$t.'`.`'.$f.'` FROM `'.$t.'` WHERE ID =
"'.$id.'";');
}
//like look but returns a string if the record can not be found
function lookd($t, $f, $id) {
$v = look($t, $f, $id);
if ( $v ) {
return $v;
}
else {
return 'record not defined';
}
}
//looks up the value for a certain table where a certain field is a certain
value
function idlook($t, $f, $v) {
return mysql_zz('SELECT `'.$t.'`.`ID` FROM `'.$t.'` WHERE '.$f.' =
"'.$v.'";');
}
function tcount ($t, $w) {
return mysql_zz('SELECT (COUNT(`'.$t.'`.`ID`)) a FROM `'.$t.'` WHERE '.$w.'
;');
}
//checks if ID exists and makes sure no sql is injected, mainly useful for
autonumber IDs
function idok($t, $id) {
$min = maxi($t, true);
$max = maxi($t, false);
$id = sanitize_int($id, $min, $max);
if($id) {
return mysql_zz('SELECT `'.$t.'`.`ID` FROM `'.$t.'` WHERE ID =
"'.$id.'";');
}
else {
return 0;
}
}
//check if ID exists for short lookup lists
function idok_byte($t, $id) {
$id = sanitize_int($id, 0, 255);
return mysql_zz('SELECT `'.$t.'`.`ID` FROM `'.$t.'` WHERE ID =
"'.$id.'";');
}
//finds the max and/or min ID-value for a certain table
function maxi($t, $min = false){
if ($min) {
$word = 'MIN';
}
else {
$word = 'MAX';
}
return mysql_zz('SELECT '.$word.'(ID) FROM `'.$t.'`;');
}
function sqllog ($s) {
$sql = 'INSERT INTO `SQL` ( `MEM` ) VALUES ("'.removequotes($s).'");';
return mysql_query($sql);
}
?>
Navigation:
[Reply to this message]
|