如何使用php从select查询插入数据

5anewei6  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(388)

我想从另一个通过odbc连接的数据库向mysql表插入数据。但是我不能进入while循环,这里是我的代码-n.b:为了安全起见,我不提供db name、user和pass。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);

?>

我怎样才能解决这个问题?

qltillow

qltillow1#

如果你真的想知道为什么你不能进入 while() {...} ,您需要考虑以下几点。
首先,调用odbc\u 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\u exec()之后的错误:

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

bnlyeluc2#

您可以使用sql在此处进行检查,例如:

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%'

相关问题