1

i can upload 1 image and store into mysql, but how to upload and store more than 1 image like i want upload 3 images and store into database? here my code for upload 1 image and store into database :

On my sql column name: 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
  • And what is the question? You can't add more file fields and process them or what? Commented May 22, 2016 at 13:35
  • yes thats i need, can you help me for make it example 4 images can be upload in same time? and store in database Commented May 22, 2016 at 13:39
  • It's all in the manual php.net/manual/en/function.move-uploaded-file.php you just need to do the MySQL part. Commented May 22, 2016 at 13:43

2 Answers 2

2

You can either add 3 inputs

<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>

Or make your one input allow multiple inputs

<td rowspan="1">
    <input type="file" id="upload" multiple name="images1[]">
</td>

Either way you will then get a $_FILES['images1'] that is now an array

Then your PHP code just needs to loop over the $_FILES array

<?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
    }
?>
Sign up to request clarification or add additional context in comments.

8 Comments

yes i need php code, could you please implement in php too?
Think I will go and do some gardening @Fred-ii-
@RiggsFolly that's one way of getting your hands dirty. Just don't go handling cod; not before you wash your hands now ;-)
i got some error, 4 all images ,case:error , name, size, and tmp_name
Cool, im still wait for this :)
|
0

This question is great ..

Project upload multi image into database with preview (readAsDataURL) using 1 input multiple

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();

  }

?>

index.php

<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 />

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.