doujiaohuo1096 2015-06-04 18:06
浏览 26
已采纳

数据库值与数据流不匹配

For some odd reason, some database values do not match the datastream. It is not for every entry although. For instance a line from my CSV file is below.

00-1751,P,1649.95,1649.95,1237.00

And somehow in my DB the same entry reads

00-1751,P,999.99,999.99,999.99

My code for dumping into the DB is below:

function dump($csvFile, $conn){
if(($handle = fopen($csvFile, 'r')) !== false) {

    $header = fgetcsv($handle);
    $id = 0;

    $sql = "TRUNCATE TABLE inv_price";
    $sth = $conn->prepare($sql);
    $sth->execute();


    while(($data = fgetcsv($handle)) !== false) {
        $sql = "INSERT INTO `inv_price` (sku, part_status, msrp, curr_sugg_retail, your_price) 
                VALUES ('$id', '$data[0]', '$data[1]', '$data[2]', '$data[3]')";
        print_r($data);
    try{
        $conn->query($sql);

    }
    catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }

        $id++;
    }
    fclose($handle);
}
}

The $data printed to the console matches the CSV file. I am not sure how or why certain rows are changing the value to 999.99.

  • 写回答

1条回答 默认 最新

  • duanhongqiong9460 2015-06-04 18:21
    关注

    Most likely explanation for this behavior is that the column is defined as datatype DECIMAL(5,2), which allows for only three digits before the decimal point. And the error/warning is being ignored.

    The value being stored in the column the maximum value that can be stored in that datatype. We observe similar behavior with integer values as well.

    SQL Fiddle Here http://sqlfiddle.com/#!2/a7577f/1

    create table foo (col52 DECIMAL(5,2), col72 decimal(7,2));
    insert ignore into foo (col52, col72) values (1234.56, 1234.56);
    
    select * from foo;
    
    col52   col72
    ------  -------
    999.99  1234.56
    

    On an entirely different note, the code appears to be vulnerable to SQL injection.

    Curiously, the TRUNCATE TABLE statement is a prepared statement, but the INSERT is not.

      $sql = 'INSERT INTO `inv_price` (sku, part_status, msrp, curr_sugg_retail, your_price) 
              VALUES (?, ?, ?, ?, ?)';
    
      $sth=conn->prepare($sql);
      $sth->bindParam(1,$id);
      $sth->bindParam(2,$data[0]);
      $sth->bindParam(3,$data[1]);
      $sth->bindParam(4,$data[2]);
      $sth->bindParam(5,$data[3]);
      $sth->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!