PHP - Uploading Image With Php Into Mysql Database.
Hi guys, I have this code that I created. It is suppost to get a file from a form and upload it to a directory that is outside the root folder of my webserver. then the image name is added to the preset location of the directory that contains all of the uploaded images and is placed into a mysql database so I can call it later. the problem I have is that when some one else signs up through this form and the file they upload has the same file name it replaces the one that is already in the images directory that has all the other pictures. I need to add something to this code that adds $username to the end of the original file name and then uploads it to the directory with the new name. Since every username is unique it will make every username unique and will eliminate my problem. I am not sure how to do this. Please, anyone that can help. Thanks.
This is my code. // get file attributes!!!!! $photoname = $_FILES['photo']['name']; $tmp_name = $_FILES['photo']['tmp_name']; if ($photoname) { // start upload process $location = "../userpictures/$photoname"; move_uploaded_file($tmp_name,$location); } else { $location = "../userpictures/nophoto.png"; } $queryreg = mysql_query(" INSERT INTO users VALUES ('','$fullname','$username','$password','$date','$location','$email','$phone') "); If there is a better way to upload images to a mysql database and outputting it later then please let me know as well. Thanks. Similar TutorialsGreetings, What I'm trying to do is have users upload their event information into a database which would include a flyer. I don't want the image file to go into the database (other than the filename) rather I'd like it to be dropped into a directory. In the same script I'd like to dynamically generate a thumbnail. I have the two scripts and separately they work fine, but I can't get them to work together. I'm guessing the conflict because the thumbnail script is using $_POST and the mysql script is using $_SESSION. If so how can I modify them to both use $_SESSION? The thumbnail script is goes from line 1 - 146 and the mysql portion is the rest. The results of processing this look something like this. QUERY TEXT: INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) VALUES ('12', 'spooky times', 'Ironwood Stage & Grill', '2010-12-17 22:36:00', 'DNB', '5000', 'me', '174366-1.jpg') <?php $debug = FALSE; /********************************************************************************************** CREATES THUMBNAIL **********************************************************************************************/ //define a maxim size for the uploaded images define ("MAX_SIZE","1024"); // define the width and height for the thumbnail // note that theese dimmensions are considered the maximum dimmension and are not fixed, // because we have to keep the image ratio intact or it will be deformed define ("WIDTH","500"); define ("HEIGHT","650"); // this is the function that will create the thumbnail image from the uploaded image // the resize will be done considering the width and height defined, but without deforming the image function make_thumb($img_name,$filename,$new_w,$new_h) { //get image extension. $ext=getExtension($img_name); //creates the new image using the appropriate function from gd library if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext) || !strcmp("JPG",$ext)) $src_img=imagecreatefromjpeg($img_name); if(!strcmp("png",$ext) || !strcmp("PNG",$ext)) $src_img=imagecreatefrompng($img_name); //gets the dimmensions of the image $old_x=imageSX($src_img); $old_y=imageSY($src_img); // next we will calculate the new dimmensions for the thumbnail image // the next steps will be taken: // 1. calculate the ratio by dividing the old dimmensions with the new ones // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable // and the height will be calculated so the image ratio will not change // 3. otherwise we will use the height ratio for the image // as a result, only one of the dimmensions will be from the fixed ones $ratio1=$old_x/$new_w; $ratio2=$old_y/$new_h; if($ratio1>$ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; } // we create a new image with the new dimmensions $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h); // resize the big image to the new created one imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); // output the created image to the file. Now we will have the thumbnail into the file named by $filename if(!strcmp("png",$ext)) imagepng($dst_img,$filename); else imagejpeg($dst_img,$filename); //destroys source and destination images. imagedestroy($dst_img); imagedestroy($src_img); } // This function reads the extension of the file. // It is used to determine if the file is an image by checking the extension. function getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } // This variable is used as a flag. The value is initialized with 0 (meaning no error found) // and it will be changed to 1 if an error occurs. If the error occurs the file will not be uploaded. $errors=0; // checks if the form has been submitted if(isset($_POST['Submit'])) { //reads the name of the file the user submitted for uploading $image=$_FILES['eventflyer']['name']; // if it is not empty if ($image) { // get the original name of the file from the clients machine $filename = stripslashes($_FILES['eventflyer']['name']); // get the extension of the file in a lower case format $extension = getExtension($filename); $extension = strtolower($extension); // if it is not a known extension, we will suppose it is an error, print an error message // and will not upload the file, otherwise we continue if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "JPG") && ($extension != "PNG") && ($extension != "png")) { echo '<h1>Unknown extension!</h1>'; $errors=1; } else { // get the size of the image in bytes // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which // the uploaded file was stored on the server $size=getimagesize($_FILES['eventflyer']['tmp_name']); $sizekb=filesize($_FILES['eventflyer']['tmp_name']); //compare the size with the maxim size we defined and print error if bigger if ($sizekb > MAX_SIZE*500) { echo '<h1>You have exceeded the size limit!</h1>'; $errors=1; } //we will give an unique name, for example the time in unix time format $image_name=$filename; //the new name will be containing the full path where will be stored (images folder) $newname="flyers/".$image_name; $copied = copy($_FILES['eventflyer']['tmp_name'], $newname); //we verify if the image has been uploaded, and print error instead if (!$copied) { echo '<h1>Copy unsuccessfull!</h1>'; $errors=1; } else { // the new thumbnail image will be placed in images/thumbs/ folder $thumb_name='flyers/thumb_'.$image_name; // call the function that will create the thumbnail. The function will get as parameters // the image name, the thumbnail name and the width and height desired for the thumbnail $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT); }} }} //If no errors registred, print the success message and show the thumbnail image created if(isset($_POST['Submit']) && !$errors) { echo "<h1>Thumbnail created Successfully!</h1>"; echo '<img src="'.$thumb_name.'">'; } /************************************************************ Adjust the headers... ************************************************************/ header("Expires: Thu, 17 May 2001 10:17:17 GMT"); // Date in the past header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header ("Pragma: no-cache"); // HTTP/1.0 /***************************************************************************** Check the session details. we will store all the post variables in session variables this will make it easier to work with the verification routines *****************************************************************************/ session_start(); if (!isset($_SESSION['SESSION'])) require_once( "../include/session_init.php"); $arVal = array(); require_once("../include/session_funcs1.php"); reset ($_POST); while (list ($key, $val) = each ($_POST)) { if ($val == "") $val = "NULL"; $arVals[$key] = (get_magic_quotes_gpc()) ? $val : addslashes($val); if ($val == "NULL") $_SESSION[$key] = NULL; else $_SESSION[$key] = $val; if ($debug) echo $key . " : " . $arVals[$key] . "<br>"; } /********************************************************************************************** Make sure session variables have been set and then check for required fields otherwise return to the registration form to fix the errors. **********************************************************************************************/ // check to see if these variables have been set... if ((!isset($_SESSION["eventname"])) || (!isset($_SESSION["eventvenue"])) || (!isset($_SESSION["eventdate"])) || (!isset($_SESSION["eventgenre"])) || (!isset($_SESSION["eventprice"])) || (!isset($_SESSION["eventpromoter"])) || (!isset($_SESSION["eventflyer"]))) { resendToForm("?flg=red"); } // form variables must have something in them... if ($_SESSION['eventname'] == "" || $_SESSION['eventvenue'] == "" || $_SESSION['eventdate'] == "" || $_SESSION['eventgenre'] == "" || $_SESSION['eventprice'] == "" || $_SESSION['eventpromoter'] == "" || $_SESSION['eventflyer'] == "") { resendToForm("?flg=red"); } /********************************************************************************************** Insert into the database... **********************************************************************************************/ $conn = mysql_connect($_SESSION['MYSQL_SERVER1'],$_SESSION['MYSQL_LOGIN1'],$_SESSION['MYSQL_PASS1']) or die ('Error connecting to mysql'); mysql_select_db($_SESSION['MYSQL_DB1']) or die("Unable to select database"); $eventgenre_sel = addslashes($_REQUEST['eventgenre_sel']); $eventname = addslashes($_REQUEST['eventname']); $eventvenue = addslashes($_REQUEST['eventvenue']); $eventdate = addslashes($_REQUEST['eventdate']); $eventgenre = addslashes($_REQUEST['eventgenre']); $eventprice = addslashes($_REQUEST['eventprice']); $eventpromoter = addslashes($_REQUEST['eventpromoter']); $eventflyer = addslashes($_REQUEST['eventflyer']); $sqlquery = "INSERT INTO td_events (eventgenre_sel, eventname, eventvenue, eventdate, eventgenre, eventprice, eventpromoter, eventflyer) " ."VALUES ('$eventgenre_sel', '$eventname', '$eventvenue', '$eventdate', '$eventgenre', '$eventprice', '$eventpromoter', '$eventflyer')"; echo 'QUERY TEXT:<br />'.$sqlquery; $result = MYSQL_QUERY($sqlquery); $insertid = mysql_insert_id(); /*** This following function will update session variables and resend to the form so the user can fix errors ***/ function resendToForm($flags) { reset ($_POST); // store variables in session... while (list ($key, $val) = each ($_POST)) { $_SESSION[$key] = $val; } // go back to the form... //echo $flags; header("Location: /user_registration.php".$flags); exit; } mysql_close($conn); ?> when i input this code it only uploads a single column into my database
<html> <head> <title>MySQL file upload example</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="try2.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" name="submit"value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> </body> <?php $con=mysqli_connect("localhost","root","","book"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if(isset($_POST['submit'])) { $fname = $_FILES['uploaded_file']['name']; $chk_ext = explode(".",$fname); if(strtolower($chk_ext[1]) == "csv") { $filename = $_FILES['uploaded_file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $sql = "INSERT into data(name,Groups,phone_number) values('$data[0]','$data[1]','$data[2]')"; $result=mysqli_query($con,$sql) or die(mysql_error()); } fclose($handle); echo "Successfully Imported"; } else { echo "Invalid File"; } } ?> </html> I am very new to php and am trying to create a simple application that uploads a PDF file to a database. I have one field for the Volume Number and on file field for the PDF to be uploaded. My issue is i can't get the PDF to upload or insert the name of the pdf (eg volume1.pdf) into the data base. I would also like to point out that I know i have a low post count, but i only seek help when i truly need it and have exhausted all other resources... Here is what i have, please go easy on me this is my first round at php: Code: [Select] <?php if(isset($_POST['submit'])){ $vol_num = $_POST['vol_num']; $pdf = $_FILES['pdf']['name']; $path = '../pdf/'.$_FILES['pdf']['name']; move_uploaded_file($_FILES["pdf"]["tmp_name"], $path); mysql_query("INSERT INTO volumes set vol_num='$vol_num', vol_link='$pdf'") or die (mysql_error()); echo "<script>location.href='add_volume.php'</script>"; } ?> what am i doing wrong here? Thanks in advance Hi, I'm not 100% sure if this is HTML, PHP or Javascript, but my best guess is PHP. When you upload an image on Facebook, it automatically gathers the data about the image, i.e. size, device used (i.e. Canon, iPhone), title and description. It then outputs this on the page. Is there anyway to do this with PHP, instead of having to type all the information out again and upload that with the photo to a database? Cheers. I am looking to resize the images (hight and width) after I have uploaded to a folder with php. What the bast way to do this. I am unable to resize them before I upload as I use the same picture in other areas. I'm using this code to view the image and other infomation on the database can some one point me in the right direction or show me how to change the code below. Thanks Code: [Select] <?php mysql_connect("localhost", "", "") or die(mysql_error()) ; mysql_select_db("stafflog") or die(mysql_error()) ; $data = mysql_query("SELECT * FROM ********") or die(mysql_error()); while($info = mysql_fetch_array( $data )) { echo "<img src=http://www.web.com/productimages/" .$info['image'] . "> <br>"; echo "<b>Name:</b> ".$info['yourname'] . "<br> "; echo "<b>price:</b> ".$info['price'] . " <br>"; echo "<b>shortdes:</b> ".$info['shortdes'] . " <hr>"; } ?> hi everyone im new to php. I have been reading few books. im trying to build a image gallery. the first step is to upload a images. in the process of uploading, i want to resize the image then add watermark last insert into the database which is mysql, (i know about the dont insert image into database thing). here is the form script Code: [Select] <?php require_once('globals.php'); ?> <html> <head> <title>Upload an Image</title> </head> <body> <div> <h1>Upload an Image</h1> <p> <a href="./">View uploaded images</a> </p> <form method="post" action="process.php" enctype="multipart/form-data"> <div> <input type="file" name="image" /> <input type="submit" value="Upload Image" /> </div> </form> </div> <!-- <form action="watermark-image.php" method="post" enctype="multipart/form-data"> Select a file to upload for processing<br> <input type="file" name="File1"><br> <input type="submit" value="Submit File"> </form> --> </body> </html> here is the watermark script Code: [Select] <?php require_once('globals.php'); ?> <html> <head> <title>Upload an Image</title> </head> <body> <div> <h1>Upload an Image</h1> <p> <a href="./">View uploaded images</a> </p> <form method="post" action="process.php" enctype="multipart/form-data"> <div> <input type="file" name="image" /> <input type="submit" value="Upload Image" /> </div> </form> </div> <!-- <form action="watermark-image.php" method="post" enctype="multipart/form-data"> Select a file to upload for processing<br> <input type="file" name="File1"><br> <input type="submit" value="Submit File"> </form> --> </body> </html> here is my resize script Code: [Select] <?php # ========================================================================# # # Author: Jarrod Oberto # Version: 1.0 # Date: 17-Jan-10 # Purpose: Resizes and saves image # Requires : Requires PHP5, GD library. # Usage Example: # include("classes/resize_class.php"); # $resizeObj = new resize('images/cars/large/input.jpg'); # $resizeObj -> resizeImage(150, 100, 0); # $resizeObj -> saveImage('images/cars/large/output.jpg', 100); # # # ========================================================================# Class resize { // *** Class variables private $image; private $width; private $height; private $imageResized; function __construct($fileName) { // *** Open up the file $this->image = $this->openImage($fileName); // *** Get width and height $this->width = imagesx($this->image); $this->height = imagesy($this->image); } ## -------------------------------------------------------- private function openImage($file) { // *** Get extension $extension = strtolower(strrchr($file, '.')); switch($extension) { case '.jpg': case '.jpeg': $img = @imagecreatefromjpeg($file); break; case '.gif': $img = @imagecreatefromgif($file); break; case '.png': $img = @imagecreatefrompng($file); break; default: $img = false; break; } return $img; } ## -------------------------------------------------------- public function resizeImage($newWidth, $newHeight, $option="auto") { // *** Get optimal width and height - based on $option $optionArray = $this->getDimensions($newWidth, $newHeight, $option); $optimalWidth = $optionArray['optimalWidth']; $optimalHeight = $optionArray['optimalHeight']; // *** Resample - create image canvas of x, y size $this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight); imagecopyresampled($this->imageResized, $this->image, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->width, $this->height); // *** if option is 'crop', then crop too if ($option == 'crop') { $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight); } } ## -------------------------------------------------------- private function getDimensions($newWidth, $newHeight, $option) { switch ($option) { case 'exact': $optimalWidth = $newWidth; $optimalHeight= $newHeight; break; case 'portrait': $optimalWidth = $this->getSizeByFixedHeight($newHeight); $optimalHeight= $newHeight; break; case 'landscape': $optimalWidth = $newWidth; $optimalHeight= $this->getSizeByFixedWidth($newWidth); break; case 'auto': $optionArray = $this->getSizeByAuto($newWidth, $newHeight); $optimalWidth = $optionArray['optimalWidth']; $optimalHeight = $optionArray['optimalHeight']; break; case 'crop': $optionArray = $this->getOptimalCrop($newWidth, $newHeight); $optimalWidth = $optionArray['optimalWidth']; $optimalHeight = $optionArray['optimalHeight']; break; } return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight); } ## -------------------------------------------------------- private function getSizeByFixedHeight($newHeight) { $ratio = $this->width / $this->height; $newWidth = $newHeight * $ratio; return $newWidth; } private function getSizeByFixedWidth($newWidth) { $ratio = $this->height / $this->width; $newHeight = $newWidth * $ratio; return $newHeight; } private function getSizeByAuto($newWidth, $newHeight) { if ($this->height < $this->width) // *** Image to be resized is wider (landscape) { $optimalWidth = $newWidth; $optimalHeight= $this->getSizeByFixedWidth($newWidth); } elseif ($this->height > $this->width) // *** Image to be resized is taller (portrait) { $optimalWidth = $this->getSizeByFixedHeight($newHeight); $optimalHeight= $newHeight; } else // *** Image to be resizerd is a square { if ($newHeight < $newWidth) { $optimalWidth = $newWidth; $optimalHeight= $this->getSizeByFixedWidth($newWidth); } else if ($newHeight > $newWidth) { $optimalWidth = $this->getSizeByFixedHeight($newHeight); $optimalHeight= $newHeight; } else { // *** Sqaure being resized to a square $optimalWidth = $newWidth; $optimalHeight= $newHeight; } } return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight); } ## -------------------------------------------------------- private function getOptimalCrop($newWidth, $newHeight) { $heightRatio = $this->height / $newHeight; $widthRatio = $this->width / $newWidth; if ($heightRatio < $widthRatio) { $optimalRatio = $heightRatio; } else { $optimalRatio = $widthRatio; } $optimalHeight = $this->height / $optimalRatio; $optimalWidth = $this->width / $optimalRatio; return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight); } ## -------------------------------------------------------- private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight) { // *** Find center - this will be used for the crop $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 ); $cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 ); $crop = $this->imageResized; //imagedestroy($this->imageResized); // *** Now crop from center to exact requested size $this->imageResized = imagecreatetruecolor($newWidth , $newHeight); imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight); } ## -------------------------------------------------------- public function saveImage($savePath, $imageQuality="100") { // *** Get extension $extension = strrchr($savePath, '.'); $extension = strtolower($extension); switch($extension) { case '.jpg': case '.jpeg': if (imagetypes() & IMG_JPG) { imagejpeg($this->imageResized, $savePath, $imageQuality); } break; case '.gif': if (imagetypes() & IMG_GIF) { imagegif($this->imageResized, $savePath); } break; case '.png': // *** Scale quality from 0-100 to 0-9 $scaleQuality = round(($imageQuality/100) * 9); // *** Invert quality setting as 0 is best, not 9 $invertScaleQuality = 9 - $scaleQuality; if (imagetypes() & IMG_PNG) { imagepng($this->imageResized, $savePath, $invertScaleQuality); } break; // ... etc default: // *** No extension - No save. break; } imagedestroy($this->imageResized); } ## -------------------------------------------------------- } ?> here is the insert database script Code: [Select] <?php require_once('globals.php'); function assertValidUpload($code) { if ($code == UPLOAD_ERR_OK) { return; } switch ($code) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $msg = 'Image is too large'; break; case UPLOAD_ERR_PARTIAL: $msg = 'Image was only partially uploaded'; break; case UPLOAD_ERR_NO_FILE: $msg = 'No image was uploaded'; break; case UPLOAD_ERR_NO_TMP_DIR: $msg = 'Upload folder not found'; break; case UPLOAD_ERR_CANT_WRITE: $msg = 'Unable to write uploaded file'; break; case UPLOAD_ERR_EXTENSION: $msg = 'Upload failed due to extension'; break; default: $msg = 'Unknown error'; } throw new Exception($msg); } $errors = array(); try { if (!array_key_exists('image', $_FILES)) { throw new Exception('Image not found in uploaded data'); } $image = $_FILES['image']; // ensure the file was successfully uploaded assertValidUpload($image['error']); if (!is_uploaded_file($image['tmp_name'])) { throw new Exception('File is not an uploaded file'); } $info = getImageSize($image['tmp_name']); if (!$info) { throw new Exception('File is not an image'); } } catch (Exception $ex) { $errors[] = $ex->getMessage(); } if (count($errors) == 0) { // no errors, so insert the image $query = sprintf( "insert into images (filename, mime_type, file_size, file_data) values ('%s', '%s', %d, '%s')", mysql_real_escape_string($image['name']), mysql_real_escape_string($info['mime']), $image['size'], mysql_real_escape_string( file_get_contents($image['tmp_name']) ) ); mysql_query($query, $db); $id = (int) mysql_insert_id($db); // finally, redirect the user to view the new image header('Location: view.php?id=' . $id); exit; } ?> <html> <head> <title>Error</title> </head> <body> <div> <p> The following errors occurred: </p> <ul> <?php foreach ($errors as $error) { ?> <li> <?php echo htmlSpecialChars($error) ?> </li> <?php } ?> </ul> <p> <a href="upload.php">Try again</a> </p> </div> </body> </html> here is my view script Code: [Select] <?php require_once('globals.php'); try { if (!isset($_GET['id'])) { throw new Exception('ID not specified'); } $id = (int) $_GET['id']; if ($id <= 0) { throw new Exception('Invalid ID specified'); } $query = sprintf('select * from images where image_id = %d', $id); $result = mysql_query($query, $db); if (mysql_num_rows($result) == 0) { throw new Exception('Image with specified ID not found'); } $image = mysql_fetch_array($result); } catch (Exception $ex) { header('HTTP/1.0 404 Not Found'); exit; } header('Content-type: ' . $image['mime_type']); header('Content-length: ' . $image['file_size']); echo $image['file_data']; ?> my main question is how to link them all together. any clues i appreciatte Hello freaks! Im new to this forum, but im not all that new to PHP and MySQL. Although there's been some years since the last time I used it, so don't go all freaky on me if I dont do this right Let's go on-topic: Im in progress of making an internal web-page for me and my colleagues to make things a bit easier for us. I am making an database of our different projects, and I need some help with the input form - as I need to upload an image to the server, and store the path in the MySQL database. In my input form, I need to store information from text fields, and I need to upload an image to the server and store the path in the database. Before I can even start to code this (although I have coded the input forum without the upload), I need to know what would be the best way to do this. I guess there are several ways.. What would the expert do (That's you right?)? Should I have the information input, and image upload in the same form, or should I make a second form (maybe on a different page) for the upload? Is it necessary with two tables, one for the info and one for the image path, and then tie them together with the imageID, or is it fine to use just one table? Any thoughts would be appreciated! <!-- TechThat --> Not really sure how to get the images I have stored in MySQL into a html form. I can call-up the text fields from the database but it cannot seem to find the index for the images. Here is my code:- <?php session_start(); mysql_connect("localhost","root","abc") or die ("Error! Cannot connect to database"); mysql_select_db("theimageworks") or die ("Cannot find database"); $query = "SELECT * FROM jobs"; $result = mysql_query($query) or die (mysql_error()); ?> <?php //display data in html table echo "<table>"; echo "<tr><td>Username</td><td align='center'>Message</td><td>Product Image</td></tr>"; while($row = mysql_fetch_array($result)) { echo "</td><td>"; echo $row['username']; echo "</td><td>"; echo $row['message']; echo "</td></tr>"; echo $row['image']; } echo "</table>"; ?> The error message I get is "Notice: Undefined index: image in....." Thanks in advance! I am in the process of writing a CMS for a friend that is looking to add a classified section to his site. He will be the only one that will ever use it. I got the code to work with one image when he asked me if I could do it so he could post 6 images for each item. I am unable to figure out how to do this. I was told to do this with a while loop. This is the code that I have written so far. <?php //Check to make sure title is filled in. If not redirects to show_add.php if (!$_POST[title]) { header("Location: show_add.php"); exit; } else { //check and see if a session has started session_start(); } //if session has not been properly started redirects back to the administration menu if ($_SESSION[valid] != "yes") { header("Location: admin_menu.php"); exit; } include('includes/connection.php'); //check and see if the type of uploaded file is an image function is_valid_type($file) { $valid_types = array("image/jpg", "image/jpeg", "image/gif", "image/bmp"); if (in_array($file['type'], $valid_types)) return 1; return 0; } //Set Constants $TARGET_PATH = "/home/content/m/i/k/mikedmartiny/html/db_images/"; $title = $_POST['title']; $year = $_POST['year']; $make = $_POST['make']; $model = $_POST['model']; $descript = $_POST['descript']; $image = $_FILES['image']; //Sanitize the inputs $title = mysql_real_escape_string($title); $year = mysql_real_escape_string($year); $make = mysql_real_escape_string($make); $model = mysql_real_escape_string($model); $descript = mysql_real_escape_string($descript); $image['name'] = mysql_real_escape_string($image['name']); //$target_path full string $TARGET_PATH .= $image['name']; //make sure that all fields from form are filled in if ( $title == "" || $year == "" || $make =="" || $model == "" || $descript == "" || $image['name'] == "") { $_SESSION['error'] = "ALL FIELDS ARE REQUIRED!"; header ("Location: show_add.php"); exit; } //check to make sure it has the right file type if (!is_valid_type($image)){ $_SESSION['error'] = "You must upload a jpeg, gif, or bmp"; header ("Location: show_add.php"); exit; } //check to see if a file with that name exsists if (file_exists($TARGET_PATH)){ $_SESSION['error'] = "A FILE WITH THAT NAME ALL READY EXIST!"; header ("Location: show_add.php"); exit; } //move the image - write path to database while($image <=2) { move_uploaded_file($image['tmp_name'], $TARGET_PATH) } else { // Make sure you chmod the directory to be writeable $_SESSION['error'] = "COULD NOT UPLOAD FILE. CHECK WRITE/REWRITE PERMISSIONS ON THE FILE DIRECTORY!"; header ("Location: show_add.php"); exit; } $sql = "INSERT INTO $table (id, title, year, make, model, descript, image, image_two) VALUES ('', '$_POST[title]', '$_POST[year]', '$_POST[make]', '$_POST[model]', '$_POST[descript]', '" . $image['name'] . "', '" . $image['name'] . "')"; $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); ?> I only have it set up to work with 2 images right now. I thought it would be easier to get it to work properly. Then I could just add in the rest of the info later. Any help would be greatly appreciated. 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 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 :-( hey guys, I'm getting a problem uploading my csv file to mysql database, the code on the top half just makes sure that I don't import data that I don't want into the database, numbers that are too high or too low on certain rows, and the second half is importing the array that I create from the csv file into the database however I'm getting the following error
Duplicate entry 'Array' for key 'strProductCode'
Now I've never had this error before and I'm not sure what's causing it so any help would be very much appreciated
$data = array(); if (($handle = fopen("stock.csv", "r")) !== FALSE) { while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) { // only add rows to the array where the 4th column value is greater than or equal to 10 if(($row[3] >= 10 && $row[4] >= 5) OR ($row[3] >= 0 AND $row[4] > 5)){ if($row[4] < 1000){ $data[] = $row; } } } foreach ($data as &$value) { mysql_query("INSERT INTO tblProductData (intProductDataId, strProductCode, strProductName, strProductDesc, strProductStock, strProductCost, dtmDiscontinued, dtmAdded, stmTimestamp) VALUES(null, '$data[0]', '$data[1]', '$data[2]', '$data[3]', '$data[4]', 'time', 'added', 'time') ") or die(mysql_error()); } } Hi.. I have code for importing .xml file to database. the problem is I cannot upload my file but no error display. And also I got a problem in importing data from .xml file to database but not all row will be save. here is my code: Code: [Select] <?php $data = array(); $con = mysql_connect("localhost", "root",""); if (!$con) { die(mysql_error()); } $db = mysql_select_db("mes", $con); if (!$db) { die(mysql_error()); } $sql = "select * from sales_order"; $result = mysql_query($sql); if (!$result) { die(mysql_error()); } function add_employee($ProductType,$WorkOrder,$POIssueDate,$SalesMonth) { global $data; $con = mysql_connect("localhost", "root",""); if (!$con){ die(mysql_error());} $db = mysql_select_db("mes", $con); if (!$db) { die(mysql_error()); } $ProductType= $ProductType; $WorkOrder = $WorkOrder; $POIssueDate = $POIssueDate; $SalesMonth = $SalesMonth; $sql = "INSERT INTO sales_order (ProductType,WorkOrder,POIssueDate,SalesMonth) VALUES ('$ProductType','$WorkOrder','$POIssueDate','$SalesMonth')" or die(mysql_error()); mysql_query($sql, $con); $data []= array('ProductType'=>$ProductType,'WorkOrder'=>$WorkOrder,'POIssueDate'=>$POIssueDate,'SalesMOnth'=>$SalesMonth); } if ( $_FILES['file']['tmp_name'] ['error']) //f (empty($_FILES['file']['tmp_name']['error'])) { //$dom = DOMDocument::load('SalesOrder.xml'); $dom = DOMDocument::load($_FILES['file']['tmp_name']); $dom = DOMDocument::__construct(); $rows = $dom->getElementsByTagName('Row'); global $last_row; $last_row = false; $first_row = true; foreach ($rows as $row) { if ( !$first_row ) { $ProductType = ""; $WorkOrder = ""; $POIssueDate = ""; $SalesMonth = ""; $index = 1; $cells = $row->getElementsByTagName( 'Cell' ); foreach( $cells as $cell ) { $ind = $cell->getAttribute( 'Index' ); if ( $ind != null ) $index = $ind; if ( $index == 1 ) $ProductType = $cell->nodeValue; if ( $index == 2 ) $WorkOrder = $cell->nodeValue; if ( $index == 3 ) $POIssueDate = $cell->nodeValue; if ( $index == 4 ) $SalesMonth = $cell->nodeValue; $index += 1; } if ($ProductType=='' AND $WorkOrder=='' AND $POIssueDate=='' AND $SalesMonth=='') { $last_row = true; } else { add_employee($ProductType,$WorkOrder,$POIssueDate,$SalesMonth); } } if ($last_row==true) { $first_row = true; } else { $first_row = false; } } } ?> <html> <body> <table> <tr> <th>Sales Order</th> </tr> <?php foreach( $data as $row ) { ?> <tr> <td><?php echo( $row['ProductType'] ); ?></td> <td><?php echo( $row['WorkOrder'] ); ?></td> <td><?php echo( $row['POIssueDate']) ;?> </td> <td><?php echo( $row['SalesMonth'] ); ?></td> </tr> <?php } ?> </table> </body> </html> and I will attach my sample data and the data with color yellow background is only row I want to save to my database. Thank you so much.. Dear 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> Hello
I want to know to upload the XML file to mysql using php as i am new to xml any help appreciated.
awaiting your valuable reply
here also i am attaching the xml file which i want to upload
Thanks in Advance
Attached Files
xml1.xml 4.89KB
2 downloads Can I get some help or a point in the right direction.
I am trying to create a form that allows me to add, edit and delete records from a database.
I can add, edit and delete if I dont include the image upload code.
If I include the upload code I cant edit records without having to upload the the same image to make the record save to the database.
So I can tell I have got the code processing in the wrong way, thing is I cant seem to see or grasp the flow of this, to make the corrections I need it work.
Any help would be great!
Here is the form add.php code
<?php require_once ("dbconnection.php"); $id=""; $venue_name=""; $address=""; $city=""; $post_code=""; $country_code=""; $url=""; $email=""; $description=""; $img_url=""; $tags=""; if(isset($_GET['id'])){ $id = $_GET['id']; $sqlLoader="Select from venue where id=?"; $resLoader=$db->prepare($sqlLoader); $resLoader->execute(array($id)); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Add Venue Page</title> <link href='http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <?php $sqladd="Select * from venue where id=?"; $resadd=$db->prepare($sqladd); $resadd->execute(array($id)); while($rowadd = $resadd->fetch(PDO::FETCH_ASSOC)){ $v_id=$rowadd['id']; $venue_name=$rowadd['venue_name']; $address=$rowadd['address']; $city=$rowadd['city']; $post_code=$rowadd['post_code']; $country_code=$rowadd['country_code']; $url=$rowadd['url']; $email=$rowadd['email']; $description=$rowadd['description']; $img_url=$rowadd['img_url']; $tags=$rowadd['tags']; } ?> <h1 class="edit-venue-title">Add Venue:</h1> <form role="form" enctype="multipart/form-data" method="post" name="formVenue" action="save.php"> <input type="hidden" name="id" value="<?php echo $id; ?>"/> <div class="form-group"> <input class="form-control" type="hidden" name="id" value="<?php echo $id; ?>"/> <p><strong>ID:</strong> <?php echo $id; ?></p> <strong>Venue Name: *</strong> <input class="form-control" type="text" name="venue_name" value="<?php echo $venue_name; ?>"/><br/> <br/> <strong>Address: *</strong> <input class="form-control" type="text" name="address" value="<?php echo $address; ?>"/><br/> <br/> <strong>City: *</strong> <input class="form-control" type="text" name="city" value="<?php echo $city; ?>"/><br/> <br/> <strong>Post Code: *</strong> <input class="form-control" type="text" name="post_code" value="<?php echo $post_code; ?>"/><br/> <br/> <strong>Country Code: *</strong> <input class="form-control" type="text" name="country_code" value="<?php echo $country_code; ?>"/><br/> <br/> <strong>URL: *</strong> <input class="form-control" type="text" name="url" value="<?php echo $url; ?>"/><br/> <br/> <strong>Email: *</strong> <input class="form-control" type="email" name="email" value="<?php echo $email; ?>"/><br/> <br/> <strong>Description: *</strong> <textarea class="form-control" type="text" name="description" rows ="7" value=""><?php echo $description; ?></textarea><br/> <br/> <strong>Image Upload: *</strong> <input class="form-control" type="file" name="image" value="<?php echo $img_url; ?>"/> <small>File sizes 300kb's and below 500px height and width.<br/><strong>Image is required or data will not save.</strong></small> <br/><br/> <strong>Tags: *</strong> <input class="form-control" type="text" name="tags" value="<?php echo $tags; ?>"/><small>comma seperated vales only, e.g. soul,hip-hop,reggae</small><br/> <br/> <p>* Required</p> <br/> <input class="btn btn-primary" type="submit" name="submit" value="Save"> </div> </form> </div> </body> </html>Here is the save.php code <?php error_reporting(E_ALL); ini_set("display_errors", 1); include ("dbconnection.php"); $venue_name=$_POST['venue_name']; $address=$_POST['address']; $city=$_POST['city']; $post_code=$_POST['post_code']; $country_code=$_POST['country_code']; $url=$_POST['url']; $email=$_POST['email']; $description=$_POST['description']; $tags=$_POST['tags']; $id=$_POST['id']; if(is_uploaded_file($_FILES['image']['tmp_name'])){ $folder = "images/hs-venues/"; $file = basename( $_FILES['image']['name']); $full_path = $folder.$file; if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) { //echo "succesful upload, we have an image!"; var_dump($_POST); if($id==null){ $sql="INSERT INTO venue(venue_name,address,city,post_code,country_code,url,email,description,img_url,tags)values(:venue_name,:address,:city,:post_code,:country_code,:url,:email,:description,:img_url,:tags)"; $qry=$db->prepare($sql); $qry->execute(array(':venue_name'=>$venue_name,':address'=>$address,':city'=>$city,':post_code'=>$post_code,':country_code'=>$country_code,':url'=>$url,':email'=>$email,':description'=>$description,':img_url'=>$full_path,':tags'=>$tags)); }else{ $sql="UPDATE venue SET venue_name=?, address=?, city=?, post_code=?, country_code=?, url=?, email=?, description=?, img_url=?, tags=? where id=?"; $qry=$db->prepare($sql); $qry->execute(array($venue_name, $address, $city, $post_code, $country_code, $url, $email, $description, $full_path, $tags, $id)); } if($success){ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Saved!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //if uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Upload Recieved but Processed Failed!')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } } //move uploaded else{ var_dump($_POST); echo "<script language='javascript' type='text/javascript'>alert('Successfully Updated.')</script>"; echo "<script language='javascript' type='text/javascript'>window.open('index.php','_self')</script>"; } ?>Thanks in advance! Edited by hankmoody, 12 August 2014 - 05:15 PM. Hi, I need some assistance with coding a form to upload a picture into MySQL DB. This will be part of a form and have a field where the user can upload a picture from where-ever, click submit and the image is uploaded into MySQL. If anyone has done this and can offer assistance with the html coding, PHP and how to set the field in MySQL, I would be greatly appreciative. what is the simple way to upload a photo to mysql or store in a dir, and update the database with the new url? Does anyone know of a good tutorial on uploading a picture file to a folder using php and copying the name to the database in mysql? Resizing photos on upload is helpful also...If you know it works...some I have tried do not work. Not asking for someone to write code for me but info or tutorial would be nice. Or maybe a code that has worked for you that is similar that I could learn from and edit... I can upload the actual photo into the database but it slows it way down. I have heard of loading the name only and resizing the photo and sending the actual photo to a file folder on the server. The few codes I have tried were not successful. Thanks for any guidance. I appreciate it. hi i m new to php there is two basic script i m testing on my localhost but it gives me error "( ! ) Notice: Undefined index: video in C:\wamp\www\Boysjoys\video\upload.php on line 4" "( ! ) Notice: Undefined index: video in C:\wamp\www\Boysjoys\video\upload.php on line 16" "( ! ) Notice: Undefined index: video in C:\wamp\www\Boysjoys\video\upload.php on line 27" i cant find where is the real problem is ##########FORM########### <form name="upload" action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="video"> <input type="submit" value="UPLOAD"> </form> #########FORM############ #########PHP############# <?php // This is the directory where images will be saved $path="uploaded/"; $path=$path.basename($_FILES["video"]["name"]); //This gets all the other information from the form $video=$_FILES["video"]["name"]; //connect to database $con=mysql_connect("localhost","root","") or die (mysql_error()); //SELECTING THE DATABASE mysql_select_db("admin_bj",$con) or die(mysql_error()); //write information to the database mysql_query("INSERT INTO 'video'(video) VALUES('$video')"); //write file to server if(move_uploaded_file($_FILES["video"]["tmp_name"],$path)) { // execute if all is ok echo "the file " . basename( $_FILES['uploadedfile']['name']). "has been uploaded and your information has been added to the server"; } else { //GIVES AND ERROR IF ITS NOT OK echo "Sorry,there was a problem in uploading."; } ?> #########PHP############# |