用php將某個 檔案夾下的所有檔案的 檔案名稱存入MySQL資料庫中

來源:互聯網
上載者:User

實現:用php將某個 檔案夾下的所有檔案的 檔案名稱存入MySQL資料庫中

注意:輸入為一個檔案夾A,如果這個檔案夾中含有其他的檔案夾B,則不顯示B中的檔案,只顯示A中的檔案。
 
源碼如下:

<?php
//功能:將檔案夾下的所有檔案的檔案名稱存入mysql資料庫中
//設定資料庫
 $server='localhost';
 $user='root';
 $passwd='password';
 $port='3306';
 $dbname='dbname';
 $link=mysql_connect($server,$user,$passwd);
 if (!$link) {
  die('Could not connect: ' . mysql_error());
 }
 else echo 'Connected successfully';
 $start=time();
 mysql_select_db("catx",$link);//選擇資料庫名稱。
 //php函數體 
 function listDir($dir){
 $cout=0;
  if(is_dir($dir)){
   if($dh= opendir($dir)) {
    while(($file= readdir($dh)) !== false){
     if($file!="."&& $file!=".."){
     $file=mb_convert_encoding ($file,'UTF-8','GBK');//轉換編碼,因為中文windwows檔案名稱的編碼是GBK格式的
     //var_dump($file);
     $re=explode(".",$file);//分解檔案名稱
     $res=$re[0];  //不要檔案尾碼名,取出檔案名稱
     $sql="insert into table_name(name) values('".$res."');";
     mysql_query($sql);
     $cout++;
     echo $res."<br>";
     }
    }
   closedir($dh);
   }
  }
  return $cout;
 } 
  //此處輸入待處理的檔案夾路徑
  $cout=listDir("E:/data");
 $end=time();
 $time=$end-$start;
 echo "cout:".$cout."<br>";
 echo "starttime:".$start."<br>";
 echo "endtime:".$end."<br>";
 echo $time."<br>";
 mysql_close($link);
?>

相關文章

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.