Ver Mensaje Individual
  #1 (permalink)  
Antiguo 22/04/2011, 20:13
Avatar de carlos_belisario
carlos_belisario
Colaborador
 
Fecha de Ingreso: abril-2010
Ubicación: Venezuela Maracay Aragua
Mensajes: 3.156
Antigüedad: 14 años
Puntos: 461
Funcion para insertar datos

bueno como voy saliendo de dudas y haciendo pruebas me hice una funcion para insertar datos en cualquier tabla que indiquemos a la misma trabajando con wordpress, aca la funcion espero que les sirva, la hice trabajando con consultras preparadas porque me parece de mayor seguridad
Código PHP:
Ver original
  1. function insert($table,$data = array(),$exist = array()){
  2.     global $wpdb;
  3.     if(empty($table) || empty($data) || !is_array($data)){
  4.         echo "Debe indicar la tabla y los datos a ser insertados";
  5.         return false;
  6.     }
  7.     if(!empty($exist)){
  8.         foreach($exist as $k => $v){           
  9.             $condic = "$v = '".$data[$v]."'";
  10.         }      
  11.         $existe = $wpdb->get_row("SELECT * FROM $table WHERE $condic", ARRAY_A);               
  12.         if(count($existe) > 0){
  13.             return "existe";
  14.         }
  15.     }
  16.     foreach($data as $key => $value){
  17.         $field[] = $key;
  18.         if(gettype($value) == "integer"){
  19.             $type[] = "%d";
  20.         }
  21.         elseif(gettype($value) == "string"){
  22.             $type[] = "%s";
  23.         }
  24.         $values[] = $value;
  25.     }
  26.     $fields = implode(',',$field);
  27.     $types = implode(',',$type);   
  28.     $wpdb->query($wpdb->prepare("INSERT INTO $table($fields) VALUES ($types)",$data));
  29.     return true;
  30. }
la probe con varias tblas qe tengo en el proyecto que estoy trabajando y me funciono, espero que les sirva
__________________
aprende d tus errores e incrementa tu conocimientos
it's not a bug, it's an undocumented feature By @David
php the right way

Última edición por carlos_belisario; 22/04/2011 a las 20:50