One thing I realized while going through code yesterday at my internship is that I run sql queries quite often. So I decided to write a function to keep all of the calls in one place and reduce the number of lines of code. It doesn't cover all possible sql calls but it does cover the basic calls I believe.
So my question is, are there any coding practices I could improve upon or have violated while writing this?
EDIT: I broke the function up into four separate functions. When it comes to PDO my bosses said they did that behind the scenes with each $db_function(there is a different sequence for each server they access) that is called. I'm simply preparing the string that they manipulate. Also I've always viewed associative arrays as field value pairs so I welcome any suggestions in alternative names.
<?
* INPUT:
* (string) Db_function: Which sql function to call
* (string) Table: The table to use
* (string/array) Fields: The values to be manipulated along with valid sql statements/modifiers(e.g DISTINCT or aliases) ,
* its a string for SELECT/DELETE or an array for INSERT/UPDATE.
* (string) Conditional: Statements that go at the end of the query such as WHERE, ORDER BY, JOIN etc.
*
* OUTPUT:
* TRUE for SELECT/DELETE or the query results for INSERT/UPDATE */
function sql_Select($Db_Function,$Table, $Fields, $Conditional = NULL){
$sql = "SELECT $Fields FROM $Table";
if(!is_null($Conditional)){
$sql .= $Conditional;
return $Db_Function($sql,1,1,1);
}
return $Db_Function($sql,1,1,1);
}
function sql_Update($Db_Function,$Table, $Fields, $Conditional = NULL){
$sql = "UPDATE $Table SET";
foreach($Fields as $field => $value){
$sql .= is_numeric($value) ? " $field = $value , " : " $field = '$value' , " ;
}
$sql = preg_replace('/,$/', '', trim($sql)); //Removes the extra ','
if(!is_null($Conditional)){
$sql .= $Conditional;
return $Db_Function($sql,0,0,0);
}
return $Db_Function($sql,0,0,0);
}
function sql_Insert($Db_Function,$Table, $Fields, $Conditional = NULL){
$Field_Name = implode(',',array_keys($Fields));
$sql = "INSERT INTO $Table ($Field_Name) VALUES ( ";
foreach($Fields as $field => $value){
$sql .= is_numeric($value) ? " $value, " : " '$value', " ;
}
$sql = preg_replace('/,$/', '', trim($sql)); //Removes the extra ','
$sql .= ')';
if(!is_null($Conditional)){
$sql .= $Conditional;
return $Db_Function($sql,0,0,0);
}
return $Db_Function($sql,0,0,0);
}
function sql_delete($Db_Function,$Table, $Fields, $Conditional = NULL){
$sql = "DELETE FROM $Table";
if(!is_null($Conditional)){
$sql .= $Conditional;
return $Db_Function($sql,0,0,0)
}
return $Db_Function($sql,0,0,0)
}
?>