When working on the web it often helps to have some kind of database abstraction present. For my Limonade-php projects, I normally end up utilizing a single function that currently ties in to a mysql database. The connection happens before you call the method, but if you pass in a connection resource it will use that resource for the sql statement.
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
|
<?php
/**
* A quick little function to interact with a MySQL database.
*
* When working with Limonade-php a full-fledged MySQL wrapper seems like
* overkill. This method instead accepts any mysql statement and if it works
* returns either the result or the number of rows affected. If neither worked,
* then it returns false
*
* @param string $sql the sql statement you want to execute
* @param resource $c mysql connect link identifier, if multi-connect
* otheriwse, you can leave it blank
* @return MIXED array the result set if the sql statement was a SELECT
* integer if the sql statement was INSERT|UPDATE|DELETE
* bool if anything went wrong with executing your statement
*
*
* [update|insert|delete]
* if(db('update mytable set myrow = 4 where someotherrow = 3') !== false) {
* // worked!
* }
*
* [select]
* $res = db('select * from mytable');
*/
function db($sql,$c = null) {
$res = false;
$q = ($c === null)?@mysql_query($sql):@mysql_query($sql,$c);
if($q) {
if(strpos(strtolower($sql),'select') === 0) {
$res = array();
while($r = mysql_fetch_assoc($q)) {
$res[] = $r;
}
}
else {
$res = ($c === null)?mysql_affected_rows():mysql_affected_rows($c);
}
}
return $res;
}
?>
|
Line by line explanation:
1-25: Documentation
26: Function declaration, accepts an sql statement and an optional connection resource.
27: We preset $res to false This is so that we can get rid of a bunch of if-statements 28: If there is no connection resource, just execute the sql statement. If there is, use it. (@ surpresses errors)
29: Check to see if our query worked, if it didn’t, we just return res which we preset.
30: Checks to see if we tried to execute a ‘SELECT’ statement.
31: Change $res into an array. Our results will be a nested array since our statement worked!
32-34: Loop through our results and assign them to $res.
36-38: If the sql statement was NOT a ‘SELECT’, return the number of affected rows. If a user passed in a connection resource, use that.
40: return $res, which could either be false, array() or int depending on if the query failed, was a select statement, affected the rows.