如何使用php从选择查询中插入数据

时间:2018-11-06 09:19:45

标签: php mysql while-loop insert-into

我想从另一个通过ODBC连接的数据库向mysql表插入数据,但是我无法进入while循环,这是我的代码- N.B:为了安全起见,我不提供数据库名称,用户名和密码。 ODBC连接声明为“ 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);

?>

我该如何解决?

2 个答案:

答案 0 :(得分:1)

如果您真的想了解为什么不能输入while() {...},则需要考虑以下内容。

首先,您致电odbc_connect(),该电话需要数据库源名称,用户名和密码作为第一个,第二个和第三个参数。它应该是这样的(无DSN连接):

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

第二,检查odbc_exec()之后的错误:

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

答案 1 :(得分:-1)

您可以使用SQL检查它here,例如:

     INSERT INTO test_data(cardnumber, peoplename, creditlimit, cbalance, minpay) 
     SELECT cardnumber, peoplename, creditlimit, 
     ROUND(cbalance,2) as cbalance, minpay from IVR_CardMember_Info
     where cardnumber not like '5127%'