Search code examples
phpmysqlwhile-loopinsert-into

How to insert data from a select query using php


I wan to insert data to mysql table from another database which is connected via ODBC.But I cannot enter into the while loop, here is my code - N.B: For security I dont provide db name, user and pass. ODBC connection declared as 'connStr'

 <?php
    $connStr = odbc_connect("database","user","pass");
    $conn = mysqli_connect("server","user","pass","database");
    //$result_set=mysqli_query($conn,$datequery);
    //$row=mysqli_fetch_array($result_set);

    echo "<br>";

    echo "<br>";

    $query="select cardnumber, peoplename, creditlimit, ROUND(cbalance,2) as cbalance, minpay from IVR_CardMember_Info
    where cardnumber not like '5127%'" ;


        $rs=odbc_exec($connStr,$query);
        $i = 1;
        while(odbc_fetch_row($rs))
        {   //echo "Test while";
            $cardnumber=odbc_result($rs, "cardnumber");
            $peoplename=odbc_result($rs, "peoplename");
            $creditlimit=odbc_result($rs, "creditlimit"); 
            $cbalance=odbc_result($rs, "cbalance"); 
            $minpay=odbc_result($rs, "minpay");


            $conn = mysqli_connect("server","user","pass","database");
            $sql= "INSERT INTO test_data(cardnumber, peoplename, creditlimit, cbalance, minpay) VALUES ('cardnumber', 'peoplename', 'creditlimit', 'cbalance', 'minpay') ";
            if(!(mysqli_query($conn,$sql))){
                //echo "Data Not Found";
                echo "<br>";

            }
            else{
                echo "Data Inserted"; 
                echo "<br>";
            }
            echo $i++ ;
        }

    echo "<br>";
odbc_close($connStr);

?>

How can I solve this?


Solution

  • If you really want to understand why you can't enter while() {...}, you need to consider the following.

    First, your call to odbc_connect(), which expects database source name, username and password for first, second and third parameter. It should be something like this (DSN-less connection):

    <?php
    ...
    $connStr = odbc_connect("Driver={MySQL ODBC 8.0 Driver};Server=server;Database=database;", "user", "pass");
    if (!$connStr) {
        echo 'Connection error';
        exit;
    }
    ...
    ?>
    

    Second, check for errors after odbc_exec():

    <?php
    ...
    $rs = odbc_exec($connStr, $query);
    if (!$rs) {
        echo 'Exec error';
        exit;
    }
    ...
    ?>