Click here to Skip to main content
15,888,733 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
 am new to PHP and MySQL and I will really need some assistance. Whenever I fill in all the information and submit my form, It successfully adds all information to the database. But the only issue is at the level of the images. When I upload two or more images, it only adds one image to the database and my upload file.

Any Idea on what's wrong?


What I have tried:

Here is my PHP CODE
PHP
public function adInsert($data, $file){
      $title = mysqli_real_escape_string($this->db->link, $data['title']);
       $catId = mysqli_real_escape_string($this->db->link, $data['catId']);
       $subcatId = mysqli_real_escape_string($this->db->link, $data['subcatId']);
       $priceformat = mysqli_real_escape_string($this->db->link, $data['priceformat']);
       $price = mysqli_real_escape_string($this->db->link, $data['price']);
       $regionId = mysqli_real_escape_string($this->db->link, $data['regionId']);
       $state = mysqli_real_escape_string($this->db->link, $data['state']);
       $description = mysqli_real_escape_string($this->db->link, $data['description']);

       if(count($file['images']['name']) > 0){
           for ($i = 0; $i < count($file['images']['name']); $i++) {//loop to get individual element from the array

               $permited  = array('jpg', 'jpeg', 'png', 'gif');
               $file_name = $file['images']['name'][$i];
               $file_size = $file['images']['size'][$i];
               $file_temp = $file['images']['tmp_name'][$i];

               $div = explode('.', $file_name);
               $file_ext = strtolower(end($div));
               $unique_image = substr(md5(time()), 0, 10).'.'.$file_ext;
               $uploaded_image = "../uploads/".$unique_image;

               if($title == "" || $catId == "" || $subcatId == "" || $priceformat == "" || $price == ""  || $regionId == "" || $file_name == "" || $state == "" || $description == ""){
                   $msg = "<span class='error'>Fields must not be empty!</span>";
                   return $msg;

               } elseif ($file_size >1048567) {
                    echo "<span class='error'>Image Size should be less then 1MB!
                </span>";

               } elseif (in_array($file_ext, $permited) === false) {
                   echo "<span class='error'>You can upload only:-".implode(', ', $permited)."</span>";

               } else{
                   move_uploaded_file($file_temp, $uploaded_image);
                   $query = "INSERT INTO ads(title, catId, subcatId, priceformat, price, regionId, images, state, description) VALUES('$title','$catId','$subcatId', '$priceformat', '$price','$regionId', '$uploaded_image', '$state', '$description')";
                   $inserted_row = $this->db->insert($query);

                       if($inserted_row){
                               $msg = "<span class='success'> Your ad has been uploaded successfully. </span>";
                               return $msg;
                           } else{
                               $msg = "<span class='error'> Sorry! Your offer is not added! Try again later. </span>";
                               return $msg;
                           }
                   }
           }
       }
   }


Here is My form page
PHP
<?php 
		$ad = new Ad();
        if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create'])){
        $insertAd = $ad->adInsert($_POST, $_FILES);

    }
?>


HTML
<form action="" method="post" class="ad-form"  enctype="multipart/form-data" data-parsley-validate >
		 <div class="form-fields-content">
		 <label for="title">Title</label>                    
		 <input type="text" id="title" name="title" placeholder="Title" required="required" data-parsley-maxlength="100" data-parsley-maxlength-message="Title can't have more than 100 words." data-parsley-required-message="Please enter a title." data-trigger="focus" data-toggle="popover" data-content="Keep the title short and clear. Do not write the price in it or any information that is not relevant." data-parsley-trigger="blur"/> 
         
          <label for="category">Category</label>  
		 <select id="Category" name="catId" required="required" data-parsley-required-message="Please select a Category." data-parsley-trigger="change">
	       <option value="">Select Category</option>
			 <?php
				  $getCategory = $category->getAllCat();
					if($getCategory){
					 while($result = $getCategory->fetch_assoc()){
			 ?>
				<option value="<?php echo $result['catId']; ?>"><?php echo $result['catName']; ?></option>
			 <?php } } ?>
		</select>                          
		
		<label for="subcategory">Subcategory</label>                           
		<select id="Subcategory" name="subcatId" required="required" data-parsley-required-message="Please select a subcategory." data-parsley-trigger="change">
		  <option value="">Select Category first</option>
		</select>  
                          
       <label for="priceformat">Price Format</label>                        
	   <select id="PriceFormat" onchange="change()" name="priceformat" required="required" data-parsley-required-message="Please Select Price Format." data-parsley-trigger="change">
		<option value="">Select Price Format</option>
		<option value="Fixed">Fixed Price</option>
        <option value="Negotiable">Negotiable</option>
	  </select>                          

	 <label for="title">Price</label>                    
	 <input type="text" name="price" placeholder="FCFA" required="required" pattern="[0-9]*" data-parsley-type="integer" data-parsley-type-message= "Enter the amount in digits. Decimals are not accepted." data-sanitize="integer" data-js-attr="{"type":"number","step":"any","min":"0"}" data-parsley-min="0" data-parsley-required-message="Please enter the price." data-parsley-trigger="blur" /> 

	 <label for="region">Location | Region</label>                        
	 <select id="Region" name="regionId" required="required" data-parsley-required-message="Please Select a Region." data-parsley-trigger="change">
	 <option value="">Select Region</option>
		<?php
			$getRegion = $region->getAllRegion();
				 if($getRegion){
					 while($result = $getRegion->fetch_assoc()){
			?>
			 <option value="<?php echo $result['regionId']; ?>"><?php echo $result['regionName']; ?></option>
             <?php } } ?>
	 </select>                          

	<label for="images[]">Images*</label>                   
    <input type="file" id="Photofile" name="images[]" required="required" data-parsley-required-message="Please Upload at least one photo" multiple />
		
       <label for="condition">Condition</label>                        						                    
       <select id="Condition" onchange="change()" name="condition" required="required" data-parsley-required-message="Please Select Product condition." data-parsley-trigger="change">
	   <option value="">Select Condition</option>
	   <option value="New">New</option>
       <option value="Used">Used</option>
	  </select>                          
	
        <label for="content">Description</label> 
        <textarea id="content" rows="10" name="description" required="required" data-parsley-minlength="10" data-parsley-maxlength="8000" data-parsley-minlength-message="Content can't have less than 9 characters." data-parsley-maxlength-message="Content can't have more than 8000 characters." data-parsley-required-message="Please enter a description." data-toggle="popover" data-content="Give a detailed description of your item. Do not put your contact details (phone, email or website url) in the description." data-parsley-trigger="blur" ></textarea>       
      <input type="submit" name="create" value="Create Post" class="button" />
      </div>
    </form>


And here is the Javascript I use for Images preview
JavaScript
<script type="text/javascript">
	var count=0;
	function handleFileSelect(evt) {
		var $fileUpload = $("input#Photofile[type='file']");
		count=count+parseInt($fileUpload.get(0).files.length);
		
		if (parseInt($fileUpload.get(0).files.length) > 4 || count>3) {
			alert("You can only upload a maximum of 3 photos");
			count=count-parseInt($fileUpload.get(0).files.length);
			evt.preventDefault();
			evt.stopPropagation();
			return false;
		}
		var files = evt.target.files;
		for (var i = 0, f; f = files[i]; i++) {
			if (!f.type.match('image.*')) {
				continue;
			}
			var reader = new FileReader();

			reader.onload = (function (theFile) {
				return function (e) {
					var span = document.createElement('span');
					span.innerHTML = ['<img class="thumb mrm mts" src="', e.target.result, '" title="', escape(theFile.name), '"/><span class="remove_img_preview"></span>'].join('');
					document.getElementById('list').insertBefore(span, null);
				};
			})(f);

			reader.readAsDataURL(f);
		}
	}
	
	$('#Photofile').change(function(evt){
		handleFileSelect(evt);
	});	 

	$('#list').on('click', '.remove_img_preview',function () {
		$(this).parent('span').remove();
        
        //this is not working...
        var i = array.indexOf($(this));
        if(i != -1) {
            array.splice(i, 1);
        }
        // tried this too:
        //$(this).parent('span').splice( 1, 1 );
        
        count--;
	});
</script>
Posted
Updated 15-Feb-18 23:50pm

1 solution

PHP
$unique_image = substr(md5(time()), 0, 10).'.'.$file_ext;
Your image names are probably not unique because time() returns a second based value (see PHP: time - Manual[^]).

You should also not truncate the MD5 hash has because that may also result in duplicates.

I suggest to use PHP: tempnam - Manual[^] instead.
 
Share this answer
 
Comments
Member 12428521 16-Feb-18 6:53am    
@jochen Oh I see. So is the format like this $unique_image = substr(tempnam(), 0, 10).'.'.$file_ext;
Jochen Arndt 16-Feb-18 8:15am    
No. See the provided link to the PHP documentation. You have to pass the directory path (resolved full path for "../uploads"). The returned string is a full path that must not be shortened by using substr().

Note also that the returned path has no image file extension. You might append that but it will again break the uniqueness because tempnam() ensures only that the returned name is unique. When doing so you should also delete the returned file name because tempnam() has already created the file with zero size.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900