sql >> Base de Datos >  >> RDS >> Mysql

ODBC/MYSQL Insertar un resultado de consulta de ODBC a una base de datos en MYSQL

Opción 1:

Función para SELECCIONAR

function get_data_from_cloud(){
    $conn=odbc_connect('CLOUD','','');
    if (!$conn) {
        exit("Connection Failed: " . $conn);
    }
    $sql="SELECT DATETIME, NAME, CNDROP 
          FROM TABLE1 
          WHERE DATETIME>='2014-09-28 00:00:00' and 
                DATETIME<='2014-09-28 23:00:00' and 
                NAME IN ('PETER') 
          GROUP BY DATETIME, NAME 
          ORDER BY DATETIME, NAME";

    $result=odbc_exec($conn,$sql)or die(exit("Error en odbc_exec"));

    $data = array();
    while (odbc_fetch_row($result)) {
        $data[]=array('DATETIME' => odbc_result ($result, "DATETIME"), 
                      'NAME'=> odbc_result ($result, "NAME"), 
                      'CNDROP'=> odbc_result ($result, "CNDROP"));
    }
    return $data;   
}

Función para INSERTAR

function insert_cloud_data($cloud_data=array()){
    $conn=odbc_connect('LOCAL','','');
    if (!$conn) {
        exit("Connection Failed: " . $conn);
    }
    foreach($cloud_data as $data){
        $sql = sprintf("INSERT INTO Prueba (DATIME, NAME, CNDROP)
                       VALUES ( '%s','%s','%s')",
                      $data['DATETIME'], $data['NAME'], $data['CNDROP']);
        $rs = odbc_exec($conn,$sql);    

        if (!$rs) {
            error_log("Consulta fallida");
        }   
    }

    odbc_close($conn);
}

Opción 2:

Función para SELECCIONAR

function get_data_from_cloud(){
    $conn=odbc_connect('CLOUD','','');
    if (!$conn) {
        exit("Connection Failed: " . $conn);
    }
    $sql="SELECT DATETIME, NAME, CNDROP 
          FROM TABLE1 
          WHERE DATETIME>='2014-09-28 00:00:00' and 
                DATETIME<='2014-09-28 23:00:00' and 
                NAME IN ('PETER') 
          GROUP BY DATETIME, NAME 
          ORDER BY DATETIME, NAME";

    $result=odbc_exec($conn,$sql)or die(exit("Error en odbc_exec"));

    $data = array();
    while (odbc_fetch_row($result)) {
        $data[]=array(odbc_result ($result, "DATETIME"),
                      odbc_result ($result, "NAME"),
                      odbc_result ($result, "CNDROP"));
    }
    return $data;   
}

Función para INSERTAR

function insert_cloud_data($cloud_data=array()){
    $conn=odbc_connect('LOCAL','','');
    if (!$conn) {
        exit("Connection Failed: " . $conn);
    }

    $sql = "INSERT INTO Prueba (DATIME, NAME, CNDROP)
            VALUES (?, ?, ?)";
    $stmt = odbc_prepare($conn, $sql);
    if(!$stmt) die("could not prepare statement ".$sql);

    foreach($cloud_data as $data){
        odbc_execute($stmt, $data);  
    }

    odbc_close($conn);
}

USO

$cloud_data = get_data_from_cloud();
insert_cloud_data($cloud_data);