Jump to content
Robert1995

DB insert/update/delete V2

Recommended Posts

Posted

Cadou de la mine. db_query presupun ca va prindeti ce face


/**
* Wrap my array
* @param array the array you want to wrap
* @param string wrapper , default double-quotes(")
* @return an array with wrapped strings
*/
function wrap_my_array($array , $wrapper = '"') {
$new_array = array();
foreach($array as $k=>$element){
if(!is_array($element)){
$new_array[$k] = $wrapper . $element . $wrapper;
}
}
return $new_array;

}
/**
* Implode an array with the key and value pair giving
* a glue, a separator between pairs and the array
* to implode.
* @param string $glue The glue between key and value
* @param string $separator Separator between pairs
* @param array $array The array to implode
* @return string The imploded array
*/
function array_implode( $glue, $separator, $array ) {
if ( ! is_array( $array ) ) return $array;
$string = array();
foreach ( $array as $key => $val ) {
if ( is_array( $val ) )
$val = implode( ',', $val );
$string[] = "{$key}{$glue}{$val}";

}
return implode( $separator, $string );
}

/**
* @param string db_name
* @param array data
* @uses wrap_my_array
* @uses array_implode
*/
function db_insert($db_name , $data){
if(is_array($data) && !empty($data)){

$data = array_map('mysql_escape_string', $data);

$keys = array_keys($data);

$sql = 'INSERT INTO {'.$db_name.'} ('
.implode("," , wrap_my_array($keys , '`'))
.') VALUES ('
.implode("," , wrap_my_array($data))
.')';
db_query($sql);
return true;
}
return false;
}

/**
* @param string db_name
* @param array data
* @param array/string where
* @uses wrap_my_array
* @uses array_implode
*/
function db_update($db_name , $data = array() , $where = array()) {
if(is_array($data) && !empty($data)){
$data = array_map('mysql_escape_string', $data);
$data = wrap_my_array($data);

$sql = 'UPDATE {'.$db_name.'} SET ';
$sql .= array_implode("=" , "," , $data);

if(!empty($where)){
$sql .= ' WHERE ';
if(is_array($where)){
$where = wrap_my_array($where);
$sql .= array_implode("=" , "AND" , $where);
}else{
$sql .= $where;
}
}

db_query($sql);
return true;
}
return false;
}

/**
* @param string db_name
* @param array/string where
* @uses wrap_my_array
* @uses array_implode
*/
function db_delete($db_name , $where = array()){
$sql = 'DELETE FROM {'.$db_name.'} ';

if(!empty($where)){
$sql .= ' WHERE ';
if(is_array($where)){
$where = wrap_my_array($where);
$sql .= array_implode("=" , "AND" , $where);
}else{
$sql .= $where;
}
}

db_query($sql);
}

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...