dt614037527
dt614037527
2014-01-21 22:20

使用php将每个数组元素发送到数据库

I have an array like this

$a = scandir($dir)

It contains a list of folders in a directory. How can I store each element of the array as a new record in a database table? The only methods I have found so far convert the array to one long string.

I have tried

foreach($array as $item)
send each item to database 

But I receive the error " Notice: Undefined variable"

Full Code

$dir = "/some/folder";

// Sort in ascending order
$a = scandir($dir);

$string_version = implode(',', $a);

$array = explode(' ', $string_version);


foreach($array as $item)
{


$dbcon="INSERT INTO $DBTable(Column) VALUES('$item')";


}

?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dry69034 dry69034 7年前

    scandir() returns an array already, why are you converting it to a string then back to an array? also your new array will be undefined because the delimiters are different.

    This should be sufficient to iterate through the array results:

    $dir = "/some/folder";
    
    // Sort in ascending order
    $array = scandir($dir);
    
    foreach($array as $item)
    {
    
    
    $dbcon="INSERT INTO $DBTable(Column) VALUES('$item')";
    /*
    I AM ASSUMING THAT YOU UNDERSTAND THAT YOUR SQL QUERY IS NOT DOING ANYTHING YET since you haven't called mysqli_query();
    Also - have you defined the connection??
    */
    
    
    }
    
    ?>
    
    点赞 评论 复制链接分享
  • dongzhuo5425 dongzhuo5425 7年前

    $array is not defined. Your array variable is called $a.

    点赞 评论 复制链接分享