PHP - Multiple Images In Database
Hello, I am new to PHP coding, and I have some issues trying to upload multiple images into database. The code works only for 1 image, but when I try to add foreach, I receive this message: Warning: Invalid argument supplied for foreach() . Can anyone help me ?
Similar TutorialsDear all, I have a problem that I need to be helped with using one form and storing the images in database. I would like to upload multiple images with same title from "title" field. Can somebody help me with this? <?php $db_host = 'localhost'; // don't forget to change $db_user = 'mysql-user'; $db_pwd = 'mysql-password'; $database = 'test'; $table = 'ae_gallery'; // use the same name as SQL table $password = '123'; // simple upload restriction, // to disallow uploading to everyone if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); // This function makes usage of // $_GET, $_POST, etc... variables // completly safe in SQL queries function sql_safe($s) { if (get_magic_quotes_gpc()) $s = stripslashes($s); return mysql_real_escape_string($s); } // If user pressed submit in one of the forms if ($_SERVER['REQUEST_METHOD'] == 'POST') { // cleaning title field $title = trim(sql_safe($_POST['title'])); if ($title == '') // if title is not set $title = '(empty title)';// use (empty title) string if ($_POST['password'] != $password) // cheking passwors $msg = 'Error: wrong upload password'; else { if (isset($_FILES['photo'])) { @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']); // Get image type. // We use @ to omit errors if ($imtype == 3) // cheking image type $ext="png"; // to use it later in HTTP headers elseif ($imtype == 2) $ext="jpeg"; elseif ($imtype == 1) $ext="gif"; else $msg = 'Error: unknown file format'; if (!isset($msg)) // If there was no error { $data = file_get_contents($_FILES['photo']['tmp_name']); $data = mysql_real_escape_string($data); // Preparing data to be used in MySQL query mysql_query("INSERT INTO {$table} SET ext='$ext', title='$title', data='$data'"); $msg = 'Success: image uploaded'; } } elseif (isset($_GET['title'])) // isset(..title) needed $msg = 'Error: file not loaded';// to make sure we've using // upload form, not form // for deletion if (isset($_POST['del'])) // If used selected some photo to delete { // in 'uploaded images form'; $id = intval($_POST['del']); mysql_query("DELETE FROM {$table} WHERE id=$id"); $msg = 'Photo deleted'; } } } elseif (isset($_GET['show'])) { $id = intval($_GET['show']); $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(image_time), data FROM {$table} WHERE id=$id LIMIT 1"); if (mysql_num_rows($result) == 0) die('no image'); list($ext, $image_time, $data) = mysql_fetch_row($result); $send_304 = false; if (php_sapi_name() == 'apache') { // if our web server is apache // we get check HTTP // If-Modified-Since header // and do not send image // if there is a cached version $ar = apache_request_headers(); if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists ($ar['If-Modified-Since'] != '') && // not empty (strtotime($ar['If-Modified-Since']) >= $image_time)) // and grater than $send_304 = true; // image_time } if ($send_304) { // Sending 304 response to browser // "Browser, your cached version of image is OK // we're not sending anything new to you" header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304); exit(); // bye-bye } // outputing Last-Modified header header('Last-Modified: '.gmdate('D, d M Y H:i:s', $image_time).' GMT', true, 200); // Set expiration time +1 year // We do not have any photo re-uploading // so, browser may cache this photo for quite a long time header('Expires: '.gmdate('D, d M Y H:i:s', $image_time + 86400*365).' GMT', true, 200); // outputing HTTP headers header('Content-Length: '.strlen($data)); header("Content-type: image/{$ext}"); // outputing image echo $data; exit(); } ?> <html><head> <title>MySQL Blob Image Gallery Example</title> </head> <body> <?php if (isset($msg)) // this is special section for // outputing message { ?> <p style="font-weight: bold;"><?=$msg?> <br> <a href="<?=$PHP_SELF?>">reload page</a> <!-- I've added reloading link, because refreshing POST queries is not good idea --> </p> <?php } ?> <h1>Blob image gallery</h1> <h2>Uploaded images:</h2> <form action="<?=$PHP_SELF?>" method="post"> <!-- This form is used for image deletion --> <?php $result = mysql_query("SELECT id, image_time, title FROM {$table} ORDER BY id DESC"); if (mysql_num_rows($result) == 0) // table is empty echo '<ul><li>No images loaded</li></ul>'; else { echo '<ul>'; while(list($id, $image_time, $title) = mysql_fetch_row($result)) { // outputing list echo "<li><input type='radio' name='del' value='{$id}'>"; echo "<a href='{$PHP_SELF}?show={$id}'>{$title}</a> – "; echo "<small>{$image_time}</small></li>"; } echo '</ul>'; echo '<label for="password">Password:</label><br>'; echo '<input type="password" name="password" id="password"><br><br>'; echo '<input type="submit" value="Delete selected">'; } ?> </form> <h2>Upload new image:</h2> <form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data"> <label for="title">Title:</label><br> <input type="text" name="title" id="title" size="64"><br><br> <label for="photo">Photo:</label><br> <input type="file" name="photo" id="photo"><br><br> <label for="password">Password:</label><br> <input type="password" name="password" id="password"><br><br> <input type="submit" value="upload"> </form> </body> </html> hi there how can i modify this code to let me upload multiple images in database? thanks Code: [Select] / Start a session for error reporting session_start(); //Connect to database require_once('../Connections/connect_to_mysql.php'); //check if the button is pressed if(isset($_POST['submit'])){ // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "adminform_images/"; // Get our POSTed variables $title = $_POST['title']; $name = $_POST['name']; $surname = $_POST['surname']; $email = $_POST['email']; $phone = $_POST['phone']; $city = $_POST['city']; $comments = $_POST['comments']; $image = $_FILES['image']; $price = $_POST['price']; // Sanitize our inputs $title = mysql_real_escape_string($title); $name = mysql_real_escape_string($name); $surname = mysql_real_escape_string($surname); $email = mysql_real_escape_string($email); $phone = mysql_real_escape_string($phone); $city = mysql_real_escape_string($city); $comments = mysql_real_escape_string($comments); $image['name'] = mysql_real_escape_string($image['name']); $price = mysql_real_escape_string($price); // Build our target path full string. This is where the file will be moved do // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Make sure all the fields from the form have inputs if ( $title == "" || $name == "" || $email == "" || $city == "" || $comments == "" || $price == ""|| $image['name'] == "" ) { echo "Te gjithe fushat duhet plotesuar. <a href=login.php>Provo perseri</a>"; exit; } // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { echo "Fotografite duhet te jene te formateve jpg, jpeg, bmp, gif, ose png. <a href=login.php>Kthehu prapa</a>"; exit; } // Here we check to see if a file with that name already exists // You could get past filename problems by appending a timestamp to the filename and then continuing if (file_exists($TARGET_PATH)) { echo "Ju lutem nderroni emrin e fotos dhe provoni perseri. <a href=login.php>Kthehu prapa</a>"; exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "INSERT INTO admins_form (title, name, surname, email, phone, city, comments, price, date_added, filename) values ('$title', '$name', '$surname', '$email', '$phone', '$city', '$comments', '$price', now(), '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Futja e te dhenave ne databaze DESHTOI. <a href=login.php>Provo perseri</a> "); echo "Shtimi i te dhenave u krye me SUKSES. Klikoni per te shkuar tek <a href=../index.php>faqja kryesore</a>"; exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable echo "Shtimi i te dhenave NUK u krye me Sukses. Ju lutem provoni <a href=login.php>perseri</a>"; exit; } } Hi all, while I was coding a script for my website something struck me which ive not really got an idea how to code it, but anyway, in my Database ive got a table which holds image URL's but how could I echo them out in PHP which will show the image? Not just the writing. Thanks for your help. Hi All Been desperate to crack this nut for a few years now, but seem to be failing epically! I have been building a property/real estate web site for a long time, but I have no training and have been learning as I go. I have a script written that allows me to upload data and store it in my database, what I was looking to do was add a section that allows me to upload multiple images at the same time, and store the location to another table in the same database. So what I was looking to do was remove all the...lets say rubbish to be nice...and see where it takes us. I apologize in advance for the lack of santized code...I am coding locally only, in an admin area, and will rectify before launching the site...just trying to get the bones of the script in place. Ok, first we have my form as shown here, warts and all. <?php /** * Create Listing */ ?> <div id="admin" class="intern"> <div class="banner"> <div class="logbanner">CREATE LISTING</div> </div> <div class="padding"> <form action="adminprocess.php" method="POST" enctype="multipart/form-data"> <table border="0" cellpadding="2" cellspacing="2" width="700"> <tr> <td align="right"><label class="text">Property Title: </label></td> <td><input type="text" name="property_title" maxlength="50" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Selling Agent: </label></td> <td><input type="text" name="agent" maxlength="30" value="<?php echo $session->username; ?>"></td> </tr> <tr> <td align="right"><label class="text">Style: </label></td> <td> <select id="property_type" name="property_type"> <option value="Not Selected" selected>Not Selected</option> <option value="Detached">Detached</option> <option value="Semi-Deatched">Semi-Detached</option> <option value="End Terrace">End Terrace</option> <option value="Mid Terrace">Mid Terrace</option> <option value="Flat">Flat</option> <option value="Ground Floor Flat">Ground Floor Flat</option> <option value="4 in a Block">4 in a Block</option> <option value="Bungalow">Bungalow</option> <option value="Apartment">Apartment</option> <option value="Studio">Studio</option> <option value="Maisonette">Maisonette</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Address: </label></td> <td><input type="text" name="address_one" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Address: </label></td> <td><input type="text" name="address_two" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Town: </label></td> <td><input type="text" name="town" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">County: </label></td> <td> <select id="county" name="county"> <option value="Fife" selected>Fife</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Post Code: </label></td> <td><input type="text" name="postcode" maxlength="30" value="" size="15"></td> </tr> <tr> <td align="right"><label class="text">Price: </label></td> <td> <select id="price_cond" name="price_cond"> <option value="Not Selected" selected>Not Selected</option> <option value="Offers Over">Offers Over</option> <option value="Fixed Price">Fixed Price</option> </select> <input type="text" name="price" maxlength="30" value="" size="32"> </td> </tr> <tr> <td align="right"><label class="text">Property Status: </label></td> <td> <select id="status" name="status"> <option value="Not Selected" selected>Not Selected</option> <option value="Offers Over">For Sale</option> <option value="Fixed Price">Sold Subject to Signed Missives</option> <option value="Fixed Price">Sold Subject to Survey</option> <option value="Fixed Price">Price Reduced</option> <option value="Fixed Price">Sold</option> <option value="Fixed Price">Re-Listed</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Description Header: </label></td> <td><input type="text" name="deschead" maxlength="30" value="" size="50"></td> </tr> <tr> <td align="right"><label class="text">Description: </label></td> <td><textarea cols="40" rows="8" type="text" name="desc" maxlength="1000" value=""></textarea></td> </tr> <!-- I want the images to be added here --> <tr> <td align="right"><label class="text">Reception Rooms: </label></td> <td> <select id="recrooms" name="recrooms"> <option value="0" selected>Not Selected</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7+</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Bedrooms: </label></td> <td> <select id="bedrooms" name="bedrooms"> <option value="0" selected>Not Selected</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7+</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Bathrooms: </label></td> <td> <select id="bathrooms" name="bathrooms"> <option value="0" selected>Not Selected</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7+</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Garden: </label></td> <td> <select id="garden" name="garden"> <option value="Not Selected" selected>Not Selected</option> <option value="Yes">Yes</option> <option value="No">No</option> <option value="Shared">Shared</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Garage: </label></td> <td> <select id="garage" name="garage"> <option value="Not Selected" selected>Not Selected</option> <option value="Yes">Yes</option> <option value="No">No</option> <option value="Shared">Shared</option> </select> </td> </tr> <tr> <td align="right"><label class="text">Additional Info: <br />** Not seen by site users **</label></td> <td><textarea cols="40" rows="8" type="text" name="addinfo" maxlength="1000" value=""></textarea></td> </tr> <tr> <td align="right"><label class="text"> </label></td> <td> <input type="hidden" name="subcreatelisting" value="1"> <input type="submit" value="Create Listing"> </td> </tr> </table> </form> <?php echo $form->error("creListing"); ?> </div> </div> next I have my process page which has the following function included... function procCreateListing(){ global $session, $database, $form; $q = "INSERT INTO ".TBL_PROP."(prop_id, prop_agent, prop_type, prop_add_1, prop_add_2, prop_town, prop_county, prop_pc, prop_price, prop_price_cond, prop_rec_rooms, prop_bedrooms, prop_bathrooms, prop_status, prop_garden, prop_garage, prop_description_header, prop_description, prop_add_info, prop_add_date) VALUES ('".$_POST['property_title']."', '".$_POST['agent']."', '".$_POST['property_type']."', '".$_POST['address_one']."', '".$_POST['address_two']."', '".$_POST['town']."', '".$_POST['county']."', '".$_POST['postcode']."', '".$_POST['price']."', '".$_POST['price_cond']."', '".$_POST['recrooms']."', '".$_POST['bedrooms']."', '".$_POST['bathrooms']."', '".$_POST['status']."', '".$_POST['garden']."', '".$_POST['garage']."', '".$_POST['deschead']."', '".$_POST['desc']."', '".$_POST['addinfo']."', '".$_POST['date']."')"; $database->query($q); } and I have 2 tables in mysql prop_listing and imagebin Code: [Select] CREATE TABLE `kea_userclass`.`prop_listing` ( `prop_id` INT( 10 ) NOT NULL AUTO_INCREMENT , `prop_agent` VARCHAR( 40 ) NOT NULL , `prop_type` VARCHAR( 20 ) NOT NULL , `prop_add_1` VARCHAR( 50 ) NOT NULL , `prop_add_2` VARCHAR( 50 ) NOT NULL , `prop_town` VARCHAR( 30 ) NOT NULL , `prop_county` VARCHAR( 25 ) NOT NULL , `prop_pc` VARCHAR( 8 ) NOT NULL , `prop_price` INT( 10 ) NOT NULL , `prop_price_cond` VARCHAR( 20 ) NOT NULL , `prop_rec_rooms` INT( 2 ) NOT NULL , `prop_bedrooms` INT( 3 ) NOT NULL , `prop_bathrooms` INT( 2 ) NOT NULL , `prop_status` VARCHAR( 20 ) NOT NULL , `prop_garage` INT( 1 ) NOT NULL , `prop_garden` INT( 1 ) NOT NULL , `prop_description_header` VARCHAR( 50 ) NOT NULL , `prop_description` VARCHAR( 2000 ) NOT NULL , `prop_add_info` VARCHAR( 2000 ) NOT NULL , `prop_add_date` DATE NOT NULL , PRIMARY KEY ( `prop_id` ) ) ENGINE = MYISAM ; CREATE TABLE `imagebin` ( `id` int( 11 ) NOT NULL AUTO_INCREMENT , `item_id` int( 11 ) NOT NULL , `image` varchar( 255 ) NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM DEFAULT CHARSET = latin1; first of all thanks for getting this far, I know it is a lot of reading, and a lot to ask for, but now I am stuck... I need a section on my form that would allow me to upload 8 images, and store them in a directory folder I need the location saved into my imagebin table thats it just now Many thanks for reading, and I hope someone can take me under their wing and help me passed this hurdle I have this code which uoploads and resizes the images into a folder without a problem. My problem is I am unable to view the Thumb or Full image which has uploaded to the folder and the database with the other data. How do i correct this problem code below. Thanks upload form and script Code: [Select] <?php //database properties $dbhost = 'localhost'; $dbuser = 'user'; $dbpass = 'pass'; $dbname = 'DB'; // make a connection to mysql here $conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error()); mysql_select_db ($dbname) or die ("I cannot select the database '$dbname' because: " . mysql_error()); /******** start function ********/ function errors($error){ if (!empty($error)) { $i = 0; echo "<blockquote>\n"; while ($i < count($error)){ echo "<p><span class=\"warning\">".$error[$i]."</span></p>\n"; $i ++;} echo "</blockquote>\n"; }// close if empty errors } // close function // ----------------Create Smaller version of large image--------------------- function createthumbfull($src_filename, $dst_filename_full) { // Get information about the image list($src_width, $src_height, $type, $attr) = getimagesize( $src_filename ); // Load the image based on filetype switch( $type ) { case IMAGETYPE_JPEG: $starting_image = imagecreatefromjpeg( $src_filename ); break; case IMAGETYPE_PNG: $starting_image = imagecreatefrompng( $src_filename ); break; case IMAGETYPE_GIF: $starting_image = imagecreatefromgif( $src_filename ); break; default: return false; } // get the image to create thumbnail from $starting_image; // get image width $width = imagesx($starting_image); // get image height $height = imagesy($starting_image); // size to create thumnail width $thumb_width = 600; // divide iwidth by specified thumb size $constant = $width/$thumb_width; // round height by constant and add t thumb_height $thumb_height = round($height/$constant, 0); //create thumb with true colours $thumb_image = imagecreatetruecolor($thumb_width, $thumb_height); //create thumbnail resampled to make image smooth imagecopyresampled($thumb_image, $starting_image, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); $ran = rand () ; $thumb1 = $ran.".jpg"; global $thumb_Add_full; $thumb_Add_full = $dst_filename_full; $thumb_Add_full .= $thumb1; imagejpeg($thumb_image, "" .$dst_filename_full. "$thumb1"); } //-------------------- create thumbnail -------------------------------------------- //$src_filename = source of image //$dst_filename_thumb = location to store final image function createthumb($src_filename, $dst_filename_thumb) { $size = getimagesize($src_filename); // get image size $stype = $size['mime']; //get image type : gif,png,jpg $w = $size[0]; // width of image $h = $size[1]; // height of image //do a switch statment to create image from right image type switch($stype) { //if image is gif create from gif case 'image/gif': $simg = imagecreatefromgif($src_filename); break; //if image is jpeg create from jpeg case 'image/jpeg': $simg = imagecreatefromjpeg($src_filename); break; //if image is png create from png case 'image/png': $simg = imagecreatefrompng($src_filename); break; } $width = $w; // get image width $height = $h; // get image height // size to create thumnail width $thumb_width = 150; $thumb_height = 150; //use true colour for image $dimg = imagecreatetruecolor($thumb_width, $thumb_height); $wm = $width/$thumb_width; //width divided by new width $hm = $height/$thumb_height; //height divided by new height $h_height = $thumb_height/2; //ass new height and chop in half $w_height = $thumb_width/2; //ass new height and chop in half //if original width is more then original height then modify by width if($w> $h) { $adjusted_width = $w / $hm; // add original width and divide it by modified height and add to var $half_width = $adjusted_width / 2; // chop width in half $int_width = $half_width - $w_height; // take away modified height from new width //make a copy of the image imagecopyresampled($dimg,$simg,-$int_width,0,0,0,$adjusted_width,$thumb_height,$w,$h); //else if original width is less or equal to original height then modify by height } elseif(($w <$h) || ($w == $h)) { $adjusted_height = $h / $wm; // diving original height by modified width $half_height = $adjusted_height / 2; // chop height in half $int_height = $half_height - $h_height; // take away modified height from new width //make a copy of the image imagecopyresampled($dimg,$simg,0,-$int_height,0,0,$thumb_width,$adjusted_height,$w,$h); } else { // don't modify image and make a copy imagecopyresampled($dimg,$simg,0,0,0,0,$thumb_width,$thumb_height,$w,$h); } $ran = "thumb_".rand (); // generate random number and add to a string $thumb2 = $ran.".jpg"; //add random string to a var and append .jpg on the end global $thumb_Add_thumb; //make this var available outside the function as it will be needed later. $thumb_Add_thumb = $dst_filename_thumb; // add destination $thumb_Add_thumb .= $thumb2; // append file name on the end //actually create the final image imagejpeg($dimg, "" .$dst_filename_thumb. "$thumb2"); } /********end functions ***********/ // if form submitted then process form if (isset($_POST['submit'])){ // check feilds are not empty $imageTitle = trim($_POST['imageTitle']); if (strlen($imageTitle) < 3 || strlen($imageTitle) > 255) { $error[] = 'Title must be at between 3 and 255 charactors.'; } // check feilds are not empty or check image file size if (!isset($_FILES["uploaded"])) { $error[] = 'You forgot to select an image.'; } // check feilds are not empty $imageDesc = trim($_POST['imageDesc']); if (strlen($imageDesc) < 3) { $error[] = 'Please enter a description for your image.'; } // location where inital upload will be moved to $target = "productimages/" . $_FILES['uploaded']['name'] ; // find the type of image switch ($_FILES["uploaded"]["type"]) { case $_FILES["uploaded"]["type"] == "image/gif": move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target); break; case $_FILES["uploaded"]["type"] == "image/jpeg": move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target); break; case $_FILES["uploaded"]["type"] == "image/pjpeg": move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target); break; case $_FILES["uploaded"]["type"] == "image/png": move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target); break; case $_FILES["uploaded"]["type"] == "image/x-png": move_uploaded_file($_FILES["uploaded"]["tmp_name"],$target); break; default: $error[] = 'Wrong image type selected. Only JPG, PNG or GIF accepted!.'; } // if valadation is okay then carry on if (!$error) { // post form data $imageTitle = $_POST['imageTitle']; $imageDesc = $_POST['imageDesc']; //strip any tags from input $imageTitle = strip_tags($imageTitle); $imageDesc = strip_tags($imageDesc); // add slashes if needed if(!get_magic_quotes_gpc()) { $imageTitle = addslashes($imageTitle); $imageDesc = addslashes($imageDesc); } // remove any harhful code and stop sql injection $imageTitle = mysql_real_escape_string($imageTitle); $imageDesc = mysql_real_escape_string($imageDesc); //add target location to varible $src_filename $src_filename = $target; // define file locations for full sized and thumbnail images $dst_filename_full = 'productimages/'; $dst_filename_thumb = 'productthumb/'; // create the images createthumbfull($src_filename, $dst_filename_full); //call function to create full sized image createthumb($src_filename, $dst_filename_thumb); //call function to create thumbnail image // delete original image as its not needed any more. unlink ($src_filename); // insert data into images table $query = "INSERT INTO table (imageTitle, imageThumb, imageFull, imageDesc) VALUES ('$imageTitle', '$thumb_Add_thumb', '$thumb_Add_full', '$imageDesc')"; $result = mysql_query($query) or die ('Cannot add image because: '. mysql_error()); // show a message to confirm results echo "<h3 align='center'> $imageTitle uploaded</h3>"; } } //dispaly any errors errors($error); ?> <form enctype="multipart/form-data" action="" method="post"> <fieldset> <legend>Upload Picture</legend> <p>Only JPEG, GIF, or PNG images accepted</p> <p><label>Title<br /></label><input type="text" name="imageTitle" <?php if (isset($error)){ echo "value=\"$imageTitle\""; }?> /></p> <p><label>Image<br /></label><input type="file" name="uploaded" /></p> <p><label>Description<br /></label><textarea name="imageDesc" cols="50" rows="10"><?php if (isset($error)){ echo "$imageDesc"; }?></textarea></p> <p><label> </label><input type="submit" name="submit" value="Add Image" /></p> </fieldset> </form> view data Code: [Select] <?php // Connects to your Database mysql_connect("localhost", "user", "pass") or die(mysql_error()) ; mysql_select_db("DB") or die(mysql_error()) ; //Retrieves data from MySQL $data = mysql_query("SELECT * FROM table") or die(mysql_error()); //Puts it into an array while($info = mysql_fetch_array( $data )) { ?> <?php echo "<img src=http://www.web.com/productimages/" .$info['imagefull'] ." > <br>"; ?> <?php echo "<img src=http://www.web.com/productthumb/" .$info['imageThumb'] ." > <br>"; ?> <?php echo "<b>imageTitle:</b> ".$info['imageTitle'] . "<br> "; ?> <?php echo "<b>imageDesc:</b> ".$info['imageDesc'] . " <hr>"; ?> <?php }?> I want users to be allowed to upload images to a table in a database but I cannot seem to find a suitable way to implementing using the code I already have, here is the code below; Code: [Select] <?php error_reporting(E_ALL ^ E_NOTICE); ini_set("display_errors", 1); require_once ('./includes/config.inc.php'); require_once (MYSQL); $add_cat_errors = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (!empty($_POST['product'])) { $prod = mysqli_real_escape_string($dbc, strip_tags($_POST['product'])); } else { $add_cat_errors['product'] = 'Please enter a Product Name!'; } if (filter_var($_POST['prod_descr'])) { $prod_descr = mysqli_real_escape_string($dbc, strip_tags($_POST['prod_descr'])); } else { $add_cat_errors['prod_descr'] = 'Please enter a Product Description!'; } // Check for a category: if (filter_var($_POST['cat'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $catID = $_POST['cat']; } else { // No category selected. $add_page_errors['cat'] = 'Please select a category!'; } if (filter_var($_POST['price'])) { $price = mysqli_real_escape_string($dbc, strip_tags($_POST['price'])); } else { $add_cat_errors['price'] = 'Please enter a Product Description!'; } if (filter_var($_POST['stock'])) { $stock = mysqli_real_escape_string($dbc, strip_tags($_POST['stock'])); } else { $add_cat_errors['stock'] = 'Please enter a Product Description!'; } if (empty($add_cat_errors)) { $query = "INSERT INTO product (product, prod_descr, catID, price, image, stock) VALUES ('$prod', '$prod_descr', '$catID', '$price', '$image', '$stock')"; $r = mysqli_query ($dbc, $query); if (mysqli_affected_rows($dbc) == 1) { echo '<p>Record Successfully Added!!!!!</p>'; $_POST = array(); } else { trigger_error('OH NOOOOO!!!!'); } } } require_once ('./includes/form_functions.inc.php'); ?> <form action="add_product.php" method="post"> Product Name: <?php create_form_input('product', 'text', $add_cat_errors);?> Product Description: <?php create_form_input ('prod_descr', 'text', $add_cat_errors);?> Category: <select name="cat"<?php if (array_key_exists('cat', $add_cat_errors))?>> <option>Select a Category</option> <?php $q = "SELECT catID, cat FROM category ORDER BY cat ASC"; $r = mysqli_query($dbc, $q); while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; if (isset($_POST['cat']) && ($_POST['cat'] == $row[0])) echo 'selected="selected"'; echo ">$row[1]</option>\n"; } ?> Price: <?php create_form_input('price', 'text', $add_cat_errors);?> Upload an Image: <?php if(array_key_exists('image', $add_cat_errors)) { echo '<input type="file" name="image" />'; } ?> Stock: <?php create_form_input('stock', 'text', $add_cat_errors);?> <input type="submit" name="submit_button" value="ADD RECORD" /> </form> Everything else writes perfectly but I have been trying ways to create a file upload and write successfully to the database. The 'image' field has a data type of 'varchar'. I apologise immensely for the long winded explanation but if anyone could help me please that would be much appreciated. I have a form that will be used to edit various fields including images. Everything works on this form except the images. When I choose the image i want to replace and upload the new image the location of the others get erased on the MySQL database and I'm just left with the one I replaced. How can I just change the image I pick to replace without erasing the location of the others? Is there a way just to tell the script to only replace the image that corresponds with the image selected? Thank You The Form Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>FormListing </title> </head> <body>\<?php session_start(); if(empty($_SESSION['myusername'])){ // send them back to login header('location: index.php'); } $_SESSION['id']; $_SESSION['$myusername']; $id = (int)$_GET['id']; $id = substr($id, 0,5); if($id < 1 || $id > 99999) exit; $host="localhost"; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name=""; // Table name // Connect to server and select database. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // get value of id that sent from address bar $id=$_GET['id']; // Retrieve data from database $sql="SELECT * FROM $tbl_name WHERE id='$id'"; $result=mysql_query($sql); $rows=mysql_fetch_array($result); ?> <form method="post" action="aptmodifyform.php" enctype="multipart/form-data"/> <input type="hidden" name="id" id="id" value="<?php echo $id; ?>" /> <table width="914" height="1234" border="0"> <tr> <td width="636" height="68"><div align="right"><span style="color: #F00">*</span>Title</div></td> <td width="11"><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="title"></label> <div align="left"><span id="sprytextfield1"> <input name="title" type="text" value="<? echo $rows['title']; ?>" id="title" size="50" maxlength="50"/> </span></div></td> </tr> <tr> <td><div align="right">County</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="county"></label> <select name="county" id="county"> <option selected="selected" <?=($rows['county'] == 'Bronx') ? 'selected="selected"' : ''?>>Bronx</option> <option <?=($rows['county'] == 'Brooklyn') ? 'selected="selected"' : ''?>>Brooklyn</option> <option <?=($rows['county'] == 'Manhattan') ? 'selected="selected"' : ''?>>Manhattan</option> <option <?=($rows['county'] == 'Queens') ? 'selected="selected"' : ''?>>Queens</option> <option <?=($rows['county'] == 'Staten Island') ? 'selected="selected"' : ''?>>Staten Island</option> <option>-----------------</option> <option <?=($rows['county'] == 'Nassau') ? 'selected="selected"' : ''?>>Nassau</option> <option <?=($rows['county'] == 'Suffolk') ? 'selected="selected"' : ''?>>Suffolk</option> </select></td> </tr> <tr> <td><div align="right">Town</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="town"></label> <input name="town" type="text" value="<? echo $rows['town']; ?>" id="town" size="50" maxlength="30"/></td> </tr> <tr> <td><div align="right">Description<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> </div></td> <td><div align="center"> <p>:<br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> </p> </div></td> <td colspan="3" style="text-align: left"><label for="description"></label> <textarea name="description" cols="70" rows="25" id="description"><?php echo $rows['description']; ?></textarea></td> </tr> <tr> <td style="text-align: right; color: #000;">Service</td> <td style="text-align: center">:</td> <td colspan="3" style="text-align: left"><label for="service"></label> <select name="service" size="1" id="service"> <option <?=($rows['service'] == 'Landlord') ? 'selected="selected"' : ''?>>Lanlord</option> <option <?=($rows['service'] == 'Property Mangement') ? 'selected="selected"' : ''?>>Property Mangement</option> <option <?=($rows['service'] == 'Realtor') ? 'selected="selected"' : ''?>>Realtor</option> </select></td> </tr> <tr> <td><div align="right">Service Fees</div></td> <td>:</td> <td colspan="3" style="text-align: left"><select name="feeornofee" id="feeornofee"> <option <?=($rows['feeornofee'] == 'Broker Fees + Other Fees') ? 'selected="selected"' : ''?>>Broker Fees + Other Fees</option> <option <?=($rows['feeornofee'] == 'Broker Fees') ? 'selected="selected"' : ''?>>Broker Fees</option> <option <?=($rows['feeornofee'] == 'Other Fees - No Broker Fee') ? 'selected="selected"' : ''?>>Other Fees - No Broker Fee</option> <option <?=($rows['feeornofee'] == 'No Fees') ? 'selected="selected"' : ''?>>No Fees</option> </select></td> </tr> <tr> <td><div align="right">Lease Type</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="lease"></label> <select name="lease" id="lease"> <option <?=($rows['lease'] == 'Rent Stabilized ') ? 'selected="selected"' : ''?>>Rent Stabilized </option> <option <?=($rows['lease'] == 'Prime, non-stabilized lease') ? 'selected="selected"' : ''?>>Prime, non-stabilized lease</option> <option <?=($rows['lease'] == 'Coop (sub) Lease') ? 'selected="selected"' : ''?>>Coop (sub) Lease</option> <option <?=($rows['lease'] == 'Condo Lease') ? 'selected="selected"' : ''?>>Condo Lease</option> <option <?=($rows['lease'] == 'Commercial Lease') ? 'selected="selected"' : ''?>>Commercial Lease</option> <option <?=($rows['lease'] == 'Other') ? 'selected="selected"' : ''?>>Other</option> </select></td> </tr> > <tr> <td><div align="right">Contact's Name</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="contact"></label> <input name="contact" type="text" value="<? echo $rows['contact']; ?>" id="contact" size="40" maxlength="40" /></td> </tr> <tr> <td><div align="right">Name of Office</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="office"></label> <input name="office" type="text" value="<? echo $rows['office']; ?>" id="office" size="40" maxlength="40" /></td> </tr> <tr> <td><div align="right">Pets</div></td> <td>:</td> <td colspan="3" style="text-align: left"><label for="pets"></label> <select name="pets" id="pets"> <option <?=($rows['pets'] == 'Pets Allowed') ? 'selected="selected"' : ''?>>Pets Allowed</option> <option <?=($rows['pets'] == 'No Pets') ? 'selected="selected"' : ''?>>No Pets</option> <option <?=($rows['pets'] == 'Pets Allowed - Small pets') ? 'selected="selected"' : ''?>>Pets Allowed - Small pets</option> </select></td> </tr> <tr> <td><div align="right">Phone<br /> </div> <br /></td> <td><div align="center">:<br /> <br /> </div></td> <td colspan="3" style="text-align: left"><label for="phone"></label> <span id="rental_phone"> <input type="text" name="phone" value="<? echo $rows['phone']; ?>"id="phone" /> <span class="textfieldMaxCharsMsg">Exceeded maximum number of characters.</span></span><br /> <span style="font-style: italic; font-size: 14px; font-weight: bold;">ex. (123) 456-7890 - Please keep this format.</span></td> </tr> <tr> <td style="text-align: right"><p>Location<br /> </p> <p><br /> <br /> <br /> </p></td> <td style="text-align: center">:<br /> <br /> <br /> <br /> <br /></td> <td colspan="3" style="text-align: left"><label for="cross_streets"></label> <input name="cross_streets" type="text" value="<? echo $rows['cross_streets']; ?>" id="cross_streets" size="80" maxlength="100" /> <br /> <span style="color: #F00">Please insert here the intersecting streets. Make sure you add the word "and" <br /> between streets <br /> OR<br /> You can put the property's full address. <br /> e.g. 193rd Street AND Jamaica Avenue, Jamaica, NY </span></td> </tr> <tr> <td style="text-align: right">Zip Code</td> <td style="text-align: center">:</td> <td colspan="3" style="text-align: left"><input name="zipcode" type="text" id="zipcode" value="<? echo $rows['zipcode']; ?>" size="9" maxlength="5" /></td> </tr> <tr> <td style="text-align: right"><span style="color: #000">Email </span><br /> <br /></td> <td style="text-align: center">:<br /> <br /></td> <td colspan="3" style="text-align: left"><label for="email"></label> <input name="email" type="text" value="<? echo $rows['email']; ?>" id="email" size="60" maxlength="60" /> <br /> <span style="font-size: 12px; font-style: italic;">This field is optional. It will be viewable to users.</span></td> </tr> <tr> <td><div align="right">Rooms</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="rooms"></label> <select name="rooms" id="rooms"> <option <?=($rows['rooms'] == '0') ? 'selected="selected"' : ''?>>0</option> <option <?=($rows['rooms'] == '1') ? 'selected="selected"' : ''?>>1</option> <option <?=($rows['rooms'] == '1.5') ? 'selected="selected"' : ''?>>1.5</option> <option <?=($rows['rooms'] == '2') ? 'selected="selected"' : ''?>>2</option> <option <?=($rows['rooms'] == '2.5') ? 'selected="selected"' : ''?>>2.5</option> <option <?=($rows['rooms'] == '3') ? 'selected="selected"' : ''?>>3</option> <option <?=($rows['rooms'] == '3.5') ? 'selected="selected"' : ''?>>3.5</option> <option <?=($rows['rooms'] == '4') ? 'selected="selected"' : ''?>>4</option> <option <?=($rows['rooms'] == '4.5') ? 'selected="selected"' : ''?>>4.5</option> <option <?=($rows['rooms'] == '5') ? 'selected="selected"' : ''?>>5</option> <option <?=($rows['rooms'] == '5.5') ? 'selected="selected"' : ''?>>5.5</option> <option <?=($rows['rooms'] == '6') ? 'selected="selected"' : ''?>>6</option> </select> 0 = Studio, 1 = 1 Bedroom, etc.</td> </tr> <tr> <td><div align="right">Bath</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="bath"></label> <select name="bath" id="bath"> <option <?=($rows['bath'] == '0') ? 'selected="selected"' : ''?>>0</option> <option <?=($rows['bath'] == '1') ? 'selected="selected"' : ''?>>1</option> <option <?=($rows['bath'] == '1.5') ? 'selected="selected"' : ''?>>1.5</option> <option <?=($rows['bath'] == '2') ? 'selected="selected"' : ''?>>2</option> <option <?=($rows['bath'] == '2.5') ? 'selected="selected"' : ''?>>2.5</option> <option <?=($rows['bath'] == '3') ? 'selected="selected"' : ''?>>3</option> <option <?=($rows['bath'] == '3.5') ? 'selected="selected"' : ''?>>3.5</option> <option <?=($rows['bath'] == '4') ? 'selected="selected"' : ''?>>4</option> </select></td> </tr> <tr> <td><div align="right">Square ft.</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="square"></label> <input name="square" type="text" value="<? echo $rows['square']; ?>" id="square" size="6" maxlength="6" /></td> </tr> <tr> <td><div align="right"><span style="color: #F00">*</span>Rent</div></td> <td><div align="center">:</div></td> <td colspan="3" style="text-align: left"><label for="rent"> $ <input name="rent" type="text" value="<? echo $rows['rent']; ?>" id="rent" size="10" maxlength="10" /> </label></td> </tr> <tr> <td><div align="right"><span style="color: #F00">*</span>Fees </div></td> <td><div align="center"> <p>: </p> </div></td> <td colspan="3" style="text-align: left"><label for="fees"></label> <span id="sprytextfield3"> <input name="fees" type="text" id="fees" value="<? echo $rows['fees']; ?>" size="90" /> </span></td> </tr> <tr> <td colspan="5" style="text-align: center; font-weight: bold; font-size: 18px; color: #F00;"> Video Link</td> </tr> <tr> <td><div align="right">URL</div></td> <td><div align="center">:</div></td> <td colspan="3"><p> </p> <p> <input name="url" type="text" id="url" value="<? echo $rows['url']; ?>"size="80" /> </td> </tr> <tr> <td><div align="center" style="color: #F00"> <div align="right">Name Your Video Link</div> </div></td> <td><div align="center"> <p>: </p> </div></td> <td colspan="3"><br /> <p> <input name="videotitle" type="text" id="videotitle" value="<? echo $rows['videotitle']; ?>"size="80" /> <br /> <span style="color: #E62E00">If you posted a URL for your video you must give it a title to give it a link.</span></p></td> </tr> <tr> <td colspan="2" style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> </tr> <tr> <td colspan="2" style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> <td style="text-align: center"> </td> </tr> <tr> <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl1']; ?>" width="200" /><br /></td> <td width="213" style="text-align: center"><img src="<? echo $rows['imageurl2']; ?>" width="200" /></td> <td width="180" style="text-align: center"><img src="<? echo $rows['imageurl3']; ?>" width="200" /></td> <td width="188" style="text-align: center"><img src="<? echo $rows['imageurl4']; ?>" width="200" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><div align="center"> <input id="image3" type="file" name="image1" /> </div></td> <td style="text-align: center"><div align="center"> <input id="image3" type="file" name="image2" /> </div></td> <td style="text-align: center"><div align="center"> <input id="image3" type="file" name="image3" /> </div></td> <td style="text-align: center"><div align="center"> <input id="image4" type="file" name="image4" /> </div></td> </tr> <tr> <td colspan="5" style="text-align: center"> </td> </tr> <tr> <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl5']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl6']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl7']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl8']; ?>" width="200" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><input id="image5" type="file" name="image5" /></td> <td style="text-align: center"><input id="image6" type="file" name="image6" /></td> <td style="text-align: center"><input id="image7" type="file" name="image7" /></td> <td style="text-align: center"><input id="image8" type="file" name="image8" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><img src="<? echo $rows['imageurl9']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl10']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl11']; ?>" width="200" /></td> <td style="text-align: center"><img src="<? echo $rows['imageurl12']; ?>" width="200" /></td> </tr> <tr> <td colspan="2" style="text-align: center"><input id="image9" type="file" name="image9" /></td> <td style="text-align: center"><input id="image10" type="file" name="image10" /></td> <td style="text-align: center"><input id="image11" type="file" name="image11" /></td> <td style="text-align: center"><input id="image12" type="file" name="image12" /></td> </tr> <tr> <td colspan="5" style="text-align: center"> </td> </tr> <tr> <td colspan="5" style="text-align: center"><span style="color: #F00">*</span> REQUIRED FIELDS </td> </tr> <tr> <td colspan="5" style="text-align: center"> PRESS SUBMIT ONCE!!!</td> </tr> <tr> <td colspan="5" style="text-align: center"><input type="submit" name="button" id="button" value="Submit Changes" /> <input type="reset" name="button" id="button" value="Reset" /></td> </tr> </table> </form> </body> </html> The Script Code: [Select] <?php session_start(); include('SimpleImage.php'); $image = new SimpleImage(); //error_reporting(E_ALL); // image upload folder $image_folder = 'images/classified/'; // fieldnames in form $all_file_fields = array('image1', 'image2' ,'image3', 'image4', 'image5', 'image6', 'image7', 'image8', 'image9', 'image10', 'image11', 'image12'); // allowed filetypes $file_types = array('jpg','gif','png'); // max filesize 5mb $max_size = 5000000; //echo'<pre>';print_r($_FILES);exit; $time = time(); $count = 1; foreach($all_file_fields as $fieldname){ if($_FILES[$fieldname]['name'] != ''){ $type = substr($_FILES[$fieldname]['name'], -3, 3); // check filetype if(in_array(strtolower($type), $file_types)){ //check filesize if($_FILES[$fieldname]['size']>$max_size){ $error = "File too big. Max filesize is ".$max_size." MB"; }else{ // new filename $filename = str_replace(' ','',$myusername).'_'.$time.'_'.$count.'.'.$type; // move/upload file $image->load($_FILES[$fieldname]['tmp_name']); if($image->getWidth() > 150) { //if the image is larger that 150. $image->resizeToWidth(500); //resize to 500. } $target_path = $image_folder.basename($filename); //image path. $image->save($target_path); //save image to a directory. //save array with filenames $images[$count] = $image_folder.$filename; $count = $count+1; }//end if }else{ $error = "Please use jpg, gif, png files"; }//end if }//end if }//end foreach if($error != ''){ echo $error; }else{ //error_reporting(E_ALL); //ini_set('display_errors','On'); $id = $_POST['id']; $id = substr($id, 0,5); if($id < 1 || $id > 99999) exit; $servername = "localhost"; $username = ""; $password = ""; if(!$_POST["title"] || !$_POST["rent"] || !$_POST["fees"]){ header('location: fields.php'); }else if (!(preg_match('#^\d+(\.(\d{2}))?$#',($_POST["rent"])))){ header('location: rent.php'); }else{ $conn = mysql_connect($servername,$username,$password)or die(mysql_error()); mysql_select_db("genesis_apts",$conn); // validate id belongs to user $sql_check = "SELECT * FROM apartments WHERE id = '".$id."' AND username = '".$myusername."'"; $res = mysql_query($sql_check,$conn) or die(mysql_error()); $count = mysql_num_rows($res); if ($count > 0){ $sql = "UPDATE apartments SET title = '".mysql_real_escape_string($_POST['title'])."', description = '".mysql_real_escape_string($_POST['description'])."', cross_streets = '".mysql_real_escape_string($_POST['cross_streets'])."', county = '".mysql_real_escape_string($_POST['county'])."', town = '".mysql_real_escape_string($_POST['town'])."', service = '".mysql_real_escape_string($_POST['service'])."', phone = '".mysql_real_escape_string($_POST['phone'])."', contact = '".mysql_real_escape_string($_POST['contact'])."', office = '".mysql_real_escape_string($_POST['office'])."', pets = '".mysql_real_escape_string($_POST['pets'])."', email = '".mysql_real_escape_string($_POST['email'])."', rooms = '".mysql_real_escape_string($_POST['rooms'])."', bath = '".mysql_real_escape_string($_POST['bath'])."', square = '".mysql_real_escape_string($_POST['square'])."', rent = '".mysql_real_escape_string($_POST['rent'])."', fees = '".mysql_real_escape_string($_POST['fees'])."', service = '".mysql_real_escape_string($_POST['service'])."', feeornofee = '".mysql_real_escape_string($_POST['feeornofee'])."', lease = '".mysql_real_escape_string($_POST['lease'])."', url = '".mysql_real_escape_string($_POST['url'])."', zipcode = '".mysql_real_escape_string($_POST['zipcode'])."', videotitle = '".mysql_real_escape_string($_POST['videotitle'])."', imageurl1 = '".mysql_real_escape_string($images[1])."', imageurl2 = '".mysql_real_escape_string($images[2])."', imageurl3 = '".mysql_real_escape_string($images[3])."', imageurl4 ='".mysql_real_escape_string($images[4])."', imageurl5 = '".mysql_real_escape_string($images[5])."', imageurl6 = '".mysql_real_escape_string($images[6])."', imageurl7 = '".mysql_real_escape_string($images[7])."', imageurl8 = '".mysql_real_escape_string($images[8])."', imageurl9 = '".mysql_real_escape_string($images[9])."', imageurl10 = '".mysql_real_escape_string($images[10])."', imageurl11 = '".mysql_real_escape_string($images[11])."', imageurl12 = '".mysql_real_escape_string($images[12])."' WHERE id = '".$id."'"; //replace info with the table name above $result = mysql_query($sql,$conn) or die(mysql_error()); header('location: apartments.php'); }else{ header('location: wrong.php'); } } } ?> Hi
I am developing a website for fun to play around with, like a little fun project and am trying to work out how to upload multiple images that stores the filename in the database and the actual file on the server
I have managed to get it working if I upload just one image but can't work it out for multiple images
Can anyone point me in the right direction or advise where I need to adjust for multiple images upload
I know on the html form on the input tag needs to have multiple and then the name in the input tag be image[] but is as far as I get, it's the PHP I get stuck on
The html for the form is below
<form action="private-add-insert.php" method="post" enctype="multipart/form-data"> Car Make: <input type="text" name="make"> Car Model: <input type="text" name="model"> Exterior Colour: <input type="text" name="exteriorcolour"> Engine Size: <input type="text" name="enginesize"> Fuel Type: <input type="text" name="fueltype"> Year Registered: <input type="text" name="yearregistered"> Transmission: <input type="text" name="transmission"> Mileage: <input type="text" name="mileage"> Number of Doors: <input type="text" name="nodoors"> Body Style: <input type="text" name="bodystyle"> Price: <input type="text" name="price"> <br> <label>Upload Images</label> <input type="file" name="image[]" multiple/> <br /> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> <br /> <input type="submit" value="Submit Listing"> </form>Below is the PHP coding that processes the html form <?php ini_set('display_startup_errors',1); ini_set('display_errors',1); error_reporting(-1); ?> <?php // Start a session for error reporting session_start(); // Call our connection file require("includes/conn.php"); // Check to see if the type of file uploaded is a valid image type function is_valid_type($file) { // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png"); if (in_array($file['type'], $valid_types)) return 1; return 0; } // Just a short function that prints out the contents of an array in a manner that's easy to read // I used this function during debugging but it serves no purpose at run time for this example function showContents($array) { echo "<pre>"; print_r($array); echo "</pre>"; } // Set some constants // This variable is the path to the image folder where all the images are going to be stored // Note that there is a trailing forward slash $TARGET_PATH = "private-listing-images/"; // Get our POSTed variables $make = $_POST['make']; $model = $_POST['model']; $exteriorcolour = $_POST['exteriorcolour']; $enginesize = $_POST['enginesize']; $fueltype = $_POST['fueltype']; $yearregistered = $_POST['yearregistered']; $transmission = $_POST['transmission']; $mileage = $_POST['mileage']; $nodoors = $_POST['nodoors']; $bodystyle = $_POST['bodystyle']; $price = $_POST['price']; $image = $_FILES['image']; // Sanitize our inputs $make = mysql_real_escape_string($make); $model = mysql_real_escape_string($model); $exteriorcolour = mysql_real_escape_string($exteriorcolour); $enginesize = mysql_real_escape_string($enginesize); $fueltype = mysql_real_escape_string($fueltype); $yearregistered = mysql_real_escape_string($yearregistered); $transmission = mysql_real_escape_string($transmission); $mileage = mysql_real_escape_string($mileage); $nodoors = mysql_real_escape_string($nodoors); $bodystyle = mysql_real_escape_string($bodystyle); $price = mysql_real_escape_string($price); $image['name'] = mysql_real_escape_string($image['name']); // Build our target path full string. This is where the file will be moved do // i.e. images/picture.jpg $TARGET_PATH .= $image['name']; // Check to make sure that our file is actually an image // You check the file type instead of the extension because the extension can easily be faked if (!is_valid_type($image)) { $_SESSION['error'] = "You must upload a jpeg, gif, bmp or png"; header("Location: private-add-listing.php"); exit; } // Lets attempt to move the file from its temporary directory to its new home if (move_uploaded_file($image['tmp_name'], $TARGET_PATH)) { // NOTE: This is where a lot of people make mistakes. // We are *not* putting the image into the database; we are putting a reference to the file's location on the server $sql = "insert into privatelistings (make, model, exteriorcolour, enginesize, fueltype, yearregistered, transmission, mileage, nodoors, bodystyle, price, filename) values ('$make', '$model', '$exteriorcolour', '$enginesize', '$fueltype', '$yearregistered', '$transmission', '$mileage', '$nodoors', '$bodystyle', '$price', '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); header("Location: private-add-listing-successfully.php?msg=Listing Added successfully"); exit; } else { // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to // Make sure you chmod the directory to be writeable $_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory"; header("Location: private-add-listing.php"); exit; } ?>I know the coding needs updating to mysqli and prevent sql injections but want to get it working first and then will do them parts Thank you in advance Kind regards Ian I created scripting to upload multiple images simultaneously. The files sizes allowed for upload are 2 MB (or larger) and are then resized to approx 300kb each. In testing, I have discovered that the uploading terminated after 20 images. Is there a variable that needs to be re-defined in order to easily allow uploads of several hundred images? PS: I've seen several conflicting examples for defining max_file_size. What is the correct math to define this parameter? Hey, I have a script which processes an image when it is uploaded, but now i have a new form that allows users to upload four images at a time. I store them in an array in the form like so: name="file[]" So now i am wondering how do i process each image with a forloop because using $_FILES doesn't say which image to check in the array? Hope some one can help me! Heres my code: Code: [Select] <?php if(isset($_POST['submit'])){ echo '<p align="center">'; if ($_FILES["file"]["size"] < 1000000) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { $filename = $_FILES["file"]["name"]; if (file_exists("images/".$name."/".$filename)) { echo "Image already uploaded!"; } else { if (is_dir("userimages/".$name) == FALSE){ mkdir("images/".$name, 0777); } move_uploaded_file($_FILES["file"]["tmp_name"], "userimages/".$name."/" . $filename); echo "Image has been uploaded!"; } } } else { echo "Invalid file"; } } ?> Thanks Hello, For starters I'm not sure if what I want to do is possible, but if it is I would like your input. I have a script that will show a number of fields to fill out in a second form based on the number the user puts into the first from. the problem is that only the last one saves into the database and not all of them. Code: [Select] <form auction="index.php" method="post"> System Name: <input type="text" name="systemname"> Number of E-sites: <input type="text" name="events"> Number of Sigs: <input type="text" name="sigs"><br> <input type="reset" name="reset" value="Reset"> <input type="submit" name="start" value="Start"> </form> <form auction="index.php" method="post"> <?php $events = $_POST['events']; $system = $POST['systemname']; if (isset($_POST['start'])) { $num = $_POST['sigs']; $i = 0; While ($i < $num) { echo "Sig ID: <input type=text name=sigid>"; echo "Type: <input type=text name=type>"; echo "Name: <input type=text name=name>"; echo "Notes: <input type=text name=notes>"; echo "<br>"; $i++; } } ?> <input type="submit" name="enter" value="Enter"> </form> <?php $sigid = $_POST['sigid']; $type = $_POST['type']; $name = $_POST['name']; $notes = $_POST['notes']; mysql_connect('xt', 'x', 'x'); mysql_select_db('wormhole'); if (isset($_POST['enter'])) { $query = "INSERT INTO sites VALUES ('$system','$events','$sigid','$type','$name','$notes')"; mysql_query($query); } ?> How do I get it so all the data saves, lets say that $num = 5, I want all 5 to save not just the last one. I want to display 3 clickable images in a single row which repeats as long as there is data in the database, so far it is displaying a single clickable image from the database. below is all the code.. <table width="362" border="0"> <?php $sql=mysql_query("select * from `publication` GROUP BY `catsue`") or die(mysql_error()); $num=mysql_num_rows($sql); while($rowfor=mysql_fetch_array($sql)) { $cat=$rowfor['catsue']; $pic=mysql_query("select * from `category` where `catsue`='$cat'") or die(mysql_error()); $picP=mysql_fetch_array($pic); $base=basename($picP['title']); ?> <tr> <td width="352" height="88"><table width="408" border="0"> <tr> <td width="113" rowspan="5"><a href="archive_detail.php?id=<?php echo $rowfor['id'];?>&category=<?php echo $rowfor['catsue'];?>"><img src="ad/pic/<?php echo $base;?>" width="100" height="100" border="0"/></a></td> <td width="94">Title</td> <td width="179" height="1"><?php echo $rowfor['catsue'];?> </td> </tr> <tr> <td> </td> <td width="179" height="3"> </td> </tr> <tr> <td> </td> <td width="179" height="8"> </td> </tr> <tr> <td> </td> <td width="179" height="17"> </td> </tr> <tr> <td> </td> <td width="179" height="36"> </td> </tr> </table></td> </tr> <?php }?> </table> this is the line in my script that I have to show the image: Code: [Select] $output .= "<img>{$row['disp_pic']}</img></br>\n"; As you can see I added the image tag, but it wont show the actual image. IE shows it as a small square with another small square picture icon in the middle of it (i'm sure you guys know what i mean). Hi guys its me again, I am having a problem that I cant figure out... Here is my code: <?php $sqlCommand = "SELECT image FROM background"; $query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); $sqlCommand2 = "SELECT backgroundimage FROM site"; $query2 = mysqli_query($myConnection, $sqlCommand2) or die (mysqli_error()); while ($row = mysqli_fetch_array($query)) { while ($row2 = mysqli_fetch_array($query2)) { if($row['image'] == $row2['backgroundimage']){ echo '<img src="site_background/'.$row['image'].'" width="75px" height="75px" style="border:2px solid red;" /><br /><br />'; } if($row['image'] != $row2['backgroundimage']){ echo '<img src="site_background/'.$row['image'].'" width="50px" height="50px" style="border:2px solid black;" />'; } } } mysqli_free_result($query); mysqli_free_result($query2); ?> What is will do is get the images from the "backgrounds" table and the image from the "site" table (the current image). I am then wanting to pick out the current image and give it a red border and then display the other left over images smaller with a black border. I can get the images to all display with the black border or the current image to display with a red border but the other images dont show... I have tried mixing things around but I have not been able to get all the images to display with the formatting I want. I dont know if it is a simple syntax error or I am doing things completely wrong... I have been looking at it for so long its just become one big mess of code to me lol Any help to get this working as I want would be great! Cheers Ben Is it better to store uploaded images as 'content' in the database? (like he http://www.techsupportforum.com/forums/f49/tutorial-upload-files-to-database-176804.html).. Or just as a regular file which is referenced in the database..? One image is displaying but when i choose image 2 it overlaps image 1..
gallery.php 8.77KB
7 downloads
I am trying to add a second image upload to a form I have, but I can't figure out how to get the insert statement and upload statement working properly. The first file uploads and inserts to the database properly, but can anyone tell me how to add a second image to the mix? Here is what I currently have: Code: [Select] //if ((($_FILES["file"]["type"] == "image/gif") //|| ($_FILES["file"]["type"] == "image/jpeg") //|| ($_FILES["file"]["type"] == "image/pjpeg")) //&& ($_FILES["file"]["size"] < 20000)) // { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { //echo "Upload: " . $_FILES["file"]["name"] . "<br />"; //echo "Type: " . $_FILES["file"]["type"] . "<br />"; //echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; //echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); //echo "Stored in: " . "http://www.webdesignsbyliz.com/wdbl_wordpress/wp-content/themes/twentyten_2/upload/" . $_FILES["file"]["name"]; $image = $_FILES["file"]["name"]; $query = "INSERT INTO gallery VALUES ('', '$cut', '$color', '$carats', '$clarity', '$size', '$metal', '$other', '$total', '$certificate', '$value', '$image', '$name', '$desc', '$item_no', '$type', '$image2')"; $query_res = mysql_query($query) or die(mysql_error()); } } I thought I could simply add a second move_uploaded_file line and replace "file" with "file2" (the name of my second file upload field from the form), but it's not working. Can anyone tell me the right way to do this, please? Thanks in advance! I'm not experienced with file uploads yet :-( I've looked around at a bunch of sample code and cannot seem to get this to work. I'm trying to create a table with the values provided in a form along with an uploaded image. Here is what I have. Code: [Select] <?php //Set variables from form $title = $_POST["title_textfield"]; $description = $_POST["description_textbox"]; $price = $_POST["price_textfield"]; $time = date("ymdHis"); $me = $myuserID /Create Table $con = mysql_connect("mydatabase.mysql.com","databaseAdmin","Adminpass"); if (!$con) { die('Could not connect: ' . mysql_error()); } //check if table exists // Create table $time = date("ymdHis"); $tablename = "1_$me$time"; mysql_select_db("db_01", $con); $sql = "CREATE TABLE $tablename ( ID int NOT NULL AUTO_INCREMENT, imageData LONGBLOB NOT NULL , PRIMARY KEY(comicID), Owner varchar(15), Status varchar(15), AgeRestriction varchar(25), Title varchar(25), Description varchar(100), Price varchar(15) )"; // Execute query mysql_query($sql,$con); //input info into table mysql_query("INSERT INTO $tablename (Owner, Status, Title, Description, Price) VALUES ('$myid', 'Pending', '$title', '$description', '$price')"); //Image control!!!! $maxFileSize = "2000000"; // 2 MB file size //Initializing the image types. $image_array = array("image/jpeg","image/jpg","image/gif","image/bmp","image/pjpeg","image/png"); // valid image type //store the file type of the uploading file. $fileType = $_FILES['userfile']['type']; $nname= $_FILES['userfile']['name']; echo "$nname"; //Initializing the msg variable. Although , not necessary. $msg = ""; // if Submit button is clicked if(@$_POST['Submit']) { // check for the image type , before uploading if (in_array($fileType, $image_array)) { // check whether the file is uploaded if(is_uploaded_file($_FILES['userfile']['tmp_name'])) { // check whether the file size is below 2 mb if($_FILES['userfile']['size'] < $maxFileSize) { // reading the image data $imageData =addslashes (file_get_contents($_FILES['userfile']['tmp_name'])); // inserting into the database $sql = "INSERT INTO $tablename (imageData) VALUES ('$imageData')"; mysql_query($sql) or die(mysql_error()); $msg = " Data successfully uploaded"; } else { $msg = " Error : File size exceeds the maximum limit "; } } } else { $msg = "Error: Not a valid image "; } } mysql_close($con); ?> All the fields populate just fine except the imageData field which shows "[BLOB - 0 Bytes]" Any help would be GREATLY appreciated. Thank you for even taking the time to look. Cordially, TcS Hi guys, I have this project that I'm working on. It is a simple html form that allows you to choose 5 images to upload and one of them is going to be the main image of the listing. It will also ask you for living area, name for listing, address, price, rooms, and restrooms. I need it to upload all info into a mysql database with php. I can make a simple listing with one picture uploaded but I really have no idea how to get more than one image uploaded that way I can recall them later or edit the images later. Can anyone gime some ideas please? This will only send 1 goggles information into the database but I have a "adding" page that can actually add more than 1 goggles at once. I have no idea how to go about saving multiple goggle's information using array or loop. $name= $_POST['goggles_name']; $price = $_POST['goggles_price']; $des = $_POST['goggles_description']; $file = $_FILES['goggles_image']['name']; $chkbox = $_POST['upload']; $id = $_POST['goggles_id']; $query = "UPDATE goggles SET goggles_name = '$name' , goggles_price = '$price' ,goggles_description = '$des' WHERE goggles_id ='".$id."' "; $result = mysqli_query($link, $query) or die(mysqli_error($link)); |