Jump to content

Upload image to directory and store url of image in database


bullbreed

Recommended Posts

Hi everyone.

 

I'm trying to upload an image and move it to a folder in the root directory of my server which I have done (wahoo);

However, when I upload the image to the folder I would also like to store the url of that image into the database;

 

Heres my code for uploading and moving the image

// Check for a front image.
if(isset($_FILES['pfrontimage'])){
if (is_uploaded_file ($_FILES['pfrontimage']['tmp_name'])) {
	if (move_uploaded_file($_FILES['pfrontimage']['tmp_name'], "uploads/{$_FILES['pfrontimage']['name']}")) { // Move the file over.
		echo '<p>The front image has been uploaded!</p>';
	} else { // Couldn't move the file over.
		echo '<p><font color="red">The image could not be moved.</font></p>';
		$i = FALSE;
	}
	$i = $_FILES['pfrontimage']['name'];
} else {
	$i = FALSE;
}
}

 

What do I add to this code that will put the link to the image into the database table.

 

You already have the URL itself (where you're uploading it)

All you'd need to do is create a table with unique ID and the url in a varchar field.

You could that in the same if() that you are echoing 'has been uploaded' in.

 

Something like...

 

mysql_query("INSERT INTO uploaded_images (image_url)VALUES('uploads/".$_FILES["pfrontimage"]["name"]."')") or die(mysql_error());

Thanks for that it make a lot of sense.

However when I do that it creates a new row in the table to store only the url. I would like it to be stored in a row that has all the other data that goes with the product so;

 

How do I store the result in to a variable so I can add it to the database further down the script with the rest?

 

$pfrontimage = mysql_real_escape_string(uploads/".$_FILES["pbackimage"]["name"].");

 

It doesnt look right and i'm new.

You should be able to save the url as a variable and insert it at the same time as the rest of the Insert or if the INSERT has happened you will need to UPDATE referencing the last_insert_id assuming it happened in the same script.

Just a suggestion, but you may want to store just the filename, and build the path out when you create the links... that way, if you change your site structure you don't have to fix all of the links already stored in the database.

Well I have a lot of other data stored with that product as well as the image. Here is my code for this page

<div id="pagecont">
  
<div id="leftcol">
  <div class="navtop">Navigation</div>
	<?php include('includes/side-nav.php'); ?>
</div>
    
<div id="rightcol">
<?php
if (isset($_POST['submit'])) {

$submit = $_POST['submit'];

//Form data
$existprodcat = mysql_real_escape_string($_POST['existprod_cat']);
$newprodcat = mysql_real_escape_string($_POST['newprod_cat']);
$prodname = mysql_real_escape_string($_POST['prod_name']);
$prodptitle = mysql_real_escape_string($_POST['prod_ptitle']);
$prodpdescription = mysql_real_escape_string($_POST['prod_pdescription']);
$prodpkeywords = mysql_real_escape_string($_POST['prod_pkeywords']);
$pcolours = mysql_real_escape_string(serialize($_POST['pcolours']));
$psizes = mysql_real_escape_string(serialize($_POST['psizes']));
$prodprice = mysql_real_escape_string($_POST['prod_price']);
$proddesc = mysql_real_escape_string($_POST['prod_desc']);
$date = date('d/m/Y \a\t g:i.s a');



//Open the database
    mysql_connect("localhost","root","");
    mysql_select_db("***********"); //Select the database

if ($existprodcat !== ""){
        $pcat = $existprodcat;
}else{
        $pcat = $newprodcat;
}	

// Check for a front image.
if ((($_FILES["pfrontimage"]["type"] == "image/gif")
|| ($_FILES["pfrontimage"]["type"] == "image/jpeg")
|| ($_FILES["pfrontimage"]["type"] == "image/pjpeg"))
&& ($_FILES["pfrontimage"]["size"] < 20000))
  {
  if ($_FILES["pfrontimage"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["pfrontimage"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["pfrontimage"]["name"] . "<br />";
    echo "Type: " . $_FILES["pfrontimage"]["type"] . "<br />";
    echo "Size: " . ($_FILES["pfrontimage"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["pfrontimage"]["tmp_name"] . "<br />";

    if (file_exists("uploads/" . $_FILES["pfrontimage"]["name"]))
      {
      echo $_FILES["pfrontimage"]["name"] . " This image already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["pfrontimage"]["tmp_name"],
      "uploads/" . $_FILES["pfrontimage"]["name"]);
      echo "Stored in: " . "uploads/" . $_FILES["pfrontimage"]["name"];
  mysql_query("INSERT INTO `customfight`.`products` (`prod_fimage`) VALUES ('uploads/".$_FILES["pfrontimage"]["name"]."')") or die(mysql_error());
      }
    }
  }
else
  {
  echo "Invalid file";
  }
  
// Check for a back image.
if ((($_FILES["pbackimage"]["type"] == "image/gif")
|| ($_FILES["pbackimage"]["type"] == "image/jpeg")
|| ($_FILES["pbackimage"]["type"] == "image/pjpeg"))
&& ($_FILES["pbackimage"]["size"] < 20000))
  {
  if ($_FILES["pbackimage"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["pfrontimage"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["pbackimage"]["name"] . "<br />";
    echo "Type: " . $_FILES["pbackimage"]["type"] . "<br />";
    echo "Size: " . ($_FILES["pbackimage"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["pbackimage"]["tmp_name"] . "<br />";

    if (file_exists("uploads/" . $_FILES["pbackimage"]["name"]))
      {
      echo $_FILES["pbackimage"]["name"] . " This image already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["pbackimage"]["tmp_name"],
      "uploads/" . $_FILES["pbackimage"]["name"]);
      echo "Stored in: " . "uploads/" . $_FILES["pbackimage"]["name"];
  mysql_query("INSERT INTO `customfight`.`products` (`prod_bimage`) VALUES ('uploads/".$_FILES["pbackimage"]["name"]."')") or die(mysql_error());
      }
    }
  }
else
  {
  echo "Invalid file";
  }
  
		//Check for existing fields
if($prodname && $pcat && $prodptitle && $prodpdescription && $prodpkeywords && $pcolours && $psizes && $prodprice && $proddesc && $date){


$pagecheck = mysql_query("SELECT prod_name FROM products WHERE prod_name = '$prodname'");echo mysql_error();
    $count = mysql_num_rows($pagecheck);

    if ($count != 0){
        echo("<font size=\"2\" color=\"#ff0000\">That product already exists. Please edit the existing product!</font>");echo mysql_error();
   }else{

//Enter into Database
	$queryreg = mysql_query("INSERT INTO `********`.`products` (`id`, `prod_cat`, `prod_name`, `prod_ptitle`, `prod_pdescription`, `prod_pkeywords`, `prod_colours`, `prod_sizes`, `prod_price`, `prod_desc`, `date`) VALUES (NULL, '$pcat', '$prodname', '$prodptitle', '$prodpdescription', '$prodpkeywords', '$pcolours', '$psizes', '$prodprice', '$proddesc', '$date')");echo mysql_error();
	echo("<font size=\"2\" color=\"#00cc00\">Your product has been created! </font>");echo mysql_error();
}
}else{
	echo ("<font size=\"2\" color=\"#ff0000\">Please complete <b>ALL</b> fields</font>");echo mysql_error();
	 }
}	//end Check for existing fields
//end if submit
$sql = "SELECT * FROM `products`";
$query = mysql_query($sql);echo mysql_error();

?>              
      <div class="conttop">Add a product</div>

      <div class="contdata">
        <form action="addproduct.php" method="post" enctype="multipart/form-data" name="addpage" target="_self" id="addpage">
           
          
            <div class="genwrap">
              <div class="arrowwrap"></div>
              <div class="titlewrap">Product Name</div>
            </div>
            
            <div class="genwrap">
              <div class="arrowwrap"></div>
              <div class="titlewrap">Create product Category</div>
            </div>
            
            <div class="genwrap">
              <div class="arrowwrap"></div>
              <div class="titlewrap">Select existing category</div>
            </div>
          
          <div class="genwrap">
            <div class="titlewrap">
              <input name="prod_name" type="text" id="prod_name" size="25" />
            </div>
          </div>
          
          <div class="genwrap">
            <div class="titlewrap">
              <input name="newprod_cat" type="text" id="newprod_cat" size="25" />
            </div>
          </div>
          
          <div class="genwrap">
            <div class="titlewrap">
            <?php
			//Open the database
			mysql_connect("localhost","root","");
			mysql_select_db("********"); //Select the database

			$sql = "SELECT `prod_cat` FROM products";
			$query = mysql_query($sql) or die(mysql_error());

			$sections = array();

			while ($row = mysql_fetch_array($query)){
					$sections[] = $row[0];
			}
			$sections = array_unique($sections);
		?>
              <select name="existprod_cat" id="existprod_cat">
                <option selected></option>
                            <?php
                				foreach($sections as $section){
							echo '<option value="'.$section.'">'.$section.'</option>';
							}
						?>
              </select>
            </div>
            
          </div>
          <div class="clear"></div></div>
             
  <div class="conttop">Meta Data</div>
      	
<div class="contdata">
           <div class="genwrapmeta">
                <div class="arrowwrap"></div>
                <div class="titlewrap">Title</div>
           </div>
	<div class="genwrapmeta"><input name="prod_ptitle" id="prod_ptitle" type="text" size="80" maxlength="100" /></div>
        
            <div class="genwrapmeta">
             
                <div class="arrowwrap"></div>
                <div class="titlewrap">Description</div>
        	</div>
	<div class="genwrapmeta"><input name="prod_pdescription" type="text" id="prod_pdescription" size="80" maxlength="200" /></div>
        
		<div class="genwrapmeta">
                <div class="arrowwrap"></div>
                <div class="titlewrap">Keywords</div>
        	</div>
        <div class="genwrapmeta"><input name="prod_pkeywords" type="text" id="prod_pkeywords" size="80" maxlength="200" /></div>
        
	<div class="clear"></div>
</div>

	<div class="conttop">Product Front Image</div>
        
        <div class="contdata"><input name="pfrontimage" type="file" />
        </div>
        
        <div class="conttop">Product Back Image</div>
        
        <div class="contdata"><input name="pbackimage" type="file" /></div>
        
        <div class="conttop">Product Sizes</div>
        
        <div class="contdata">
        <label>S1</label>
        <input name="psizes[]" type="text" id="psizes[]" size="5" maxlength="20" />
        
        <label>S2</label>
        <input name="psizes[]" type="text" id="psizes[]" size="5" maxlength="20" />
        
        <label>S3</label>
        <input name="psizes[]" type="text" id="psizes[]" size="5" maxlength="20" />
        
        <label>S4</label>
        <input name="psizes[]" type="text" id="psizes[]" size="5" maxlength="20" />
        
        <label>S5</label>
        <input name="psizes[]" type="text" id="psizes[]" size="5" maxlength="20" />
        
        <label>S6</label>
        <input name="psizes[]" type="text" id="psizes[]" size="5" maxlength="20" />
        
        <label>S7</label>
        <input name="psizes[]" type="text" id="psizes[]" size="5" maxlength="20" />
        <br /><br />
        <label>S8</label>
        <input name="psizes[]" type="text" id="psizes[]" size="5" maxlength="20" />
        
        <label>S9</label>
        <input name="psizes[]" type="text" id="psizes[]" size="5" maxlength="20" />
        
        <label>S10</label>
        <input name="psizes[]" type="text" id="psizes[]" size="5" maxlength="20" />
        <div class="clear"></div>
        </div>
        
        <div class="conttop">Product Colour</div>
        
        <div class="contdata">
        <div class=" colourswrap">
                <div class="colours"><img src="uploads/black.jpg" alt="Black" /></div><br /><br />
                <input type="checkbox" name="pcolours[]" id="pcolours[]" value="uploads/black.jpg" />
            </div>
            
            <div class=" colourswrap">
                <div class="colours"><img src="uploads/white.jpg" alt="White" /></div><br /><br />
                <input type="checkbox" name="pcolours[]" id="pcolours[]" value="uploads/white.jpg" />
            </div>
            
            <div class=" colourswrap">
                <div class="colours"><img src="uploads/blue.jpg" alt="Blue" /></div><br /><br />
                <input type="checkbox" name="pcolours[]" id="pcolours[]" value="uploads/blue.jpg" />
            </div>
            
            <div class=" colourswrap">
                <div class="colours"><img src="uploads/red.jpg" alt="Red" /></div><br /><br />
                <input type="checkbox" name="pcolours[]" id="pcolours[]" value="uploads/red.jpg" />
            </div>
            
            <div class=" colourswrap">
                <div class="colours"><img src="uploads/pink.jpg" alt="Pink" width="22" height="22" /></div>
            <br /><br />
                <input type="checkbox" name="pcolours[]" id="pcolours[]" value="uploads/pink.jpg" />
            </div><div class="clear"></div>
                </div>
        
        
        <div class="conttop">Product Price</div>
        
        <div class="contdata"><input type="text" name="prod_price" id="prod_price" />
        <div class="clear"></div>
        </div>
     
  <div class="conttop">Page Content</div>
  <div class="contdata">
    <textarea name="prod_desc" cols="80" rows="20" id="prod_desc"></textarea>
        <br />
        <input type="submit" value="Save" name="submit" />
      </div>
  </form>
    </div><div class="clear"></div></div>

 

I thought maybe store the uploads/" . $_FILES["pbackimage"]["name"] as a variable like

 

$pfrontimage = my_real_escape_string (uploads/" . $_FILES["pbackimage"]["name"]); (not sure if I have to use my real escape string)

 

and do the same for the back image then I could INSERT into with the rest at the same time at the //Enter into database part of the script. I would think that this would add them to the correct row associated with that product. Just unsure how to call that into a variable with the $FILES in there

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.