我要把CSV的数据导入到数据库中,并且在导入的时候随机从文件中取一张图片路径存入数据库,在导入的时候只有第一条数据导进数据库,其他数据没有导入,相关代码如下<?php
$fname = $_FILES['MyFile']['name'];
$do = copy($_FILES['MyFile']['tmp_name'],$fname);
if ($do)
{
echo"导入数据成功
";
} else {
echo "";
}
?>
<?
error_reporting(0);
//导入CSV格式的文件
$connect=mysql_connect("localhost","root","") or die("could not connect to database");
mysql_select_db("student",$connect) or die (mysql_error());
mysql_query("set names gb2312"); 
$fname = $_FILES['MyFile']['name'];
$handle=fopen("$fname","r");while($data=fgetcsv($handle,10000,","))
{
if($data[1]=='男')
{
$dir="img/men/";
}
elseif($data[1]=='女')
{
$dir="img/women/";
}
else
{
$dir="img/men/";
}
//
//
//
//取出文件夹中的内容存为数组
//$dir="img/men/"; //路径 
//PHP遍历文件夹下所有文件 
$handle=opendir($dir."."); 
//定义用于存储文件名的数组
$array_file = array();
while (false !== ($file = readdir($handle))) 

if ($file != "." && $file != "..") 

$array_file[] = $file; //输出文件名 


//PHP读取一个文件夹内有多少个文件
//用以随机生成以上数组文件名的KEY值
$handle = opendir($dir);
$i = 0;
while(false !== $file=(readdir($handle)))
{
    if($file !== '.' && $file != '..')
    {
        $i++;
    }
}
closedir($handle);
$h = $i-1;
$randnum=rand(0,$h);
$imgrand="$dir"."$array_file[$randnum]";
$q="insert into student_info (name,sex,photo) values ('$data[0]','$data[1]','$imgrand')";mysql_query($q) or die (mysql_error());
}
fclose($handle);
?>
<form ENCTYPE="multipart/form-data" ACTION="<?php echo"".$PHP_SELF.""; ?>" METHOD="POST">导入CVS数据 <input NAME="MyFile" TYPE="file"> <input VALUE="提交" TYPE="submit">
</form>

解决方案 »

  1.   

    while(false !== $file=(readdir($handle)))
    {
      if($file !== '.' && $file != '..')
      {
      $i++;
      }
    } // <=== 到这里 while 循环就结束了
    closedir($handle);
    $h = $i-1;
    $randnum=rand(0,$h);
    $imgrand="$dir"."$array_file[$randnum]";
    $q="insert into student_info (name,sex,photo) values ('$data[0]','$data[1]','$imgrand')";mysql_query($q) or die (mysql_error());// <<=== 这个插入是在循环外进行的
    }
    fclose($handle);
      

  2.   

    谢谢二楼的帮助,一楼的回答正解,就是因为几个$handle冲突了,最后的fclose($handle);
    中的$handle取到循环里面的值了就跳出循环了,我把$handle的命名该了下就好了