Drupal - Custom functions
I created the functions below to easily process the values of a $field in a $table by $number using the specified $params.
Explanation:
Explanation:
$number = number
$field = string
$table = string(schema name)
$params = array(
'fields' => array('uid','nid',...),
'select' => array('=','>','<',...),
'update' => array('=','>','<',...),
'values' => array('1','1',...),
);
/*
* This function increases by $number,
* the $field of the $table WHERE $params
* are valid. This function assumes the
* field needs to be updated and NOT created.
*/
function module_increase_field($table,$field,$number,$params){
$select = "SELECT {$field} FROM {".$table."}";
if(!empty($params['fields'])){
$select .= " WHERE ";
for($i=0;$i<count($params['fields']);$i++){
$select .= $params['fields'][$i].$params['select'][$i]."'".$params['values'][$i]."',";
}
$select = substr($select,0,strlen($select)-1);
$value = db_result(db_query($select),0);
$value++;
$update = "UPDATE {".$table."} SET {$field}='{$value}' WHERE ";
for($i=0;$i<count($params['fields']);$i++){
$update .= $params['fields'][$i].$params['update'][$i]."'".$params['values'][$i]."' AND ";
}
$update = substr($update,0,strlen($update)-4);
db_query($update);
}else{
watchdog('Modify field',t('The $params array is empty'));
}
}
/*
* This function increases by $number,
* the $field of the $table WHERE $params
* are valid. This function assumes the
* field needs to be updated and NOT created.
*
* @see function module_increase_field()
* for more information
*/
function module_decrease_field($table,$field,$number,$params){
$select = "SELECT {$field} FROM {".$table."}";
if(!empty($params['fields'])){
$select .= " WHERE ";
for($i=0;$i<count($params['fields']);$i++){
$select .= $params['fields'][$i].$params['select']."'".$params['values'][$i]."',";
}
$select = substr($select,0,strlen($select)-1);
$value = db_result(db_query($select),0);
$value++;
$update = "UPDATE {".$table."} SET {$field}='{$value}' WHERE";
for($i=0;$i<count($params['fields']);$i++){
$update .= $params['fields'][$i].$params['update'][$i]."'".$params['values'][$i]."' AND ";
}
$update = substr($update,0,strlen($update)-4);
db_query($update);
}else{
watchdog('Modify field',t('The $params array is empty'));
}
}
/*
* This function returns the number of
* $field(s) the $table has WHERE $params
* are valid.
*
* @see function_module_increase_field()
* for more information
*/
function module_count_field($table,$field,$params){
$sql = "SELECT COUNT({$field}) FROM {".$table."}";
if(!empty($params['fields'])){
$sql .= " WHERE ";
for($i=0;$i<count($params['fields']);$i++){
$sql .= $params['fields'][$i].$params['select'][$i]."'".$params['values'][$i]."' AND ";
}
$sql = substr($sql,0,strlen($sql)-4);
}
return db_result(db_query($sql));
}
Comments