php-mysql
php/mysql tips,tricks,scripts
Friday, February 13, 2009
Array Paging
Comments are written to understand the code.
Please write any suggestions or improvements you have to implement in this code.
<?php
//This is the temporary array created for this example. In your case the values would be coming from database
$DataArray = array('value1','value2','value3','value4','value5','value6','value7','value8','value9','value10','value11','value12','value13','value14','value15','value16','value17');
//take the count of the array
$cnt = count($DataArray);
//get the page number from the url
if($_REQUEST['pge_no']){
$pge_no=$_REQUEST['pge_no'];
}else{
$pge_no=1; //set page number to 1 if not specified
}
if($_REQUEST['lim']){
$lim=$_REQUEST['lim'];
}else{
$lim=2; //Number of records to display per page.
}
if(!$cnt)
{
$cnt=0;
}
//calculate the number of pages
$pages = ceil($cnt/$lim);
if($pge_no>$pages)
{
$pge_no=$pages;
}
$pg_last=$pge_no*$lim; //calculate the last page value
$pg_start=$pg_last-($lim-1); //calculate the first page value
$counter=0;
//create the sets of pages eg. page number 1 will have 1,2,3 records, 2 will have 4,5,6 records...
for($l=1;$l<=$pages;$l++)
{
for($m=1;$m<=$lim;$m++)
{
$pagesets[$l][]=$counter;
$counter++;
}
}
//display the records
for($k=0;$k<count($DataArray);$k++)
{
//display the records only for the particular page
if(in_array($k,$pagesets[$pge_no]))
{
echo $DataArray[$k]."<br><hr/>";
}
}
//this is the number of pages to be displayed at a time between next and previous buttons
$NumberOfPagesToShow = 3;
if($pages>1){
$sets = ceil($pages/$NumberOfPagesToShow);
//createing first and last page numbers
for($j=1;$j<=$sets;$j++)
{
$lastpage = $j*$NumberOfPagesToShow;
$firstpage = $lastpage-$NumberOfPagesToShow+1;
$nextPageValue = $pge_no + 1; //calculate value of next button
if($nextPageValue>$pages)
{
$nextPageValue=$pages;
}
$next = "<a href='array_paging.php?pge_no=$nextPageValue'>Next »</a>"; //create next button
//create value of last button
$ending = $lastpage+1;
if($ending>$pages)
{
$ending = $pages;
}
$end = "<a href='array_paging.php?pge_no=$ending'>»</a>"; //Create last button
$prevPageValue = $pge_no - 1; //calculate value of previous button
if($prevPageValue<=0)
{
$prevPageValue=1;
}
$prev = "<a href='array_paging.php?pge_no=$prevPageValue'>« Previous</a>"; //create previous button
//create value of first button
$starting = $firstpage-1;
if($starting < 1)
{
$starting = 1;
}
$start = "<a href='array_paging.php?pge_no=$starting'>«</a>";//create first button
if($pge_no>=$firstpage && $pge_no<=$lastpage)
{
break;
}
}
echo $start." "; //display first button
echo $prev." "; //display previous button
//Display pages
for ($x=$firstpage;$x<=$lastpage;$x++){
if($x==$pge_no){
echo "<span style='color:red'>".$x."</span> ";
}else{
if($x<=$pages)
{
echo "<a href='array_paging.php?pge_no=$x'>".$x."</a> ";
}
}
}
echo $next." "; //display next button
echo $end." "; //display last button
echo "<br><br>";
}
?>
Tuesday, August 19, 2008
Multiple File upload in php
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"> Title: <input type="text" name="ImageTitle[]" id="ImageTitle' num '" class="normal"/> 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"> Title: <input name="ImageTitle[]" type="text" class="normal" id="ImageTitle_1"> 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();"> <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.
$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)”;
$sql = “DELETE FROM employees WHERE id in ($id1,$id2,$id3,$id4)”;