从txt文件中提取数据并插入数据库

时间:2015-09-17 07:49:51

标签: php mysql database

我想从名为domains.txt的txt文件中提取数据,并将该文件的内容插入到数据库中。下面是我写的代码但是没有用。请帮帮我

<?php

$conn = mysql_connect("localhost","root","");
if (!$conn) {
    die("Could not connect: " . mysql_error());
}
mysql_select_db("modify_domains");
$file = fopen("domains.txt", "r");

    // Read line by line until end of file
    while (!feof($file)) { 

    // Make an array using comma as delimiter
       $array = explode(",",fgets($file)); 
        $domain_name=$array[0];
        $reg_email=$array[1];
        $tech_email=$array[2];
        $billing_email=$array[3];
        $admin_email=$array[4];
        $password=$array[5];
    $sql = "INSERT INTO tbl_domains (domain_name, reg_email, tech_email,billing_email,admin_email,password) VALUES('".$adomain_name"','".$reg_email."',".$tech_email.",".$billing_email.",".$admin_email.",".$password.")";   
    mysql_query($sql,$conn)  or die("Could not connect: " . mysql_error());
    // use mysql insert query here
}

?>

1 个答案:

答案 0 :(得分:0)

所有文本字段必须用单引号分隔(例如'“。$ reg_email。”')并且不要忘记分隔文本字段和变量的点。

查询应该是这样的:

$sql = "INSERT INTO tbl_domains 
(domain_name, reg_email, tech_email,billing_email,admin_email,password) VALUES
('".$adomain_name."','".$reg_email."','".$tech_email."','".$billing_email."','".$admin_email."','".$password."')"; 

所有文本字段必须用单引号分隔。你也可以这样写:

 $sql = "INSERT INTO tbl_domains 
    (domain_name, reg_email, tech_email,billing_email,admin_email,password) VALUES
    ('$adomain_name','$reg_email','$tech_email','$billing_email','$admin_email','$password')";