Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 多张图片上传到Mysql数据库_Php_Mysql - Fatal编程技术网

Php 多张图片上传到Mysql数据库

Php 多张图片上传到Mysql数据库,php,mysql,Php,Mysql,我可以上传一张图片并存储到mysql中,但如何上传和存储多张图片,就像我想上传3张图片并存储到数据库中一样? 这里是我上传一张图片并存储到数据库的代码: 在我的sql列名上:kodem、tipe、images1、images2、images3 <!DOCTYPE html> <?php include("koneksi.php"); if(isset($_POST['Input'])) { $Kode = $_POST['Kode'];

我可以上传一张图片并存储到mysql中,但如何上传和存储多张图片,就像我想上传3张图片并存储到数据库中一样? 这里是我上传一张图片并存储到数据库的代码:

在我的sql列名上:kodem、tipe、images1、images2、images3

<!DOCTYPE html>
<?php
    include("koneksi.php");
    if(isset($_POST['Input'])) {    
        $Kode = $_POST['Kode'];
        $Tipe = $_POST['Tipe'];

        $file_name = $_FILES['images1']['name'];
        $file_size = $_FILES['images1']['size'];
        $file_tmp = $_FILES['images1']['tmp_name'];

        $file_ext = strtolower(end(explode(".", $file_name)));
        $ext_boleh = array("jpg", "jpeg", "png", "gif", "bmp");

            if(in_array($file_ext, $ext_boleh)) {
                $sumber = $file_tmp;
                $tujuan = "images/" . $file_name;
                move_uploaded_file($sumber, $tujuan);
                $sql = "insert into database_latihan values ('$Kode' , '$Tipe' , '$tujuan')";
                mysqli_query($koneksi, $sql);   
            }else  {
                echo "Only Images can be store!";
            }
    }
?>
<html>
<head>
    <title>Input Database</title>
</head>
<body>

<div>   
    <form id="adminform" action="" method="post" enctype="multipart/form-data">
    <table>
        <tr>
            <td>Kode </td>
            <td><input type="text" name="Kode" placeholder="CAR/STH/STC" /><br /></td>
        </tr>
        <tr>
            <td>Tipe  </td>
            <td><select name = "Tipe">
                  <option value="Cardio">Cardio</option>
                  <option value="Strength">Strength</option>
                  <option value="Stretching">Stretching</option>
            </select><br /></td>
            <td rowspan="1">
                    <input type="file" id="upload" name="images1">
            </td>
        </tr>
        <tr>
            <td><input type="submit" name="Input" value="Input" /></td>
            <td><input type="submit" name="reset" value="Reset" /></td>
        </tr>
    </table>
    </form>
</div>
</body>
</html>


您可以添加3个输入

<td rowspan="1">
    <input type="file" id="upload" name="images1[]">
</td>
<td rowspan="1">
    <input type="file" id="upload" name="images1[]">
</td>
<td rowspan="1">
    <input type="file" id="upload" name="images1[]">
</td>
无论哪种方式,您都将获得一个
$\u FILES['images1']
,它现在是一个数组

然后您的PHP代码只需要在$\u文件数组上循环

<?php
    include("koneksi.php");
    if(isset($_POST['Input'])) {
        $Kode = $_POST['Kode'];
        $Tipe = $_POST['Tipe'];

        // you should really be checking for upload errors
        foreach ($_FILES['images1']['error'] as $err) {
           switch ($err) {
              case UPLOAD_ERR_NO_FILE:
                  echo 'No file sent.';
                  exit;
              case UPLOAD_ERR_INI_SIZE:
              case UPLOAD_ERR_FORM_SIZE:
                  echo 'Exceeded filesize limit.';
                  exit;
            }
        }

        for($x=0; $x<count($_FILES['images1']['tmp_name']); $x++ ) {

            $file_name = $_FILES['images1']['name'][$x];
            $file_size = $_FILES['images1']['size'][$x];
            $file_tmp  = $_FILES['images1']['tmp_name'][$x];

            $t = explode(".", $file_name);
            $t1 = end($t);
            $file_ext = strtolower(end($t));

            $ext_boleh = array("jpg", "jpeg", "png", "gif", "bmp");

            if(in_array($file_ext, $ext_boleh)) {
                $sumber = $file_tmp;
                $tujuan = "images/" . $file_name;
                move_uploaded_file($sumber, $tujuan);

                $sql = "insert into database_latihan values ('$Kode' , '$Tipe' , '$tujuan')";
               mysqli_query($koneksi, $sql);
            }else  {
                echo "Only Images can be store!";
            }
        } // endfor
    }
?>

这个问题很好

使用1个输入多个项目将多个图像上载到带有预览(readAsDataURL)的数据库中 database.sql

CREATE TABLE IF NOT EXISTS `database_latihan` (
`id` tinyint(3) NOT NULL,
  `kode` varchar(10) NOT NULL,
  `tipe` varchar(50) NOT NULL,
  `images1` varchar(100) DEFAULT NULL,
  `images2` varchar(100) DEFAULT NULL,
  `images3` varchar(100) DEFAULT NULL,
  `images4` varchar(100) DEFAULT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

ALTER TABLE `database_latihan`
 ADD PRIMARY KEY (`id`);

ALTER TABLE `database_latihan`
MODIFY `id` tinyint(3) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;
koneksi.php

<?php

  $hostname = "localhost";
  $database = "database";
  $port     = '3306';

  $username = "root";
  $password = "";

  try 
  {

    /* set server */            
    $server = "mysql:host=$hostname;dbname=$database;port=$port";

    /* set attribute */             
    $setAttribute = array(
                           PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
                           PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                           PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                         );

    $conn = new PDO($server, $username, $password, $setAttribute);

    /* set the PDO error mode to exception */
    //$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  }

  catch(PDOException $e)
  {

    echo "Connection failed: " . $e->getMessage();

  }

?>



upload.php

<?php                       

  $file_dir  = "images/";

  /* Check if folder not exists, then create it */
  if (!file_exists($file_dir)) {
    mkdir($file_dir, 0777, true);
  }

  if (isset($_POST["Input"])) {

    /* conversi multi array */
    function diverse_array($array) { 
      $result = []; 
      foreach($array as $key1 => $value1) 
        foreach($value1 as $key2 => $value2) 
          $result[$key2][$key1] = $value2; 

      return $result; 
    }

    $file_multi  = diverse_array($_FILES['upload']);

    for ($y = 0; $y < 4; $y++) {    
      $image[$y] = '';
    }

    /* loop multi file */           
    for ($x = 0; $x < count($file_multi); $x++) {

      /* loop array file $_FILES */                 
      foreach ($file_multi[$x] as $key => $value) {

        $file_name   = $file_multi[$x]['name'];
        $file_size   = $file_multi[$x]['size'];
        $file_tmp    = $file_multi[$x]['tmp_name'];

        $file_target = $file_dir . $file_name;

        $errors = array();  

        /* Check current file formats with file secure */
        $file_secure  = array('jpg', 'jpeg', 'png', 'gif', 'bmp');                  
        $file_current = strtolower(pathinfo($file_name, PATHINFO_EXTENSION)); /* (end(explode('.', $file_name) */

        if (in_array($file_current, $file_secure) === false) {
          $errors[] = "Sorry, <strong>{$file_current}</strong> extension not allowed";      
        }

      }

      /* Check if Errors exist, then not upload. Or if Errors NOT exist, then try upload */
      if (!empty($errors)) {                            

        /* display error */                 
        foreach ($errors as $keyError => $valueError) {
          echo "$keyError = $valueError <br />";
        }                           

      } else {

        if (move_uploaded_file($file_tmp, $file_target)) {

          $image[$x] = $file_target;

          echo "<strong>{$file_name}</strong> has been uploaded." . "<br />";

        } else {

          echo "Sorry, there was an something wrong in <b>move_uploaded</b>.";

        }

      }                     

    }                   

    /* Check for error */
    if (!empty($errors)) {                          

      /* Check errors and display them */                   
      foreach ($errors as $keyError => $valueError) {
        echo "$keyError = $valueError <br />";
      }                     

    /* if everything is ok, try to upload file */
    } else {

      /* Insert Form Data into Database */
      $kode   = $_POST['Kode'];
      $tipe   = $_POST['Tipe'];
      $image1 = $image[0];
      $image2 = $image[1];
      $image3 = $image[2];
      $image4 = $image[3];

      require_once("koneksi.php");                  

      $sql = "INSERT INTO database_latihan (kode,
                                            tipe,
                                            images1,
                                            images2,
                                            images3,
                                            images4) 

                                    VALUES (:kode,
                                            :tipe,
                                            :image1,
                                            :image2,
                                            :image3,
                                            :image4)";

      $parameter = array(':kode'   => $kode,
                         ':tipe'   => $tipe,
                         ':image1' => $image1,
                         ':image2' => $image2,
                         ':image3' => $image3,
                         ':image4' => $image4);

      $query = $conn->prepare($sql);
      $query->execute($parameter);

      echo "Data succesfully inserted !!";

      $conn = null;
      /* Insert Form Data into Database || */

    }

  } else {

    //header("location: index.php");

  }

?>

<a href="index.php">Index</a>

问题是什么?你不能添加更多的
文件
字段并对其进行处理,或者做什么?是的,这是我需要的,你能帮我做一个例子吗?4张图片可以同时上传吗?存储在数据库中这都在手册中,你只需要做MySQL部分。是的,我需要php代码,你能用php实现吗?我想我会去做一些园艺工作@Fred ii-@RiggsFolly,这是一种弄脏你手的方法。只是不要去处理鳕鱼;在你现在洗手之前不可以;-)我得到了一些错误,4个全部图像,
大小写:错误、名称、大小和tmp_名称
酷,我还在等这个:)
<form id="adminform" action="upload.php" method="post" enctype="multipart/form-data">
  <table>
    <tr>
      <td>Kode </td>
      <td><input type="text" name="Kode" placeholder="CAR/STH/STC" /><br /></td>
    </tr>
    <tr>
      <td>Tipe  </td>
      <td>
        <select name = "Tipe">
          <option value="Cardio">Cardio</option>
          <option value="Strength">Strength</option>
          <option value="Stretching">Stretching</option>
        </select><br />
      </td>

    </tr>
    <tr>
      <td>Upload Images</td>
      <td rowspan="1">
        <input type="file" name="upload[]" onchange="previewFiles()" multiple />
      </td>
    </tr>
    <tr>
      <td></td>
      <td>
        <div id="preview"></div>
      </td>
    </tr>

    <tr>
      <td></td>                 
      <td><input type="submit" name="Input" value="Input" /><input type="submit" name="reset" value="Reset" /></td>
    </tr>
  </table>
</form>

    <!-- preview image -->          
    <script>
      function previewFiles() {

        var preview = document.querySelector('#preview');
        var files   = document.querySelector('input[type=file]').files;

        function readAndPreview(file) {

          /* Make sure `file.name` matches our extensions criteria */
          if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) {
            var reader = new FileReader();

            reader.addEventListener("load", function () {
              var image = new Image();

              image.height = 100;
              image.title = file.name;
              image.src = this.result;

              preview.appendChild( image );
            }, false);

            reader.readAsDataURL(file);
          }

        }

        if (files) {
          [].forEach.call(files, readAndPreview);
        }

      }         
    </script>
    <!-- preview image || -->

<hr />

        <table cellpadding="5" cellspacing="0" border="1">
          <tr bgcolor="#CCCCCC">
            <th>No.</th>
            <th>Kode</th>
            <th>Tipe</th>
            <th>Image 1</th>
            <th>Image 2</th>
            <th>Image 3</th>
            <th>Image 4</th>
          </tr>

<?php

  require_once("koneksi.php");

  $result = $conn->prepare("SELECT * FROM database_latihan ORDER BY id DESC") or die($conn->error);
  $result->execute();
  $rows   = $result->fetchAll(); /* array of object

  /* cek, apakah hasil query di atas mendapatkan hasil atau tidak (data kosong atau tidak) */
  if ($result->rowCount() == 0) {

    echo '<tr><td colspan="7">Tidak ada data!</td></tr>'; /* menampilkan row data kosong */

  } else {  /* else ini artinya jika data hasil query ada */

    $no = 1;    /* membuat variabel $no untuk membuat nomor urut */

    foreach ($rows as $row) {   /* loop foreach */ ?>

      <tr>
        <td><?php echo $no; ?></td> <!-- menampilkan nomor urut -->
        <td><?php echo $row['kode']; ?></td>    <!-- menampilkan kode dari database -->
        <td><?php echo $row['tipe']; ?></td>    <!-- menampilkan tipe dari database -->
        <td><?php echo $row['images1']; ?></td> <!-- menampilkan image dari database -->
        <td><?php echo $row['images2']; ?></td> <!-- menampilkan image dari database -->
        <td><?php echo $row['images3']; ?></td> <!-- menampilkan image dari database -->
        <td><?php echo $row['images4']; ?></td> <!-- menampilkan image dari database -->                            
      </tr>

<?php     $no++;    /* menambah jumlah nomor urut setiap row */

    }

  }

      $conn = null;                                 

?>

<hr />
<a href="https://developer.mozilla.org" ><h3>mozilla.org</h3></a>           
<a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL" >FileReader.readAsDataURL()</a>
<a href="https://stackoverflow.com/questions/37375013/multiple-upload-images-into-mysql-database/47366585#47366585" >Multiple Upload Images into Mysql Database</a>
<hr />
<?php                       

  $file_dir  = "images/";

  /* Check if folder not exists, then create it */
  if (!file_exists($file_dir)) {
    mkdir($file_dir, 0777, true);
  }

  if (isset($_POST["Input"])) {

    /* conversi multi array */
    function diverse_array($array) { 
      $result = []; 
      foreach($array as $key1 => $value1) 
        foreach($value1 as $key2 => $value2) 
          $result[$key2][$key1] = $value2; 

      return $result; 
    }

    $file_multi  = diverse_array($_FILES['upload']);

    for ($y = 0; $y < 4; $y++) {    
      $image[$y] = '';
    }

    /* loop multi file */           
    for ($x = 0; $x < count($file_multi); $x++) {

      /* loop array file $_FILES */                 
      foreach ($file_multi[$x] as $key => $value) {

        $file_name   = $file_multi[$x]['name'];
        $file_size   = $file_multi[$x]['size'];
        $file_tmp    = $file_multi[$x]['tmp_name'];

        $file_target = $file_dir . $file_name;

        $errors = array();  

        /* Check current file formats with file secure */
        $file_secure  = array('jpg', 'jpeg', 'png', 'gif', 'bmp');                  
        $file_current = strtolower(pathinfo($file_name, PATHINFO_EXTENSION)); /* (end(explode('.', $file_name) */

        if (in_array($file_current, $file_secure) === false) {
          $errors[] = "Sorry, <strong>{$file_current}</strong> extension not allowed";      
        }

      }

      /* Check if Errors exist, then not upload. Or if Errors NOT exist, then try upload */
      if (!empty($errors)) {                            

        /* display error */                 
        foreach ($errors as $keyError => $valueError) {
          echo "$keyError = $valueError <br />";
        }                           

      } else {

        if (move_uploaded_file($file_tmp, $file_target)) {

          $image[$x] = $file_target;

          echo "<strong>{$file_name}</strong> has been uploaded." . "<br />";

        } else {

          echo "Sorry, there was an something wrong in <b>move_uploaded</b>.";

        }

      }                     

    }                   

    /* Check for error */
    if (!empty($errors)) {                          

      /* Check errors and display them */                   
      foreach ($errors as $keyError => $valueError) {
        echo "$keyError = $valueError <br />";
      }                     

    /* if everything is ok, try to upload file */
    } else {

      /* Insert Form Data into Database */
      $kode   = $_POST['Kode'];
      $tipe   = $_POST['Tipe'];
      $image1 = $image[0];
      $image2 = $image[1];
      $image3 = $image[2];
      $image4 = $image[3];

      require_once("koneksi.php");                  

      $sql = "INSERT INTO database_latihan (kode,
                                            tipe,
                                            images1,
                                            images2,
                                            images3,
                                            images4) 

                                    VALUES (:kode,
                                            :tipe,
                                            :image1,
                                            :image2,
                                            :image3,
                                            :image4)";

      $parameter = array(':kode'   => $kode,
                         ':tipe'   => $tipe,
                         ':image1' => $image1,
                         ':image2' => $image2,
                         ':image3' => $image3,
                         ':image4' => $image4);

      $query = $conn->prepare($sql);
      $query->execute($parameter);

      echo "Data succesfully inserted !!";

      $conn = null;
      /* Insert Form Data into Database || */

    }

  } else {

    //header("location: index.php");

  }

?>

<a href="index.php">Index</a>