php - Inserting multiple images in mysql, also inserts multiple rows -


i searched google on place answer can't seem find right 1 i'll try here.

i want store users' firstname, lastname , path of images in mysqli database , image in folder uploads. (the user can upload multiple images)

this works , no problem.

the issue is:

when example type firstname , lastname , select 2 images , press upload button uploads creates 2 rows exact same values.

i want store everyting in 1 row, see code below:

<?php  $con = mysqli_connect('localhost','root','','img_db'); mysqli_select_db($con,'img_db');  $rn = mt_rand();  if(isset($_post['submit'])&& isset($_files['image'])&& !empty($_post['firstname'])&& !empty($_post['lastname'])) {     $firstname = $_post['firstname'];     $lastname = $_post['lastname'];      for($i=0; $i<count($_files['image']['name']); $i++)     {         $tmp_name = $_files['image']['tmp_name'][$i];         $max_size = 100000;         $path = "uploads/";           $name = $_files['image']['name'][$i];         $size = $_files['image']['size'][$i];         $type = $_files['image']['type'][$i];          $ext = strtolower(substr($name, strpos($name, '.') +1));         $name = str_replace('_','',trim($name));         $name = str_replace('-','',trim($name));         $name = str_replace(' ','',trim($name));          $name = str_replace('__','',trim($name));          if(($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')&&($type=='image/jpeg' || $type=='image/png' || $type=='image/gif')&&$size<=$max_size)         {                if(move_uploaded_file($_files['image']['tmp_name'][$i], $path.$rn.$name))              {                  mysqli_query($con,"insert `img` (firstname,lastname,url) values('$firstname','$lastname','$rn$name')");             }         }// end ext      }// end loop  }// end if isset post submit  ?> 

suggestion 1

one solution store uploaded file urls in array (declared before for loop) , utilize array outside of for loop, so:

if (isset(/* ... */)) {   // outside loop   $files = array();    (/* .. */) {      // doing things      if (/* $ext stuff */) {       if (move_uploaded_file(/* ... */))       {         $files[] = $rn.$name;       }     } // end ext   } // end    // utilize $files array determine how want store of these urls in 1 field.   // let's created variable called $store desired representation.   mysqli_query($con,"insert `img` (firstname,lastname,url) values('$firstname','$lastname','$store')");  } // end isset 

suggestion 2

you use two-table structure (one table users, 1 table images) , create foreign key relation each image table row user table row via desired user's primary key.

see: http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -