PHP中txt匯入mysql代碼

來源:互聯網
上載者:User

注意在匯入時保持資料庫教程的編碼與txt文檔編碼盡量一樣,要不可能出現亂碼問題哦。

<?php教程
  //驗證檔案類型和錯誤
if($_FILES["insert_first"]["type"] == "text/plain"){
    echo "第一步:檔案類型上傳正確"."<br/>";
        if($_FILES["insert_first"]["error"]){
          echo "上傳錯誤:".$_FILES["insert_first"]["error"]."<br/>";
        }else{
          echo "檔案名稱:".$_FILES["insert_first"]["name"]."<br/>";
          echo "檔案類型:".$_FILES["insert_first"]["type"]."<br/>";
          echo "檔案大小:".($_FILES["insert_first"]["size"]/1024)."Kb<br/>";
          echo "臨時名稱:".$_FILES["insert_first"]["tmp_name"]."<br/>";
        }       
  }else{
    echo "上傳檔案格式不正確";
        exit;
}

//串連資料庫
$con = new mysql教程i('localhost','s503440db0','td9928ps教程','s503440db0');
if(mysqli_connect_errno()){
  echo "連結資料庫失敗";
  exit;
}
 
 
//開啟檔案
$file = fopen($_FILES["insert_first"]["tmp_name"],"r") or exit("開啟檔案失敗!");

var_dump($file);
echo "<br/>";

while(!feof($file)){ 
  //逐行分拆
  $row = explode(",",fgets($file));
  $row0 = $row[0];
  $row1 = (string)$row[1];
  echo "$row0"."---"."$row1"."<br/>";

  //判斷記錄是否存在
        $query1 = "select firstid from firstcategory where firstid=$row0";
        $query2 = "select firstname from firstcategory where firstname='$row1'";
        $result1 = $con->query($query1);
        $result2 = $con->query($query2);
    //判斷行數
        $result1 = mysqli_num_rows($result1);
        $result2 = mysqli_num_rows($result2);

                 
    if($result1){
          echo "行號{$row0}已存在<br/>";
        }elseif($result2){
          echo "分類{$row1}已存在<br/>";
        }else{
          $query = "insert into firstcategory (firstid,firstname) values ($row0,'音樂')";
          $result = $con->query($query);
        }
}
echo "匯入結束,請檢查資料是否正確 http://www.111cn.net ";


fclose($file);
$con->close();

?>

mysql資料庫

"create table firstcategory (
          firstid int unsigned not null primary key,
                  firstname char(50) not null               
                )";

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.