dsa122870 2014-12-03 08:58
浏览 44

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

I am completely new to PHP but have had to learn what I can really quick for something at work. I am trying to create a form which then saves the answers to a row in a database and the images on the server. The below code is from tutorials etc. across the net with my additions in there. I think I'm 90% there apart from saving the image URLs in the database. I'm guessing it's something wrong in the "foreach" section in the code.

What I would like to achieve is to save each file upload URL in a column in the database. At present I've only created the imageurl field but I'm guessing I would need imageurl2 etc. I've tried searching for the next part but cannot find it. I'm assuming what I really need to achieve is a way for the code to call up all of the multiple file upload URLs (array) and then do the SQL insert after?

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 Code - I've replaced the database connection details with "xxx" however I'm connecting fine on my code

<?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;
}

?>

</div>
  • 写回答

1条回答 默认 最新

  • douhu3424 2014-12-03 09:08
    关注

    Updated

    <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 creates an array of the files uploaded with the given INPUT's name. This variable will always be an array within PHP.

    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)