我准备撕掉我的头发了。
基本上我必须创建一个页面来读取文件目录并创建一个表单,允许您按下每个文件名旁边的“导入”按钮将文件导入数据库。
我在这样的目录中扫描:
$files=scandir('uploads');//get array of files/directories in uploads
foreach($files as $file) {//loop through the array
if(!is_dir($file)) {//if not a directory must be a file
echo $file.'<input type="submit" value="Import CSV File" name="'.$file.'" >';
}
}
而不是以相同的形式(一种形式)我做:
$files=scandir('uploads');//get array of files/directories in uploads
foreach($files as $file) {//loop through the array
if(!is_dir($file)) {//if not a directory must be a file
if(isset($_POST[$file])) {//this if never hits
echo 'aa';
exit();
}
}
}
当我点击按钮导入文件时,我可以通过我的评论看到if(isset($_POST[$file]))
从未点击过...
我不知道为什么......
以下是页面上的更多代码,以便更好地全面理解
import_csv.php:
<?php
if(session_id()=='') {
session_start();
}
// check if user is not logged in thus is most likely not allowed to view the page or login went wrong
if(!isset($_SESSION['loggedin'])||$_SESSION['loggedin']===false) {
echo '<p>You are not logged in. Please <a href="index.php">login</a> and try again.</p>';
exit();//stops the execution of the php file so we dont show the links below to unauthorized visitors
}
$files=scandir('uploads');//get array of files/directories in uploads
foreach($files as $file) {//loop through the array
if(!is_dir($file)) {//if not a directory must be a file
if(isset($_POST[$file])) {
echo 'aa';
exit();
}
}
}
?>
<h2 align="center">Import CSV Files:</h2>
<p align="center">
This will allow you to view names of uploaded CSV files and import them into the database.
Below are a list of available files on the server to be imported:
</p>
<form method="post" action="import_csv.php">
<?php
//Create connection and suppress any errors for now using @
$con=@mysqli_connect('localhost','jd','1111','my_db');
// Check connection
if (mysqli_connect_errno($con)) {
echo 'Could not connect to database.';
exit();
}else {
//query all tables in db
$sql = "SHOW TABLES FROM my_db;";
$result = mysqli_query($con,$sql);
//loop through results/all tables
while ($row = mysqli_fetch_row($result)) {
if($row[0]=='users'&&isset($_SESSION['user_type']) && $_SESSION['user_type']!='admin') {
}else {
echo '<input type="checkbox" name="'.$row[0].'" > '.$row[0].'<br></br>';
}
}
}
$files=scandir('uploads');//get array of files/directories in uploads
foreach($files as $file) {//loop through the array
if(!is_dir($file)) {//if not a directory must be a file
echo $file.'<input type="submit" value="Import CSV File" name="'.$file.'" >';
}
}
?>
</form>
答案 0 :(得分:3)
这是因为文件扩展问题,文件扩展名应始终为'。',但php将其转换为'_'。然后请重写您的代码,
$files=scandir('uploads');//get array of files/directories in uploads
foreach($files as $file) {//loop through the array
$postName = str_replace('.','_',$file);
if(isset($_POST[$postName])) {//if not a directory must be a file
echo 'aa';
exit();
}
}
这里$ file应该像file.csv,但PHP REQUEST数组包含$ _POST [file_csv]