473,382 Members | 1,657 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

Inserting undefined number of images/files or its description into MySQL database.

Inserting single or pre-defined number of image(s)/file(s) or its description into MySQL database is no problem for me but undefined number of it, which will be added the input fields by users voluntarily, in single submit is difficult for me. Anyone has the solution ?
Sep 19 '11 #1
2 2223
Dormilich
8,658 Expert Mod 8TB
I’m not really seeing the problem:
Expand|Select|Wrap|Line Numbers
  1. <form action="process.php" method="post">
  2.     <input type="file" name="upload[]">
  3.     <input type="file" name="upload[]">
  4.     <input type="file" name="upload[]">
  5.     <button type="submit">upload ’em all</button>
  6. </form>
Expand|Select|Wrap|Line Numbers
  1. foreach ($_FILES["upload"] as $file)
  2. {
  3.     // insert into DB
  4. }
Sep 19 '11 #2
@Dormilich
First of all I thank you for your reply, Dormilich. I have tried it once before but only the last item went into the database. I think the problem is how to handle the array well in php.
I'm currently developing a website. The related page URL is http://www.ehyeh.com/validatedformtest3.html.

The following is the complete form page code :
Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html>
  2.  
  3. <html>
  4. <head>
  5. <title>Submit Form</title>
  6.  
  7. <!-- include the Tools -->
  8. <script src="/jquery.tools.min.js"></script>     
  9.  
  10. <!-- same styling as in minimal setup --> 
  11. <link rel="stylesheet" type="text/css" href="/form.css"/>
  12.  
  13. <!-- override it to have a columned layout -->
  14. <link rel="stylesheet" type="text/css" href="/columns.css"/>
  15.  
  16. <script language="javascript">
  17. <!-- 
  18. function OpenWindow(url,intWidth,intHeight) {
  19.      window.open(url, "_blank", "width="+intWidth+",height="+intHeight+",resizable=0,scrollbars=0") ;
  20. //--> 
  21. </script>
  22.  
  23. <script language="javascript">
  24. <!-- 
  25. fields = 0;
  26. images = new Array();
  27. image_title = new Array();
  28.  
  29. function addInput() {
  30.     if (fields != 3) {
  31.         var htmlText =  "<input type='file' name='images' id='fields' value='' ACCEPT='filetype/*' />";
  32.         var deleteField = "<a style='cursor:pointer;color:yellow;' onclick='this.parentNode.parentNode.removeChild(this.parentNode), fields -=1;'> X</a><br />"
  33.         var imageTitle = "Title of the photo/image if any<input type='text' name='image_title' id='fields' value='' size='35' /><br /><br />";
  34.         var stringConcatenated = htmlText + deleteField + imageTitle;
  35.         var newElement = document.createElement('div');
  36.         newElement.id = ''; // Give the DIV an ID, if you need to reference it later...
  37.      newElement.innerHTML = stringConcatenated;
  38.  
  39.         var fieldsArea = document.getElementById('files_list');
  40.     fieldsArea.appendChild(newElement);
  41.  
  42.         fields += 1;
  43.     } else {
  44.         alert("Only 3 upload fields allowed.");
  45.         document.form.add.disabled=true;
  46.     }
  47. }
  48. //--> 
  49. </script>
  50.  
  51. <style type="text/css">
  52. a {font-family : Arial; Font-size : 12px; text-decoration : none}
  53. a:link {color : pink}
  54. a:visited {color : pink}
  55. a:active {color : blue}
  56. a:hover {color : #3399FF}
  57. </style> 
  58.  
  59. </head>
  60.  
  61. <body background="bg1.gif">
  62. <table width="500px" align="center">
  63. <tr><td  bgcolor="#333"> <!-- I tested with '<tr width="500px" align="center">' eliminating table tags, but the result was same as before -->
  64. <form action="process-form-data-post.php" method="post" enctype="multipart/form-data" name="wordcount" id="myform" class="cols">
  65. <script language="JavaScript">
  66.    function countit(){    
  67.      var formcontent=document.wordcount.message.value
  68.          formcontent=formcontent.split(" ")
  69.          document.wordcount.wordcount3.value=formcontent.length
  70.     }
  71. </script>
  72. <h4>We strictly don't use the input data for other purposes.</h4>
  73.  
  74. <fieldset><font=+2>
  75. <label> First name * </label><input type="text" name="first_name" id="first_name" required="required" maxlength="25" /> 
  76. <label> Last name * </label><input type="text" name="last_name" id="last_name" required="required" maxlength="25" />  
  77. </fieldset>
  78. <fieldset>
  79. <label> E-mail address * </label><input type="email" name="e_list" id="e_list" required="required" maxlength="70" />  
  80. <label> Living City  </label><input type="text" name="livingcity" id="livingcity" maxlength="25" /> 
  81. </fieldset>
  82. <fieldset>
  83. <label> Message * &nbsp;&nbsp;Maxlength : 5000 words </label><input type="button" value="Click to Check Words Length" onClick="countit()"> <input type="text" name="wordcount3" size="5">
  84. <textarea rows=15 cols=59 name="message" id="message" wrap="physical" required="required" maxlength="10000" />Under construction.</textarea> <p> 
  85. <input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
  86. <input type="button" name="imagesubmit" onclick="addInput()" value="Attaching file/photo(s)" />
  87. <div id="files_list"></div>
  88. <script>
  89. <!-- Create an instance of the multiSelector class, pass it the output target and the max number of files -->
  90. var multi_selector = new MultiSelector( document.getElementById( 'files_list' ), 30 );
  91. <!-- Pass in the file element -->
  92. multi_selector.addElement( document.getElementById( 'my_file_element' ) );
  93. </script>
  94. </font>
  95. </fieldset>
  96. <fieldset>
  97. <label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:OpenWindow('spellcheck2.html','344','285')">SPELL CHECK</a></label>
  98. </fieldset>
  99. <div class="clear"></div>
  100. <button type="submit" name="s1" id="s1">Submit form</button>
  101. <button type="button" class="close" onclick="history.back();"> Cancel/Back </button>
  102. </form>
  103. </td></tr>
  104. </table> 
  105. <script> 
  106.  
  107. // Regular Expression to test whether the value is valid
  108. $.tools.validator.fn("[type=time]", "Please supply a valid time", function(input, value) { 
  109.     return /^\d\d:\d\d$/.test(value);
  110. });
  111.  
  112. $.tools.validator.fn("[data-equals]", "Value not equal with the $1 field", function(input) {
  113.     var name = input.attr("data-equals"),
  114.          field = this.getInputs().filter("[name=" + name + "]"); 
  115.     return input.val() == field.val() ? true : [name]; 
  116. });
  117.  
  118. $.tools.validator.fn("[minlength]", function(input, value) {
  119.     var min = input.attr("minlength");
  120.  
  121.     return value.length >= min ? true : {     
  122.         en: "Please provide at least " +min+ " character" + (min > 1 ? "s" : ""),
  123.         fi: "Kentän minimipituus on " +min+ " merkkiä" 
  124.     };
  125. });
  126.  
  127. $.tools.validator.localizeFn("[type=time]", {
  128.     en: 'Please supply a valid time',
  129.     fi: 'Virheellinen aika'        
  130. });
  131.  
  132.  
  133. $("#myform").validator({ 
  134.     position: 'top left', 
  135.     offset: [-12, 0],
  136.     message: '<div><em/></div>' // em element is the arrow
  137. });
  138. </script>
  139. </body>
  140. </html>
  141.  
And the following is the complete processing form data php code :
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // Connecting to the MySQL server
  3. $db = mysql_connect("host", "username", "password"); 
  4. if (!$db)
  5.   {
  6.   die('Could not connect: ' . mysql_error());
  7.   }
  8. mysql_select_db("databasename",$db) or die(mysql_error());
  9.  
  10. // Inserting these values into the MySQL table
  11. $_POST[message] = mysql_real_escape_string($_POST[message]);
  12. $_POST[first_name] = mysql_real_escape_string($_POST[first_name]);
  13. $_POST[last_name] = mysql_real_escape_string($_POST[last_name]);
  14. $_POST[livingcity] = mysql_real_escape_string($_POST[livingcity]);
  15.  
  16. $uploadDir = '/directory/path/';
  17.  
  18. /*
  19. if(count($_POST['images'])) 
  20.     { 
  21.         $len = count($_POST['images']); 
  22.  
  23.        for ($i=0; $i < $len; $i++) 
  24.           {  
  25.               $images = $_POST['images'][$i]; 
  26.               $image_title = $_POST['image_title'][$i]; 
  27.           }  
  28.     } 
  29. */
  30.  
  31. if(isset($_POST['s1']))
  32. {
  33. if($images) {
  34. $fileName = $_FILES['images']['name'];
  35. $tmpName = $_FILES['images']['tmp_name'];
  36.  
  37. $filePath = $uploadDir . $fileName;
  38.  
  39. $result = move_uploaded_file($tmpName, $filePath);
  40. if (!$result) {
  41. echo "Error uploading file";
  42. exit;
  43. }
  44.  
  45. if(!get_magic_quotes_gpc())
  46. {
  47. $filePath = addslashes($filePath);
  48. }
  49. }
  50.  
  51. foreach ($filePath as $v1) {
  52.    // foreach ($v1 as $v2) {
  53. $query = "INSERT INTO databasename (path) VALUES ('$filePath')";
  54.     }
  55. //}
  56.  
  57. //$filePath = serialize($filePath);   $filePath = implode(',',$filePath);
  58. $image_title = mysql_real_escape_string($image_title);    //$_POST[image_title]
  59. $image_title = serialize($image_title);   
  60. //$image_title = implode(',',$image_title); 'Invalid arguments passed' error message was produced
  61. //$image_title = join(" ",$image_title); also 'Invalid arguments passed' error message was produced
  62. $query = "INSERT INTO databasename (first_name, last_name, e_list, livingcity, message, image_title, submit_date, path) VALUES ('$_POST[first_name]', '$_POST[last_name]', '$_POST[e_list]', '$_POST[livingcity]', '$_POST[message]', '$image_title', NOW(), '$filePath')";
  63. $result = mysql_query($query,$db);
  64.  if (!$result){
  65.   die('Error: ' . mysql_error());
  66.   }
  67. echo <<<_END
  68. <html> 
  69. <head>
  70. <title>Processing Form Data</title> 
  71. <!-- include the Tools -->
  72. <script src="/jquery.tools.min.js"></script>
  73.  
  74. <!-- same styling as in minimal setup --> 
  75. <link rel="stylesheet" type="text/css" href="/form.css"/>
  76.  
  77. <!-- override it to have a columned layout -->
  78. <link rel="stylesheet" type="text/css" href="/columns.css"/>
  79.  
  80. <style type="text/css">
  81. a {font-family : Arial; Font-size : 12px; text-decoration : none}
  82. a:link {color : pink}
  83. a:visited {color : pink}
  84. a:active {color : pink}
  85. a:hover {color : #3399FF}
  86. </style>
  87.  
  88. </head>
  89. <body background="bg1.gif" link="white">
  90. <table align="center">
  91. <tr><td>&nbsp;</td></tr><tr><td>&nbsp;</td></tr>
  92. </table>
  93. <table id="myform" class="cols" align="center">
  94. <tr><td>&nbsp;</td></tr>
  95. <tr><td align="center">
  96. <h2>Thank you for submitting your inputs !</h2>
  97. </td></tr>
  98. <tr><td>&nbsp;</td></tr>
  99. <tr><td align="center"><font size="+1"><a href="http://www.ehyeh.com">Back to Home Page</a></font></td></tr><tr><td>&nbsp;</td></tr>
  100. </table>
  101. </body>
  102. </html>
  103. _END;
  104.  
  105. mysql_close($db);
  106. ?> 
  107.  
And the following is a screenshot of the database table. Only the last item which I input 'a' in the field of 'image_title' was inserted into the database.


I don't think it could be the problem of that the inconsistency of the use of the array in the javascript and the php script.
Sep 20 '11 #3

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

Similar topics

1
by: Spidah | last post by:
Is there an easier way to get the number of items in a database table than selecting all the records in it and then running mysql_num_rows on the result? Hamilton www.laughland.biz
0
by: Jonas Meurer | last post by:
hello, i develop a project with a mysql interface. one mysql table holds all the images for my project. everything works quite well so far, except i'm not able to upload images into the...
0
by: Dan Anderson | last post by:
I have created a BLOB field to store images. Is there any way to embed them within HTML with something like: <image start: jpeg> </image> Thanks in advance, Dan
0
by: Matt | last post by:
Hi I'm have difficulty displaying images that are stored in a MySQL database. I've tried using the odbc.net provider, the ByteFX provider and the MySQLDriverCS one but can't seem to get the...
0
by: marcin | last post by:
I have problems with inserting Japanese chars into MySQL database. This operation results in two completetely different strings that I can see via phpMyAdmin: $word: SELECT word FROM table;...
1
by: akashkhasgiwala | last post by:
i am developing i web application in which every user will have an Xml File containing mostly text and date/time stamps this application will use MySql for storing data so pl tell me if i can STORE...
5
tolkienarda
by: tolkienarda | last post by:
hi all i need to allow people to upload images to my site and then save them in a mysql database. i've looked at some prebuilt scripts using iframes but i don't think that will work for me. I want...
2
by: mannavavp | last post by:
hi friends, please let me know how i can store audio files in database table using java programming?
6
by: Keith Hughitt | last post by:
Hi all, I've run into a strange error while trying to store some PNG images in a MySQL database using MySQLdb. When I try to insert smaller images (< 64kb or so) everything seems to work fine....
2
by: poopsy | last post by:
hello all, i am developing a web application for my final year project where i will be able to download and upload files(more specifically, it will be papers and articles, mostly pdf files) from the...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.