简体   繁体   中英

Using foreach loop to insert data into mysql database

Greeting ,

I am using an ODBC connection with qucikbooks. Using PHP i can show quickbooks data on my website. Now I would like to save that data in my local MYSQL. So I create an table and some fields.

//this line gets data from quickbooks connection
$query = odbc_exec($conn, "SELECT GivenName FROM Customers");

//fetch data in an array
while($row = odbc_fetch_array($query)){

    //Go through the array and save the data into MYSQL.
    foreach ($row as $key => $value) {
        echo  $value . "<br>";

        //Insert data into mySQL. 
        $sql = "INSERT INTO Customers (GivenName) VALUES ('$value') ";
        if (mysqli_query($mysqlconn, $sql)) {
            echo "New record created successfully";
        }
    }
}

The foreach loop above dont work.

My question is how I can use foreach loop to get get the data from an array, and insert it into mysql table; and also dont insert any empty field.

Many Thanks

Try this :

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;   
}

ODBC/MYSQL Insert a Query Result from ODBC to a databse in MYSQL

i hope it's help you

I have understood what you doing. But I cannot see an Insert statement anywhere. After getting the data from cloud; I would like to loop through that data and save in MYSQL table on my local server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM