[thelist] PHP/MySQL wrapper
Kasimir K
evolt at kasimir-k.fi
Thu Oct 21 04:54:14 CDT 2004
Hello,
I've made myself a wrapper to make (My)SQL queries from PHP. While I
have no problems with it, I'd like to hear your opinions of it. Would it
make sense to check/sanitize the $sql_query? Is there a way to find out
if $sql_query is already slashed? Any other ideas/thoughts?
cheers,
.k
<?php
/*
function sql_query
wrapper for all db queries
for queries returning a resource, $type, $key1 and $key2 may be set
- $type sets the type used with mysql_fetch_array()
- $key1 sets what row will be returned
- $key2 sets what column will be returned
- if $key1 and $key2 are both '*' an array of arrays is returned
- else if $key1 or $key2 is '*' an array is returned
- else a string is returned
for insert queries the auto increment id is returned
for other queries true is returned
*/
function sql_query($sql_query, $type = 'b', $key1 = '*', $key2 = '*')
{
$statements = preg_split('/\s/', $sql_query, -1,
PREG_SPLIT_NO_EMPTY);
switch (strtoupper($statements[0]))
{
case 'SELECT' :
case 'SHOW' :
case 'EXPLAIN' :
case 'DESCRIBE' :
switch ($type)
{
case 'b': $type = MYSQL_BOTH; break;
case 'a': $type = MYSQL_ASSOC; break;
case 'n': $type = MYSQL_NUM; break;
}
$rs = query_or_die($sql_query);
$array = array();
while ($row = mysql_fetch_array($rs, $type))
{
array_push($array, $key2 == '*' ? $row : $row[$key2]);
}
return $key1 == '*' ? $array : $array[$key1];
break;
case 'INSERT' :
query_or_die($sql_query);
return mysql_insert_id();
break;
default:
query_or_die($sql_query);
return true;
break;
}
}
function query_or_die($sql_query)
{
return mysql_query($sql_query)
or die('<pre>' . mysql_error() . '</pre>
<pre>' . $sql_query . '</pre>');
}
// usage examples
// list of articles
$articles = sql_query
("
SELECT title, pub_date
FROM articles
");
// just one article (one row)
$article = sql_query
("
SELECT title, body, pub_date
FROM articles
WHERE art_id = '" . $id . "'
", 'a', '0');
// just pub_dates (one column)
$pub_dates = sql_query
("
SELECT pub_date
FROM articles
", 'n', '*', '0');
// just one item
$title = sql_query
("
SELECT title
FROM articles
WHERE art_id = '" . $id . "'
", 'n', '0', '0');
?>
More information about the thelist
mailing list