473,856 Members | 1,834 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

multiple file upload to server and MySQL database

johngault
5 New Member
I've been working with this PHP page for several days now and I'm stumped. The page is supposed to allow the user to upload up to six images for their profile. When the user adds an image it (the page coding) does verify file size, if correct it places it on the server in the users folder and with the correct names and extension, creates the thumbnail and adds the correlating file name. However, it only adds the first file name to the database. When it displays the images we see the six columns in the table, but of course only the first column contains an image because the other image names did not get written into the database table. Does anyone see what is written wrong or missing? please!

Expand|Select|Wrap|Line Numbers
  1. <? if (!isset($_COOKIE["id"]) || $_COOKIE['usertype']!="chatmodels" )
  2.  
  3. {
  4.  
  5. header("location: ../../login.php");
  6.  
  7. } else{
  8.  
  9. include("../../dbase.php");
  10.  
  11. $result=mysql_query("SELECT user from $_COOKIE[usertype] WHERE id='$_COOKIE[id]' LIMIT 1");
  12.  
  13.  
  14.     while($row = mysql_fetch_array($result)) 
  15.  
  16.     {    $username=$row[user];    }
  17.  
  18. }
  19. mysql_free_result($result);
  20.  
  21. $errorMsg="You can upload up to 6 images";
  22.  
  23.  
  24.  
  25. //function that handles creation of thumbnails
  26.  
  27. function LoadJpeg ($imgname,$tocreate) {
  28.  
  29.     $tnsize="80";//thumbnail size
  30.  
  31.     $bigimage = @ImageCreateFromJPEG ($imgname); // Attempt to open 
  32.  
  33.     if (!$bigimage){
  34.  
  35.     $result=false;
  36.  
  37.     echo "<font color=#ffdd54>The image thumbnail could not be created. The image file might be corrupted.</font><br> You can can resave the file by using any image editor and then try again<br><br>Thank You! $endstr ";
  38.  
  39.     //exit();
  40.  
  41.     }
  42.  
  43.     $tnimage = ImageCreate($tnsize,$tnsize);
  44.  
  45.     $white = ImageColorAllocate ($tnimage,0, 0, 0);
  46.  
  47.     $sz = GetImageSize($imgname);
  48.  
  49.     // load our internal variables
  50.  
  51.     $x = $sz[0];    // big image width
  52.  
  53.     $y = $sz[1];    // big image height
  54.  
  55.  
  56.  
  57.     // find the larger dimension
  58.  
  59.         if ($x>$y) {    // if it is the width then
  60.  
  61.         $dx = 0;                    // the left side of the new image
  62.  
  63.         $w = $tnsize;                // the width of the new image
  64.  
  65.         $h = ($y / $x) * $tnsize;    // the height of the new image
  66.  
  67.         $dy = ($tnsize - $h) / 2;    // the top of the new image
  68.  
  69.         }else{    // if the height is larger then
  70.  
  71.         $dy = 0;                    // the top of the new image
  72.  
  73.         $h = $tnsize;                // the height of the new image
  74.  
  75.         $w = ($x / $y) * $tnsize;    // the width of the new image
  76.  
  77.         $dx = ($tnsize - $w) / 2;    // the left edgeof the new image
  78.  
  79.         }
  80.  
  81.     // copy the resized version into the thumbnal image
  82.  
  83.    ImageCopyResized($tnimage, $bigimage, $dx, $dy, 0, 0, $w, $h, $x, $y);
  84.  
  85.     //if we manage to create the thumbnail
  86.  
  87.    if (ImageJPEG($tnimage,$tocreate,80) && $x<640 && $y<640){
  88.  
  89.    $result=true;
  90.  
  91.    } else{ //if we dont
  92.  
  93.      $result=false;
  94.  
  95.               if ($x>640 || $y>640){
  96.  
  97.                $errorMsg="File resolution too big. Maximum 640x640 pictures accepted.";
  98.  
  99.               } else{
  100.  
  101.               $errorMsg="Thumbnail file could not be created";
  102.  
  103.               }
  104.  
  105.           //exit();
  106.  
  107.        }
  108.  
  109.   return $result;
  110.  
  111. }
  112.  
  113. if(!isset($_COOKIE["id"]))
  114.  
  115. {
  116.  
  117. header("Location: ../../login.php");
  118.  
  119. } else if (isset($_FILES['ImageFile']['tmp_name']))
  120.  
  121.     {    
  122.  
  123.         $currentTime=time();
  124.  
  125.         $pictureName=md5("$currentTime".$_SERVER['REMOTE_ADDR']);
  126.  
  127.  
  128.  
  129.         $urlImage="../../models/".$username."/".$pictureName.".jpg";
  130.  
  131.         $urlThumbnail="../../models/".$username."/".$pictureName."_thumbnail.jpg";
  132.  
  133.  
  134.  
  135.  
  136.  
  137.         //we copy the thumbail image
  138.  
  139.         if (copy ($_FILES['ImageFile']['tmp_name'],$urlImage) && LoadJpeg($urlImage,$urlThumbnail))
  140.  
  141.         {
  142.  
  143.         $id=$_COOKIE["id"];
  144.  
  145.         mysql_query("INSERT INTO modelpictures ( user , name, dateuploaded ) VALUES ('$username', '$pictureName', '$currentTime')");
  146.  
  147.         $errorMsg.='<img src="http://bytes.com/topic/models/'.$username.'/'.$pictureName.'_thumbnail.jpg"> File Copied';        
  148.  
  149.         }         
  150.  
  151.         else        
  152.  
  153.         {        
  154.  
  155.         $errorMsg.="File not Copied. Check resolution. Maximum 640kb files accepted.";        
  156.  
  157.         }
  158.  
  159.     } else  if(isset($_GET[delete]))
  160.  
  161.     {
  162.  
  163.     unlink("../../models/$username/$_GET[delete]_thumbnail.jpg");
  164.  
  165.     unlink("../../models/$username/$_GET[delete].jpg");
  166.  
  167.     mysql_query('DELETE from modelpictures WHERE name="'.$_GET[delete].'" LIMIT 1');
  168.  
  169.     $errorMsg+="File Deleted";    
  170.  
  171.     }
  172.  
  173.  
  174. ?>
  175.  
  176. <?
  177. include("_models.header.php");
  178. ?>
  179. <br>
  180.  
  181. <span style="font-weight: bold">This function is still under development process. Currently you can upload 1 image only!</span>
  182. <table width="720" border="0" align="center" cellpadding="0" cellspacing="0">
  183.  
  184.   <tr valign="top">
  185.  
  186.     <td height="113"><form action="uploadpicture.php" method="post" enctype="multipart/form-data" name="form2">
  187.  
  188.         <p><span class="error">
  189.  
  190.           <?php if ( isset($errorMsg) && $errorMsg!=""){ echo $errorMsg; } ?>
  191.  
  192.         </span></p>
  193.  
  194.         <table width="720" border="0" align="center" cellpadding="4" cellspacing="0">
  195.  
  196.           <tr class="barbg">
  197.  
  198.             <td colspan="2"><span class="form_header_title">Upload new Image </span></td>
  199.           </tr>
  200.  
  201.           <tr align="right">
  202.  
  203.             <td width="555" align="left"><input name="ImageFile" type="file" id="ImageFile">
  204.  
  205.                 <input type="submit" name="Submit2" value="Upload image to my gallery"></td>
  206.  
  207.           </tr>
  208.  
  209.         </table>
  210.  
  211.         <br>
  212.  
  213.         <table width="720" border="0" align="center" cellpadding="4" cellspacing="0">
  214.  
  215.           <tr class="barbg">
  216.  
  217.             <td class="barbg"><span class="form_header_title">Image  Gallery </span></td>
  218.  
  219.           </tr>
  220.  
  221.           <tr>
  222.  
  223.             <td>
  224.  
  225.               <table width="700" border="1" align="center" bordercolor="#CCCCCC">
  226.  
  227.                 <?
  228.  
  229.             $count=0;
  230.  
  231.             $result = mysql_query('SELECT * FROM modelpictures WHERE user="'.$username.'" ORDER BY dateuploaded DESC');
  232.  
  233.             while($row = mysql_fetch_array($result)) 
  234.  
  235.             {
  236.  
  237.             $count++;
  238.  
  239.             if ($count>0) {echo"<tr>";}
  240.  
  241.             echo "<td width='100'class='form_definitions' height='100' align='center' valign='middle'><img src ='../../models/".$username."/".$row[name]."_thumbnail.jpg' ><br><a href='uploadpicture.php?delete=$row[name]'>Delete</a></td>";
  242.  
  243.             if ($count==6){ echo"</tr>"; $count=0;}
  244.  
  245.             }
  246.  
  247.             mysql_free_result($result);
  248.  
  249.             for($i=0; $i<6-$count; $i++)
  250.  
  251.             {
  252.  
  253.             echo"<td width='100' height='100' align='center' valign='middle'>&nbsp</td>";
  254.  
  255.             }
  256.  
  257.             echo"</tr>";
  258.  
  259. ?>
  260.  
  261.             </table></td>
  262.  
  263.           </tr>
  264.  
  265.         </table>
  266.  
  267.         </form></td>
  268.  
  269.   </tr>
  270.  
  271.   <tr>
  272.  
  273.     <td>&nbsp;</td>
  274.  
  275.   </tr>
  276.  
  277. </table>
Dec 30 '08 #1
8 9867
Atli
5,058 Recognized Expert Expert
Hi.

On line #145. You execute the query to add the new image to the database, but there is nothing in place to check whether the row was actually added. All errors that could be occurring would simply be ignored.

Make sure that query is in fact working before you do anything else.
(See Turn on PHP Debugging Messages to see how to do that)
Dec 30 '08 #2
johngault
5 New Member
Thank you for your patience.
I added the error checking and found a warning on line 241, undefined constant assumed 'name'.
So I added $name=$row["name"]; in line 234 and changed line 241 to:
Expand|Select|Wrap|Line Numbers
  1. echo "<td width='100'class='form_definitions' height='100' align='center' valign='middle'><img src ='../../models/".$username."/".$name."_thumbnail.jpg' ><br><a href='uploadpicture.php?delete=$name'>Delete</a></td>";
I see no further warnings or errors. I can upload 1 image (file name) successfully to the sql table and display that 1 image. Uploading additional image files will add to the server folder, but not the sql table.
Dec 30 '08 #3
Atli
5,058 Recognized Expert Expert
And did the query in line #145 get executed successfully every time?

To make sure of that, try something like:
Expand|Select|Wrap|Line Numbers
  1. $sql = "INSERT INTO ...";
  2. $result = mysql_query($sql) 
  3.   or die("<h3>Query failed!</h3><pre>". mysql_error() ."</pre>");
  4.  
  5. if(mysql_get_affected_rows($result) != 1) {
  6.   die("<h3>Failed to insert!</h3><pre>". mysql_error() ."</pre>");
  7. }
That should tell you why the row isn't getting inserted.
Dec 30 '08 #4
johngault
5 New Member
Adding/changing line 145 with the above resulted in:
Query failed!
Duplicate entry 'Username' for key 1
Dec 30 '08 #5
johngault
5 New Member
Since the primary key in the Sql table is the Username, the subsequent images beyond the first do not get added to the table because Sql will not allow more than one Unique entry to the primary key. Nice what reading errors and warnings can trigger in the grey matter! :) So -- by adding a check at the beginning of the process to verify if the Username already exists in the table and if not create it and than removing the insert 'user' from line 145 allows Sql to do what we expect it to do.
Dec 31 '08 #6
Atli
5,058 Recognized Expert Expert
Ahh ok. So the username is the primary key.
Then there is no good way to add multiple pictures per user, using your current table structure.
If you simply remove the 'user' field from the INSERT clause, then you will just have a bunch of images floating around without a user.

But, if you add a integer field to your current structure and make that your primary key, you can use your code just as it is.

I mean, if you table looked somewhat like:
Expand|Select|Wrap|Line Numbers
  1. modelpicture
  2. ----------------
  3. id int unsigned primary key
  4. user varchar not null
  5. image varchar not null
  6. created datetime not null
  7.  
The 'id' field would act as a row counter of sorts, just what a PK is usually supposed to be.
Dec 31 '08 #7
johngault
5 New Member
Perfect. That solution was right on. I had to make the id primary key auto increment to get past the duplicate value error from Sql.
Thank you for your help. Awesome!
Dec 31 '08 #8
Atli
5,058 Recognized Expert Expert
I'm glad I was able to help :)
Dec 31 '08 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

2
2741
by: shahram.shirazi | last post by:
Hi I am looking to develop an application that provides decision support through various graphs and charts using a mysql backend. My problem is between the data collection and data represenation. I would have a handheld device with a database application on it to collect data, this data (in a csv file most probably) would be transferred wirelessly to a pc, which then would need to be uploaded online and loaded into the correct mysql...
3
3999
by: Ben Holness | last post by:
Hi all, I have a php/mysql website where people can upload their own graphics for the buttons and background of pages on the website. This used to run on one server, but I have now been asked to set it up on multiple servers. The problem is that when someone uploads a file, how do I distribute it to all of the servers? Should I use php to send it to all of the servers once
3
11706
by: AHMLIVE | last post by:
Hi everyone. I got a problem when i tried to upload MYSQL database. I don't have any idea how to upload it. It is my first time to do it. I already upload the pages from my local pc to server with Bulletproof FTP transfer and now I want to upload my database. For now I am using vertrigoServ 2.15 and I found my database in folder path C:\Program Files\VertrigoServ2\Mysql\data\mydatabase. and i want it to transfer to my server. Do I need...
0
2839
by: dann2 | last post by:
hello, i try to upload in an access db two pictures at the same time. i use the adjusted sample code from persits. it looks like this: ... '<% ' Create an instance of AspUpload object 'Set Upload = Server.CreateObject("Persits.Upload") ' Capture uploaded file. Save returns the number of files uploaded 'Count = Upload.Save(Path) 'If Count = 0 Then 'Response.Write "message"
3
22067
by: siyaverma | last post by:
i am trying to upload csv file from user's computer to main server the code i am using is if(((isset($_GET)) && ($_GET=="yes")) ) { $typefield = $_GET; echo "<form enctype=\"multipart/form-data\" action=\"$PHP_SELF\" method=\"POST\">
2
7660
by: hotflash | last post by:
Hi All, I found the best pure ASP code to upload a file to either server and/or MS Access Database. It works fine for me however, there is one thing that I don't like and have tried to fix but don't have any luck is to do a form validation. This script requires the files: db-file-to-disk.asp and _upload.asp. There is a DESCRIPTION field in the db-file-to-disk.asp file, what I want to do is the user has to field out this fied before...
43
9946
by: bonneylake | last post by:
Hey Everyone, Well this is my first time asking a question on here so please forgive me if i post my question in the wrong section. What i am trying to do is upload multiple files like gmail does. I found a script that does this on easycfm.com (Topic 13543). But anyway when i try to upload multiple files it will create multiple records in my database (like it should), but it wont upload multiple files. What ever file i choose to upload...
4
4900
by: MoroccoIT | last post by:
Greetings - I saw somewhat similar code (pls see link below) that does mupltiple files upload. It works fine, but I wanted to populate the database with the same files that are uploaded to mydirectory, but for some reason, I am getting different file names on the database. Here is the full code: please do serach on kewword "database" to see where I added my database code - that where I need help with. And here the link where I got it...
4
2964
by: liberty1 | last post by:
Hi everyone. I appreciate your effort at helping newbies like me. I have the following problems and will appreciate urgent help. PROBLEM NUMBER 1: Using PHP and MySQL, I am able to upload picture successfully unto the server but not so with the file name of the picture even though other parameters in my form got inserted successfuly in the database. I have read several posts on this topic including here on this site but I can't get around...
0
9911
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
11055
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10696
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10780
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7093
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5761
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4575
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4174
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3201
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.