douzhuang1900 2014-06-21 11:04
浏览 52
已采纳

使用更新插入查询将.csv值插入数据库

i have a .csv file where its data get inserted into database,but my code has a drawback like

if my .csv file contain a row and its inserted in db then to insert more row the user should remove that 1st row from .csv and put new row value then it will insert else duplicate key entry as a column in my db have unique key.

my code for inserting .csv to mysql.

<?php
//db connection goes here
$csv_file="/var/www/html/141.csv";
 $savefile="141.csv";
  $handle = fopen($csv_file, "r");

$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($i>0){
$import="INSERT into  lead141(urn,phone)values('".addslashes($data[0])."','".addslashes($data[1])."')";
mysql_query($import) or die(mysql_error());
}
$i=1;
}

$test="select * from lead141
where phone in (select phone from dnc)";
$query=mysql_query($test);
$testing=count($query);
echo "matched rows".$testing; 

?>   

my mysql lead141table structure

    CREATE TABLE `lead141` (
 id int(100) NOT NULL AUTO_INCREMENT,
 urn int(100) NOT NULL,
 phone bigint(20) NOT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `phone` (`phone`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1

my 141.csv file

urn    phone
141     20134325
141     20985675

if i run my code 141.csv inserting into database but when a user is adding new rows in 141.csv the user should remove the previous rows and add new rows to 141.csv for inserting.

i need to make my code work to insert new values from 141.csv to db evenif the old values are present in .csv.i think if i put a update statement and then insert then it will do the trick.

am i into right path for the logic? please help

  • 写回答

2条回答 默认 最新

  • dongzhi6927 2014-06-21 11:19
    关注

    Try to use INSERT ... ON DUPLICATE KEY UPDATE Syntax like this:

    $import="INSERT INTO lead141(urn,phone)values('".addslashes($data[0])."','".addslashes($data[1])."') ON DUPLICATE KEY UPDATE phone= '".addslashes($data[1])."'";
    

    Because phone column is UNIQUE KEY.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路