使用PHP将多个文件上载字段URL转换为SQL数据库

时间:2014-12-03 08:58:44

标签: php mysql

我对 PHP 完全不熟悉,但必须了解我能够快速完成工作的内容。我正在尝试创建一个表单,然后将答案保存到数据库中的行和服务器上的图像。下面的代码来自网上的教程等,我在那里添加了。我认为除了保存数据库中的图像URL之外我还有90%。我猜测代码中的“ foreach ”部分出了问题。

我想要实现的是将每个文件上传URL保存在数据库的一列中。目前我只创建了imageurl字段,但我猜我需要imageurl2等。我已经尝试搜索下一部分但找不到它。我假设我真正需要实现的是一种方法,让代码调用所有多个文件上传URL(数组),然后执行 SQL 插入?

HTML code:

<form action="form.php" method="post" enctype="multipart/form-data">
  <label>Date:</label>
    <br>
    <input name="date" type="date">
    <label>Name:</label>
    <br>
    <select name="visitor">
      <option value="name1">Name One</option>
      <option value="name2">Name Two</option>
    </select>
    <label>Pub:</label>
    <br>
    <select name="pub">
      <option value="pubOne">Pub One</option>
      <option value="pubTwo".Pub Two</option>
    </select>
    <label>Comment:</label>
    <br>
    <textarea cols="30" rows="5" name="comment"></textarea>
    <label>Upload Image:</label>
    <br>
    <input name="fileToUpload[]" type="file" multiple="">
    <input class="formbtn" type="submit" value="Submit">
</form>

PHP代码 - 我用“xxx”替换了数据库连接详细信息但是我的代码连接正常

<?php
print_r($_POST);
$servername = 'xxx';
$username = 'xxx';
$password = 'xxx';
$dbname = 'xxx';

// Create connection to server
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "<div><center><h1>Connected successfully</h1></center></div>";

// Get all the values from input
    $date = $_POST['date'];
    $visitor = $_POST["visitor"];
    $pub = $_POST['pub'];
	$comment = $_POST['comment'];

date_default_timezone_set('UTC');
if (!file_exists("uploads/" .date('Y') . '/' .date('m') . '/')) {
    mkdir("uploads/" .date('Y') . '/' .date('m') . '/', 0777, true);
}

require_once('ImageManipulator.php');

foreach($_FILES['fileToUpload']['tmp_name'] as $key => $tmp_name) {
	
	if ($_FILES['fileToUpload']['error'][$key] > 0) {
    // Insert data into table
		$sql = "INSERT INTO visits (date, visitor, pub, comment)
		VALUES ('$date', '$visitor', '$pub', '$comment')";
	} else {

	$image_mime = image_type_to_mime_type(exif_imagetype($_FILES['fileToUpload']['tmp_name'][$key]));
	$allowedFiles = array("image/png","image/jpeg","image/gif");
	echo "File type:" . $image_mime . "<br>";
	if(!in_array($image_mime, $allowedFiles)){
    echo "The picture is not allowed.<br>";
	} else
	{
        $newNamePrefix = time() . '_';
        $manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name'][$key]);
        // resizing to 200x200
        $newImage = $manipulator->resample(200, 200);
        // saving file to uploads folder
		$target_dir = "uploads/" .date('Y') . '/' .date('m') . '/';
		$target_file = $target_dir .date('Ymd-his') . '-' . $visitor . '-' . basename($_FILES["fileToUpload"]["name"][$key]);
        $manipulator->save($target_file);
		// Insert data into table
		$sql = "INSERT INTO visits (date, visitor, pub, comment, imageurl) VALUES ('$date', '$visitor', '$pub', '$comment', '$target_file')";
		echo 'Image resized and uploaded!<br>';
    }
}
}

if ($conn->query($sql) === TRUE) {
    echo "<p>New record created successfully</p>";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

?>

1 个答案:

答案 0 :(得分:0)

已更新

<form method="post" action="upload.php" enctype="multipart/form-data">
  <input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>

if(count($_FILES['uploads']['filesToUpload'])) {
    foreach ($_FILES['uploads']['filesToUpload'] as $file) {

        //do your upload stuff here
        echo $file;

    }
}

php创建一个使用给定INPUT名称上传的文件数组。这个变量永远是PHP中的一个数组。