Skip to content

Instantly share code, notes, and snippets.

@aswebdev
Last active December 27, 2015 00:59
Show Gist options
  • Save aswebdev/f297768b08b49a5ad43f to your computer and use it in GitHub Desktop.
Save aswebdev/f297768b08b49a5ad43f to your computer and use it in GitHub Desktop.
A Database select function
function dbSelect($select,$from,$where,$orderby=false,$limit=false,$connection=false) {
// dbSelect 0.2, Created by AS
// General Database Selection Function
// initate variables
$query = ''; // String to Setup query
$return = ''; // The return array
$rowsReturned = ''; // The Number of Rows Returned from the query
$error = false; // Boolean. Has an error.
$query = 'SELECT '; // Initiate Query
if(!empty($select)) { // Check the SELECT Query is not empty
if(is_array($select)) { // $select argument is an array
foreach($select as $s) {
$query .= $s.","; // Loop the Selected Rows
}
$query = substr($query,0,-1); // Strip the Last Comma
} else {
$query .= $select; // Standard string $select argument.
}
} else {
$error .= "No SELECT Argument Set in dbSelect function"; // Is an empty Select Argument
}
$query .= ' FROM '; // Continue building SQL Statement
if(!empty($from)) { // Check the FROM query is not empty
if(is_array($from)) { // $from argument is an array
foreach($from as $f) {
$query .= "`".$f."`,";
}
$query = substr($query,0,-1); // Strip the Last Comma
} else {
$query .= $from; // Standard string $from argument
}
} else {
$error .= "No FROM Argument Set in dbSelect function"; // Is an empty Select Argument
}
if($where) { $query .= ' WHERE '.$where; } // If has where condition
if($orderby) { $query .= ' ORDER BY '.mysql_real_escape_string($orderby); } // If order by condition
if($limit) { $query .= ' LIMIT '.mysql_real_escape_string($limit); } // If order by condition
if($resource = mysql_query($query)) {
$rowsReturned = mysql_num_rows($resource); // Check the Amount of Rows Returned
if(mysql_num_rows($resource) > 0) {
$return['rows'] = $rowsReturned;
if($rowsReturned == 1) {
$return['results'][0] = mysql_fetch_array($resource); // Returned Single Row of Results
} else {
// Has returned multiple results. Run Query to get them
$return['results'] = array();
while($rows = mysql_fetch_assoc($resource)) {
$return['results'][] = $rows; // Return The Rows into an array
}
}
} else {
$return['results'] = 0; // Has Return no results
}
} else {
$error = 'Query Error ('.$query.')'; // Error with MySQL Query
}
if(DEBUG == true) { if($error) { echo $error; exit; } } // Check for Error
return $return; // Return the Array
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment