Tuesday, August 19, 2008

Multiple File upload in php

Hello friends. This is a short tutorial for uploading multiple files (gmail style). on the server. The tutorial shows a html file to generate dynamic elements and a php file which displays the submitted values. Hope it will be helpful.

Below is the entire html code. On this page, html elements like textbox and file upload are dynamically created on a button click. These elements are then validated for empty check before submitting. To see this page working copy and paste the entire html code (in grey) on a new blank html file.


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic Fields Tutorial</title>
<script type="text/javascript">
//Validate data
function validate()
{
TotalImages = parseInt(document.getElementById("DynamicFieldsCount").value);
for(i=1;i<=TotalImages;i )
{
//check empty title
var ctrl_id = "ImageTitle_" i;
var ctrlValue = document.getElementById(ctrl_id).value.replace(/^\s |\s $/g, '');
if(ctrlValue=="")
{
alert("please enter Image Title");
document.getElementById(ctrl_id).focus();
return false;
}

//check if the image is selected or not
var ImageFileID = "ImageFile_" i;
var ImageFileValue = document.getElementById(ImageFileID).value.replace(/^\s |\s $/g, '');
if(ImageFileValue!="")
{
//check if the image is a jpg, gif or png image.
filetype = ImageFileValue.substr(ImageFileValue.lastIndexOf(".")).toLowerCase();
if(filetype!=".jpg" && filetype!=".jpeg" && filetype!=".gif" && filetype!=".png")
{
alert("Invalid image type. Please upload images of type jpg, gif or png");
document.getElementById(ImageFileID).focus();
return false;
}
}
else
{
alert("please select image to upload");
document.getElementById(ImageFileID).focus();
return false;
}
}
}
function addElement()
{
document.getElementById('RemoveElement').style.display= 'inline';
var ni = document.getElementById('dvDynamicElements');
var num = parseInt((document.getElementById('DynamicFieldsCount').value)) 1;
if(num<=20)
{
if(num<=9)
{
serialnum = '0' num;
}
else
{
serialnum = num;
}
var newdiv = document.createElement('div');
var divIdName = 'New' num 'Div';
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML = '<table width="100%" border="0" cellpadding="8" cellspacing="0" bgcolor="#EFEFEF" class="normal"><tr><td width="5%" style="font:Verdana, Arial, Helvetica, sans-serif;font-size:15px; font-weight:bold" >' serialnum '</td><td style="font:Verdana, Arial, Helvetica, sans-serif;font-size:15px; font-weight:bold" valign="top">&nbsp;Title: <input type="text" name="ImageTitle[]" id="ImageTitle' num '" class="normal"/>&nbsp; Upload Image: <input name="ImageFile[]" type="file" class="normalmedium" id="ImageFile_' num '"></td></tr></table>';
ni.appendChild(newdiv);
document.getElementById('DynamicFieldsCount').value = num;
}
}

function removeElement() {
divNum = 'New' parseInt(document.getElementById('DynamicFieldsCount').value) 'Div';
var d = document.getElementById('dvDynamicElements');
var olddiv = document.getElementById(divNum);
d.removeChild(olddiv);
var OptionsCount = document.getElementById('DynamicFieldsCount').value;
OptionsCount = OptionsCount - 1;
document.getElementById('DynamicFieldsCount').value = OptionsCount;
document.getElementById('DynamicFieldsCount').value = OptionsCount;
if(OptionsCount==1)
{
document.getElementById('RemoveElement').style.display= 'none';
}
}
</script>
</head>

<body>
<form name="frmUploadFiles" id="frmUploadFiles" action="myServerPage.php" method="post" onsubmit="return validate()" enctype="multipart/form-data">
<table width="100%" border="0" cellpadding="8" cellspacing="0" bgcolor="#EFEFEF" class="normal">
<tr>

<td colspan="2" style="font:Verdana, Arial, Helvetica, sans-serif;font-size:15px; font-weight:bold">Multiple Upload</td>
</tr>
<tr>

<td width="5%" style="font:Verdana, Arial, Helvetica, sans-serif;font-size:15px; font-weight:bold">01</td>
<td style="font:Verdana, Arial, Helvetica, sans-serif;font-size:15px; font-weight:bold" valign="top">&nbsp;Title: <input name="ImageTitle[]" type="text" class="normal" id="ImageTitle_1">&nbsp; Upload Image:
<input name="ImageFile[]" type="file" class="normalmedium" id="ImageFile_1" >
</td>
</tr>
</table>
<div id="dvDynamicElements" align="left" ></div>
<table width="100%" border="0" cellpadding="8" cellspacing="0" bgcolor="#EFEFEF" class="normal">
<tr>

<td colspan="2">
<input type="hidden" value="1" id="DynamicFieldsCount" />
<input name="UploadMore" type="button" class="normalmedium" id="UploadMore" value="Upload More" onclick="addElement();"> &nbsp; <input name="RemoveElement" type="button" class="normalmedium" id="RemoveElement" value="Remove" onclick="removeElement();" style="display:none">
</td>
</tr>
</table>
<input name="submit" type="submit" class="normal" id="submit" value="Submit">
</form>
</body>
</html>


Ok now if you are saturated playing with upload more and remove buttons, lets move on to generate our php file.

Create a php file with the name myServerPage.php and insert the code given below inside the php tags.

print_r($_POST);
print_r($_FILES);

I hope the readers of this blog know how to setup a local webserver to run php files.

Monday, July 14, 2008

Multiple Insert, Update or Delete in one Query (php-mysql).

Many times we want to make a multiple Insert (I), Update (U) or Delete (D) on a certain database table. The first thought of doing it would be to fire Insert, Update or Delete query inside a for(each) loop. But this is not the best solution regarding the system performance. Ever thought of inserting Or Updating |or Deleting multiple records in 1 query? Yes it is possible. It may look complex to beginners. The idea is to create a query dynamically for all the values you want to Insert, Update or Delete. The example of each is given below. I am not going to write the code for creating query, but will show how the final query looks like (the syntax) after dynamically created.

Imagine a table name employees with fields id (int auto increment) age (int), name (varchar) and sex (char).

The syntax of the Multiple Insert Query for the employees table would be –

$sql = "INSERT INTO employees (age, name, sex)
VALUES
(25, 'Swanand', 'M'),

(26, 'Smeeta', 'F'),

(33, 'Vicky', 'M'),

(42, 'Tony', 'M')”;


One another alternative I know for inserting multiple records is through LOAD DATA INFILE statement of mysql. This approach gives the best performance as compared to multiple insert. Its description and syntax is out of the scope of this article. You can refer in mysql manual for more details.


The syntax of the Multiple Update Query for the employees table would be –

$sql = “UPDATE employees

SET age =

CASE id

WHEN $id1 THEN $age1

WHEN $id2 THEN $age2

WHEN $id3 THEN $age3

WHEN $id4 THEN $age4

END

, name =

CASE id

WHEN $id1 THEN '$name1'

WHEN $id2 THEN '$name2'

WHEN $id3 THEN '$name3'

WHEN $id4 THEN '$name4'

END

, sex =

CASE id

WHEN $id1 THEN '$sex1'

WHEN $id2 THEN '$sex 2'

WHEN $id3 THEN '$sex3'

WHEN $id4 THEN '$sex4'

END

WHERE id in ($id1,$id2,$id3,$id4)”;


The syntax of the Multiple Delete Query for the employees table would be –

$sql = “DELETE FROM employees WHERE id in ($id1,$id2,$id3,$id4)”;