Upload multiple files to MySql database in PHP development (1)

In the previous chapter, we introduced the tutorial of uploading a file using PHP.

Friends will have questions, how can I upload multiple files to the database?

The key point is to put in several files and click submit to upload. Then all the files will be uploaded together, and each file will be given a new path.

2276.jpg

Provide an idea:

First get the information of each uploaded file and put it into a custom array

<?php
    $uploadFiles = array();
?>

Then pass The foreach loop is displayed

<?php
    foreach($upfile as $key =>$value) {
      foreach($value as $k => $v){
        $uploadFiles[$k][$key]=$v;
      }
    }
    print_r($uploadFiles);
?>

The result display is similar

<?php
/* 这里展示同时上传2个文件信息
Array
(
    [0] => Array
        (
            [name] => 1.png
            [type] => image/png
            [tmp_name] => C:\Windows\php82E9.tmp
            [error] => 0
            [size] => 65646
        )
    [1] => Array
        (
            [name] => 2.png
            [type] => image/png
            [tmp_name] => C:\Windows\php82EA.tmp
            [error] => 0
            [size] => 70463
        )
)
*/
?>

The last step is to put the restrictions on publishing a file demonstrated in the previous chapter into the loop for judgment

Get The random file name uses the current time as the prefix of the new file name, and is recombined with the suffix name into the database.

<?php
    //上传后的文件名定义(随机获取一个文件名(保持后缀名不变))
    $fileinfo = pathinfo($v["name"]);//解析上传文件名字
    do{
      $newfile = date("Y-m-d,H-i-s") . rand(1000, 9999) . "." . $fileinfo["extension"];
    } 
    while (file_exists($path . $newfile));
?>

Of course, linking to the database table and uploading files is also an essential link

<?php
    $link = mysqli_connect('localhost','username','password') or die("数据库连接失败!");
    mysqli_select_db($link,'test');
    mysqli_set_charset($link,'utf8');
    
    $filepath = $path.$newfile;
    $name = $v['name'];
    $size = $v['size'];
    $sql = "insert into img(id,name,size,pic) value(null,'$name','$size','$filepath')";
    mysqli_query($link,$sql);
    mysqli_close($link);
?>


Continuing Learning
||
<?php $link = mysqli_connect('localhost','username','password') or die("数据库连接失败!"); mysqli_select_db($link,'test'); mysqli_set_charset($link,'utf8'); $filepath = $path.$newfile; $name = $v['name']; $size = $v['size']; $sql = "insert into img(id,name,size,pic) value(null,'$name','$size','$filepath')"; mysqli_query($link,$sql); mysqli_close($link); ?>
submitReset Code