PHP - Moved: Conect Php With Mysql In Order To Upload Image
This topic has been moved to Third Party PHP Scripts.
http://www.phpfreaks.com/forums/index.php?topic=328623.0 Similar TutorialsThis topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=347726.0 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=349226.0 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=320026.0 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=345631.0 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=321906.0 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=312690.0 Hello I am having problems uploading an image through a HTML form. I want the image to be uploaded to the server and the image name to be written to the mysql database. Below is the code I am using: Code: [Select] <?php if (isset($_POST['add'])){ echo "<br /> add value is true"; $name = $_POST['name']; $description = $_POST['description']; $price = $_POST['price']; $category_id = $_POST['category_name']; $image = $_FILES['image']['name']; //file path of the image upload $filepath = "../images/"; //mew name for the image upload $newimagename = $name; //new width for the image $newwidth = 100; //new height for the image $newheight = 100; include('../includes/image-upload.php'); mysql_query("INSERT INTO item (item_name, item_description, item_price, item_image) VALUES ('$name','$description','$price','$image')"); ?> Here is the image-upload.php file code: Code: [Select] <?php //assigns the file to the image $image =$_FILES["image"]["name"]; $uploadedfile =$_FILES["image"]["tmp_name"]; if ($image) { //retrieves the extension type from image upload $extension = getextension($image); //converts extension to lowercase $extension = strtolower($extension); //create image from uploaded file type if($extension=="jpg" || $extension=="jpeg") { $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefromjpeg($uploadedfile); }else if($extension=="png") { $uploadedfile = $_FILES['image']['tmp_name']; $src = imagecreatefrompng($uploadedfile); }else{ $src = imagecreatefromgif($uploadedfile); } //creates a list of the width and height of the image list($width,$height)=getimagesize($uploadedfile); //adds color to the image $tmp = imagecreatetruecolor($newwidth,$newheight); //create image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); //set file name $filename = $filepath.$newimagename.".".$extension; $imagename = $newimagename.".".$extension; //uploads new file with name to the chosen directory imagejpeg($tmp,$filename,100); //empty variables imagedestroy($src); imagedestroy($tmp); } ?> Any help would be appreciated, fairly new to all this! Thanks!!! This topic has been moved to Third Party PHP Scripts. http://www.phpfreaks.com/forums/index.php?topic=357648.0 Hi Guys, I am trying to use a script that is available on the net to upload an image into a mysql using BLOB. However it wont upload it keep getting Warning: fread() [function.fread]: Length parameter must be greater than 0 in /home/theacidf/public_html/attendance/upload.php on line 17 Here is the code... <?php // Connect to database $errmsg = ""; if (! @mysql_connect("localhost","theacidf_admin","password")) { $errmsg = "Cannot connect to database"; } @mysql_select_db("theacidf_attendanc"); // Insert any new image into database if ($_REQUEST[completed] == 1) { move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img"); $instr = fopen("latest.img","rb"); $image = addslashes(fread($instr,filesize("latest.img"))); if (strlen($image) < 149000) { mysql_query ("insert into pix (title, imgdata) values (\"". $_REQUEST[whatsit]. "\", \"". $image. "\")"); } else { $errmsg = "Too large!"; } } // Find out about latest image $gotten = @mysql_query("select * from pix order by pid desc limit 1"); if ($row = @mysql_fetch_assoc($gotten)) { $title = htmlspecialchars($row[title]); $bytes = $row[imgdata]; } else { $errmsg = "There is no image in the database yet"; $title = "no database image available"; // Put up a picture of our training centre $instr = fopen("../images/logo_png.png","rb"); $bytes = fread($instr,filesize("../images/logo_png.png")); } // If this is the image request, send out the image if ($_REQUEST[gim] == 1) { header("Content-type: image/jpeg"); print $bytes; exit (); } ?> <html><head> <title>Upload an image to a database</title> <body bgcolor=white><h2>Here's the latest picture</h2> <font color=red><?= $errmsg ?></font> <center><img src=?gim=1><br> <?= $title ?></center> <hr> <h2>Please upload a new picture and title</h2> <form enctype=multipart/form-data method=post> <input type=hidden name=MAX_FILE_SIZE value=150000> <input type=hidden name=completed value=1> Please choose an image to upload: <input type=file name=imagefile><br> Please enter the title of that pictu <input name=whatsit><br> then: <input type=submit></form><br> <hr> </body> </html> Why wont it run properly? Thanks in advance... S This topic has been moved to PHP Installation & Configuration. http://www.phpfreaks.com/forums/index.php?topic=307015.0 Okay, so I found this code on-line that uploads images via a form, inserts them in to MySQL and displays the images on the page. It works great! Problem is, I spent a long time hacking this script to make it work with my site just to realize it did not re-size the image after it uploaded (dumb me). I have found other code that do this but I really do not want to start over at this point and my level of expertise with PHP are a step below what I need to figure this out. I am attaching the "original" code. If anyone knows how to add the necessary lines of code to make every image re-size (reduce) itself. I would very much appreciate it. Thanks <?php $con=mysql_connect("localhost", "root", "rootwdp")or die("cannot connect"); mysql_select_db("student",$con)or die("cannot select DB"); if(isset($_POST['upload'])) { $img=$_FILES["image"]["name"]; foreach($img as $key => $value) { $name=$_FILES["image"]["name"][$key] ; $tname=$_FILES["image"]["tmp_name"][$key]; $size=$_FILES["image"]["size"][$key]; $oext=getExtention($name); $ext=strtolower($oext); $base_name=getBaseName($name); if($ext=="jpg" || $ext=="jpeg" || $ext=="bmp" || $ext=="gif"){ if($size< 1024*1024){ if(file_exists("upload/".$name)){ move_uploaded_file($tname,"upload/".$name); $result = 1; list($width,$height)=getimagesize("upload/".$name); $qry="select id from img where `img_base_name`='$base_name' and `img_ext`='$ext'"; $res=mysql_fetch_array(mysql_query($qry)); $id=$res['id']; $qry="UPDATE img SET `img_base_name`='$base_name' ,`img_ext`='$ext' ,`img_height`='$height' ,`img_width`='$width' ,`size`='$size' ,`img_status`='Y' where id=$id"; mysql_query($qry); echo "Image '$name' updated<br />"; } else{ move_uploaded_file($tname,"upload/".$name); $result = 1; list($width,$height)=getimagesize("upload/".$name); $qry="INSERT INTO `img`(`id` ,`img_base_name` ,`img_ext` ,`img_height` ,`img_width`, `size` ,`img_status`)VALUES (NULL , '$base_name', '$ext', '$height', '$width', '$size', 'Y');"; mysql_query($qry); echo "Image '$name' uploaded<br />"; } } else{ echo "Image size excedded.<br />File size should be less than 1Mb<br />"; } } else{ echo "Invalid file extention '.$oext'<br />"; } } } function getExtention($image_name){ return substr($image_name,strrpos($image_name,'.')+1); } function getBaseName($image_name){ return substr($image_name,0,strrpos($image_name,'.')); } ?> <!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>Untitled Document</title> <script type="text/javascript"> function addItems() { var table1 = document.getElementById('tab1'); var newrow = document.createElement("tr"); var newcol = document.createElement("td"); var input = document.createElement("input"); input.type="file"; input.name="image[]"; newcol.appendChild(input); newrow.appendChild(newcol); table1.appendChild(newrow); } function remItems() { var table1 = document.getElementById('tab1'); var lastRow = table1.rows.length; if(lastRow>=2) table1.deleteRow(lastRow-1); } </script> <style type="text/css"> <a class="tooltip" and them url href="/http.www.anyurl.com" </a> a.tooltip:hover span{display:inline; position:absolute; border:2px solid #cccccc; background:#efefef; color:#333399;} a.tooltip span {display:none; padding:2px 3px; margin-left:8px; width:150px;} </style> </head> <body> <form method="post" action="" enctype="multipart/form-data"> <table align="center" border="0" id="tab1"> <tr> <td width="218" align="center"><input type="file" name="image[]" /></td> <td width="54" align="center"><img src="Button-Add-icon.png" alt="Add" style="cursor:pointer" onclick="addItems()" /></td> <td><img src="Button-Delete-icon.png" alt="Remove" style="cursor:pointer" onclick="remItems()" /></td> </tr> </table> <table align="center" border="0" id="tab2"> <tr><td align="center"><input type="submit" value="Upload" name="upload" /></td></tr> </table> </form> <table border="0" style="border:solid 1px #333; width:800px" align="center"><tr><td align="center"> <iframe style="display:none" name="if1" id="if1"></iframe> <? $qry="select * from img where img_status='Y' order by id"; $res=mysql_query($qry); $i=0; if(mysql_num_rows($res)){ ?> <div align="center"><ul style="width:650px; border: 0px"> <? while($fetch=mysql_fetch_array($res)){ $hratio=120/$fetch['img_height']; $wratio=120/$fetch['img_width']; $ratio=($hratio < $wratio) ? $hratio : $wratio; $hth=$fetch['img_height']*$ratio; $wth=$fetch['img_width']*$ratio; ?> <li style="width:120px; height:180px; border:0px solid #333;float:left;list-style:none outside none; padding-right:5px;"><img src="upload/<? echo $fetch['img_base_name'].'.'.$fetch['img_ext']; ?>" width="<? echo $wth; ?>" height="<? echo $hth; ?>" title="<? echo "image : ".$fetch['img_base_name'].".".$fetch['img_ext']; ?>" /><br /> <? if($i==0) $fp=fopen("fileInfo.txt",'w'); else $fp=fopen("fileInfo.txt",'a'); fwrite($fp,"Image : ".++$i ."\r\n"); fwrite($fp,"Name : ".$fetch['img_base_name'].".".$fetch['img_ext']."\r\n"); fwrite($fp,"width X height : ".$fetch['img_width']." X ".$fetch['img_height']."\r\n"); fwrite($fp,"Size : ".round($fetch['size']/1024,1)."Kb\r\n"); fwrite($fp,"____________________________________\r\n"); fclose($fp); echo $fetch['img_base_name'].".".$fetch['img_ext'].'<br />'; echo $fetch['img_width'].' X '; echo $fetch['img_height'].'<br />'; echo round($fetch['size']/1024,1) .'Kb'; ?> </li> <? }?> </ul> </div><? }?> </td></tr></table> </body> </html> 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 --> what's wrong with this ? i can't upload 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. so what i have going on is that i need help writing a basic script to upload original and copy with resize for thumbnail. then also need to rename both image files with content in the form. My server supports GD Library and that imagemagik or whatever it is lol. upload dirs orig: ../media/photos/ thumb: ../media/photos/thumb/ mySQL DB: name: m_photos fields: id(INT) m_cat(varchar) m_sub_cat(varchar) pic(varchar) description(varchar) p_group(varchar) I have the form written up for how it should look like: Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data"> Upload an image for processing<br /> <input type="file" name="Image"><br /> <select name="sub_group"> <option value="Photo Shoot">Photo Shoot</option> <option value="Live Performances">Live Performances</option> <option value="Randoms">Randoms</option> <option value="Fan Photos">Fan Photos</option> </select><br /> Location: <input type="text" name="p_group" /><br /> Date of Pic: <input type="text" name="date" /><br /> Description: <input type="text" name="description" /><br /> <input type="submit" value="Upload"> </form> so what needs to happen is for the file upload name. it needs to grab a count from "p_group" database to give it a starting number in a "00" pattern and then the date of pic needs to go in there next then the p_group name. so when the files gets uploaded it would look something like this after upload. "03 - Oct 21, 2011 - The Mex.jpg" NOTE: all pics must be converted to ".jpg" extension. both the orig and thumb will use that same file name cuz they just go into different dirs re-sizing for the thumbnail should be done by aspect ratio and needs to either be 300px width or 400px height. so if anyone would like to help me out please do. im not the greatest at writing in php yet I'm looking to order my upload files in a specific order. I believe the default is a random upload order, but I would like to change this based on the file name, which I'm having difficulty with.
The file names would be for example;
'01 smiley' '02 dog' '03 cat'Currently I used a 'Drag & Drop' multiple file upload although this just uploads in any random order to my database table, I'd like to upload it by numeric order as above. Code so far (upload code works, just the order needs work)... $count = count($_FILES['upload']['name']); $in=0; while($in<$count) { //upload here $in++; }I think I need to sort()? before my while loop, but having difficulty getting this correct. How would I be able to sort each file into a correct order. Many thanks. Edited by Veltu, 12 December 2014 - 05:46 AM. This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=321790.0 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=318036.0 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=355706.0 Lets say I have this query: $sql = mysql_query("SELECT * FROM Member ORDER BY posts DESC LIMIT 10"); while ($get = mysql_fetch_array($sql)){ $row .= $get['id']; $posts .= $get['posts']; echo "$row - $posts<br />"; } Lets say I have two of rows, with posts fields of 84 and 803. When it displays it, it grabs the 84 row first, when I want the bigger number 803 first. Is there a way to fix this? |