To do cascading drop down in php using mysql we can use AJAX. The name AJAX is from asynchronous JavaScript and XML and it’s a new technique for web development to build rich interactive web application. The power of this technique comes from the fact that it can send to server requests from the client side, in order to not reload the page. The object that is using AJAX to send and retrieve data between server and the client is named XmlHttpRequest.
To build a cascading drop down in php to retrieve data from a mysql server we will first populate a drop down with the results from a first table from a mysql database. The first table is linked with a second table by a field. When we change the drop down we should assign to OnChanging event an Javascript function that will populate the second drop down . The function will create a new XmlHttpRequest object and make a call to other php script, grab data and populate the second drop down. The script that it’s called will fetch the results for that field that was changed.
Watch a demo here:populate drop down using ajax
Tags:
AJAX,
PHP,
PHP/MYSQL
To search an string into an array of string you can iterate through all the strings one by one and test which is the string that we wanna search. Doing this you will have a complexity of O(n), where n is the number of the strings that array have.
To do search more efficient you should use binary search which have a complexity of O(log2(n)). To use the binary search method in an array of string we assume that we have a sorted array. To sort an array of string efficiently you can use for example Quicksort algorithm , that was previously described, to obtain a good complexity. Of course, you should use binary search algorithm when you are doing something complex that have a complexity bigger or equal to O(n^2).
So to search a string in an array the algorithm selects the middle element of the array and verify if it is equal to our string. If it is equal it stops, if not it sees if the string is bigger then our string and if it is, it searches in the right part of the array string, if not in left part, applying the same algorithm. So it uses a recursive function to search the string in the array.
We will use the following type of string and declare a variable:
type arraystrings=array[1..1000000] of string;
var words:arraystrings;
Here is the binary search algorithm:
function BinSearch(word:string;l:integer;h:integer):integer;
begin
while (StrIComp(pchar(word),pchar(words[(l+h)div 2]))<>0)and(l<>h) do
begin
if strIcomp(pchar(word),pchar(words[(l+h)div 2]))>0 then
l:=(l+h)div 2+1
else
h:=(l+h)div 2-1;
end;
if l<>h then
BinSearch:=(l+h)div 2
else
BinSearch:=0;
end;
It returns the position in the array where it was found. If not returns 0.
To call it you can use:
position:=BinSearch(word,1,nrwords);
where word is the string we search for and nrwords it’s the number of strings in the array.
Tags:
Algorithms,
Delphi
Quicksort it’s an algorithm that it’s very efficient when you wanna sort an array of any type: string, integer, real. I will show you how to sort an array of string, it can be modified easily to sort other types of array.
Quicksort it’s efficient because it’s having a sorting complexity of O(n* log2(n)). An usual sorting algorithm like bubble sort or merge sort it’s taking O(n^2), which it’s very inefficient for array with over 5000 elements.
I will write an implementation of this algorithm in Delphi.
The Quicksort algorithm it’s very similar to divide and conquer algorithm because it splits the array into to sub arrays, sort those sub arrays and put them together after into 1 array sorted. For sorting those array it uses a pivot that it’s positioned in the middle of the array and put in the left, strings that are lower and in the right, the strings that are higher. So for doing this it uses a recursive function because for every sub array divides again in 2 sub array and sort them. So after sorting each sub array , we will have in the final step all the array sorted.
Here is an implementation of Quicksort array of string in Delphi.
First declare a type of array string:
type arraystrings=array[1..100000] of string;
Quicksort algorithm:
procedure QuickSort(var A: arraystrings; Lo, Hi: Integer);
procedure Sort(l, r: Integer);
var
i, j,aux: integer;
y,x:string;
begin
i := l; j := r; x := a[(l+r) DIV 2];
repeat
while strIcomp(pchar(a[i]),pchar(x))<0 do i := i + 1;
while StrIComp(pchar(x),pchar(a[j]))<0 do j := j - 1;
if i <= j then
begin
y := a[i]; a[i] := a[j]; a[j] := y;
i := i + 1; j := j - 1;
end;
until i > j;
if l < j then Sort(l, j);
if i < r then Sort(i, r);
end;
begin
Sort(Lo,Hi);
end;
Tags:
Algorithms,
Delphi
To copy a directory source to a destination directory you will need to scan the source directory with all files and directory and copy to the destination. To accomplish this we should make a recursive function that will copy the files from source to target dir. If it is not a directory in the source dir we should just copy the file to target. If it is a directory in the source dir then we should create a new dir in the target directory and apply the same mechanism, so we need to recall again the same function.
Here is the code to do this:
<?
function copy_directory( $source, $destination ) {
if ( is_dir( $source ) ) {
@mkdir( $destination );
$directory = dir( $source );
while ( FALSE !== ( $readdirectory = $directory->read() ) ) {
if ( $readdirectory == '.' || $readdirectory == '..' ) {
continue;
}
$PathDir = $source . '/' . $readdirectory;
if ( is_dir( $PathDir ) ) {
copy_directory( $PathDir, $destination . '/' . $readdirectory );
continue;
}
copy( $PathDir, $destination . '/' . $readdirectory );
}
$directory->close();
}else {
copy( $source, $destination );
}
}
?>
Calling the function:
copy_directory('dirnameSource','dirnameDestination');
Tags:
PHP,
PHP/MYSQL
This is a short php logout script for logging out a user that you previously logged in through your website:
<?
function redirect($url)
{
echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0;URL=$url\">";
echo "Click <a href=$url>".here.'</a> if you not get redirected';
}
session_start();//initialize the session data
$_SESSION['session_user'] = '';//clear the session user that you created on login
unset($_SESSION['session_user']);//destroy the session variable of the user
//redirect to home page
redirect('index.php');
?>
Tags:
PHP,
PHP/MYSQL
To upload files from a directory in delphi to a ftp server you should first loop through all the files that are in that directory. To do this you should first declare a new type of files, that will be a string of array that will hold the names of files from that directory.
type FilesArray=array[1..1000] of string;
To get all the files from a directory you should use the function FindFirst and FindNext to loop through all the files of directory. To use those functions you should include the unit SysUtils in the uses. To get the attribute of a file you should use the record TSearchRec.The TSearchRec record has the following attribute:
type
TSearchRec = record
Time : Integer;
Size : Integer;
Attr : Integer;
Name : TFileName;
ExcludeAttr : Integer;
FindHandle : THandle;
FindData : TWin32FindData;
end;
The most impostant attributes you need are the following:
Time – when the file was last modified
Size – the size of the file
Attr – file attributes
Name – the name of the file
Here is the function to get all the files from a directory:
function GetFiles(dirpath:string;var nrfiles:integer):FilesArray;
var searchResult : TSearchRec;
allfiles: FilesArray;
begin
nrfiles:=0;
if FindFirst(dirpath+'*.*', faAnyFile, searchResult) = 0 then
begin
repeat
if (searchresult.name<>'.') and (searchresult.name<>'..') then
begin
inc(nrfiles);
allfiles[nrfiles]:=searchresult.name;
end;
until FindNext(searchResult) <> 0;
FindClose(searchResult);//free the memory
GetFiles:=allfiles;
end;
end;
To upload a file to a ftp server we can use the ftp Indy component IdFtp, using the Put command to upload a file. In order not the application to stop when the file is uploaded use a try except statement to catch the error:
procedure UploadFiles(host:string;username:string;password:string);
var files:FilesArray;
j,nrfiles:integer;
idftp1:TIdFtp;
begin
//conect to ftp server
idftp1.Host:=host;
idftp1.Username:=username;
idftp1.Password:=password;
idftp1.Connect;
//go in which directory you need with ChangeDir command
idftp1.ChangeDir('www');
//get all files from local dir
files:=Getfiles(ExtractFilePath(application.exename)+'mydir\',nrfiles);
//upload all files from dir to ftp server
for j:=1 to nrfiles do
begin
idftp1.put(ExtractFilePath(application.exename) + 'mydir\' + files[j], files[j]);
except
On E:Exception do
begin
end;
end;
end;
//disconnect from ftp server
idftp1.Quit;
end;
Tags:
borland delphi,
Delphi
The concept to cache it’s very simple in PHP. First you should have some content on a page in order to cache it. First you should have a directory where all the cached pages are stored.
How it works?
First, we should verify if the page exists in our directory, if exists then it means that the page was saved(chached) before and we can list that page. For caching a page for a period of time we should verify if the date creation of the page cached was before the time that we want to keep the page cached, otherwise we create a fresh cached page. Here is a sample code to do this:
<?php
$filetocache = "../cache/".$filename.".html"; //to cache outside root directory
//time to cache the page
$timecache = 3600 * 24 * 7;//// calculate a period of 1 week
// Here we test if the file exists and if the cached file was created in the period we specify
if (file_exists($filetocache) && (time() - $time cache < filemtime($filetocache)))
{
include($filetocache);//we show the page that was cached previously
echo "<!-- Date cached ".date('jS F Y H:i', filemtime($filetocache))." -->n";
exit;
}
ob_start(); // here we start the output buffer
//HERE we otput the page as html
....
?>
If it not exists we list our page and in the end we save the page to the cache directory, so next time the page is loaded we will get the content from cache directory. So if it time creation is higher then our period then we list the page and rewrite again to the cache directory. Here is the code for saving the contents output displayed on the browser:
<?
ob_start();
//HERE we otput the page as html
.....
$filetocache = "../dircache/".$filename.".html";//this is the page that we should cache, the filename is the name of the page
$fp = fopen($filetocache, 'w'); // first open the cache file for writting
fwrite($fp, ob_get_contents()); // we put the output contents that
are sent to browser
fclose($fp); // close the file
ob_end_flush(); // for sending content to the browser
?>
Tags:
Codes,
PHP
To upload a file to ftp you need a html form where you can insert the ftp details, like the ones described above:
server – is the server on which he wanna upload the file
username – is the user for which he makes the connection to ftp server
password - is the user password for ftp username
path to server – is the path on the ftp server which he wanna upload his file.
user file – is the file of the you wanna upload to ftp server
Hint: If you want to offer to your website members a form where he will upload his file, you should take the ftp server details and path, from a config file. Here we made a complete example how to upload through ftp putting all the details.
We will have a POST form and an enctype of multipart/form-data because we have a file on our form.
The user form that the user will insert info is like that:
<form action="upload.php" method="POST" enctype="multipart/form-data">
<table align="center">
<tr>
<td align="right">
Server:
</td>
<td>
<input size="50" type="text" name="server" value="">
</td>
</tr>
<tr>
<td align="right">
Username:
</td>
<td>
<input size="50" type="text" name="user" value="">
</td>
</tr>
<tr>
<td align="right">
Password:
</td>
<td>
<input size="50" type="text" name="password" value="" >
</td>
</tr>
<tr>
<td align="right">
Path on the server:
</td>
<td>
<input size="50" type="text" name="pathserver" >
</td>
</tr>
<tr>
<td align="right">
Select your file to upload:
</td>
<td>
<input name="userfile" type="file" size="50">
</td>
</tr>
</table>
<table align="center">
<tr>
<td align="center">
<input type="submit" name="submit" value="Upload image" />
</td>
</tr>
</table>
</form>
Now, when the user submits the form, we should get all the details that he inputed and then upload the file to the ftp server.
// the file name that should be uploaded
$filep=$_FILES['userfile']['tmp_name'];
// ftp server
$ftp_server=$_POST['server'];
//ftp user name
$ftp_user_name=$_POST['user'];
//ftp username password
$ftp_user_pass=$_POST['password'];
//path to the folder on which you wanna upload the file
$paths=$_POST['pathserver'];
//the name of the file on the server after you upload the file
$name=$_FILES['userfile']['name'];
To upload the file , first we should establish a connection to the ftp server using ftp_connect and specifing as a parameter the ftp servver. This function return a connection id.
$con_id=ftp_connect($ftp_server);
After connecting to server we should login using the function ftp_login passing three parameters: connection id, ftp user, ftp user password and checking if the login was sucessfull
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// check connection
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name....";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name".".....";
}
After loging in we can upload the file to the server and after that check if the file was uploaded correctly:
// upload the file
$upload = ftp_put($conn_id, 'public_html/'.$paths.'/'.$name, $filep, FTP_BINARY);
// check upload status
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $name to $ftp_server ";
}
In the end we should close the ftp connection using ftp_close passing the connection id:
For uploading big files you should set the time limit of the server in order not to finish the script while it’s uploading:
Here is the complete code:
<?
if(!isset($_POST["submit"])){?>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<table align="center">
<tr>
<td align="right">
Server:
</td>
<td>
<input size="50" type="text" name="server" value="">
</td>
</tr>
<tr>
<td align="right">
Username:
</td>
<td>
<input size="50" type="text" name="user" value="">
</td>
</tr>
<tr>
<td align="right">
Password:
</td>
<td>
<input size="50" type="text" name="password" value="" >
</td>
</tr>
<tr>
<td align="right">
Path on the server:
</td>
<td>
<input size="50" type="text" name="pathserver" >
</td>
</tr>
<tr>
<td align="right">
Select your file to upload:
</td>
<td>
<input name="userfile" type="file" size="50">
</td>
</tr>
</table>
<table align="center">
<tr>
<td align="center">
<input type="submit" name="submit" value="Upload image" />
</td>
</tr>
</table>
</form>
<?}
else
{
set_time_limit(300);//for setting
$paths=$_POST['pathserver'];
$filep=$_FILES['userfile']['tmp_name'];
$ftp_server=$_POST['server'];
$ftp_user_name=$_POST['user'];
$ftp_user_pass=$_POST['password'];
$name=$_FILES['userfile']['name'];
// set up a connection to ftp server
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// check connection and login result
if ((!$conn_id) || (!$login_result)) {
echo "FTP connection has encountered an error!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name....";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name".".....";
}
// upload the file to the path specified
$upload = ftp_put($conn_id, $paths.'/'.$name, $filep, FTP_BINARY);
// check the upload status
if (!$upload) {
echo "FTP upload has encountered an error!";
} else {
echo "Uploaded file with name $name to $ftp_server ";
}
// close the FTP connection
ftp_close($conn_id);
}
?>
Tags:
PHP,
PHP/MYSQL
In this tutorial I want to make a paging tutorial in php.
A friend of mine tell me to help him with a script to do paging in php from a mysql database and I would like to share with all.
If you wanna take data from a xls,csv or other files, from a database like mysql,mssql and you wanna list the results on the page, you may have many results for your result.
I want to present an example so you can understand how a paging can be made in php. I made an example about how to search results from a mysql database and make pagination on the results.
You should first have a form in html from where the user can input the search field:
<form action="Search.php" method="POST">
<table align="center">
<tr><td>Name:</td><td><input type="text" name="search" width="40"></td><td><input name=submit type=submit value=Search><input type=hidden name=hiddensearch value=yes></td></tr>
</table>
</form>
You should now put the code before the html form for verifying if the user submits the form through a POST, if not show the html form. So we will have 2 cases, when when we first post the form we will show the first page and links to all other pages. The links to other pages will look something like search.php?search=Name&page=10 -> this will fetch the results from database for the page number 10 with the search query ‘Name’. Each page will have a number of results say 20, which we will call it pagesize.
First we should connect to the mysql server and make a query on the database. We discuss previously how we can connect to a database and how to make a query, go here for learning how to connect and fetch results from mysql. After we make a query we get each row of the query result and verify if it is on the current page( if it is a post then we will get the first $pagesize records). To select records for a page we should use verify a condition for every row:
if ($nr>=($pagesize*($page-1)+1)&&($nr<=($pagesize*$page)))
{
//write the result
}
Where $nr – is the current record
$pagesize – is the size of a page
$page – is the page number
In the end we should write all the links to other pages( the navigation through result pages part ):
<?
echo '<tr>';
echo '<td>';
for ($i=1;$i<=ceil($nr/$pagesize);$i++)
if ($i!=$page)
echo '<a href="Search.php?search='.urlencode($name).'&page='.$i.'">'.$i.'</a> | ';
else
echo $i.' | ';
echo '</td>';
echo '<tr>';
?>
Here is the complete code:
<?
$server="";
$user="";
$pass="";
$database="";
include("header.php");
if($_POST['hiddensearch'] == 'yes'|| isset($_GET['search']))
{
$connect=mysql_connect($server, $user, $pass)
or die ("Database Connection Error");
$pagesize=20;//how many results will be on a page
$page=$_GET['page'];//curent page
if ($page=="")
$page=1;
//we
if ( $_POST['hiddensearch'] == 'yes')
$name=$_POST['search'];
else
$name=$_GET['search'];
//we write the query
$result = mysql_db_query($database, "SELECT * FROM Table Where Name='".$name."'");
if(mysql_num_rows($result) > 0)
{
?>
<br>
<center>Results <?=mysql_num_rows($result);?> with <b><?echo $name;?> parameter</b></center>
<TABLE align="center" cellspacing="0" cellpadding="0">
<?
$nr=0;
//fetch every row and verify if it is in the current page
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$nr++;
if ($nr>=($pagesize*($page-1)+1)&&($nr<=($pagesize*$page)))
{
echo '<tr>';
echo '<td>'.$row['Name'].'</td>';
echo '</tr>';
}
}
//build the navigation links to other pages
if ($pagesize<$nr)
{
echo '<tr>';
echo '<td>';
for ($i=1;$i<=ceil($nr/$pagesize);$i++)
if ($i!=$page)
echo '<a href="Search.php?search='.urlencode($name).'&page='.$i.'">'.$i.'</a> | ';
else
echo $i.' | ';
echo '</td>';
echo '<tr>';
}
echo '</table>';
}
else
{
echo 'No results found.';
}
mysql_close($connect);
}
else
{
?>
<center><b>Search </b></center><br><br>
<form action="Search.php" method="POST">
<table align="center">
<tr><td>Name:</td><td><input type="text" name="search" width="40"></td><td><input name=submit
type=submit value=Search><input type=hidden name=hiddensearch value=yes></td></tr>
</table>
</form>
<?
}
include("footer.php");
?>
Tags:
PHP,
PHP/MYSQL
I will show you how you can remove word duplicates form a file with an efficient algorithm. Say you are having a large file with words that are line by line in a file on your disk. If you want to remove word or phrases duplicates from file you should first read the entire file into an array of strings, sort it and after that remove duplicate phrases and write back to the file.
Why we sort the array?
Because if we would not sort the array of strings then the complexity of a normal algorithm like, taking each phrase and compare to all other phrases, will have the O(N^2) complexity.
Tip: you should use QuickSort algorithm because if you have over 5000 phrases or words, the application will freeze. The complexity of the QuickSort algorithm is O(n*log(n)), so if you have saying 100.000 phrases, the complexity of the QuickSort will be 5000*log(5000) which is lower then 5000*5000, that a normal sorting algorithm uses to sort an array.
After sorting the array you should go through the array from the first phrase to the last element and compare on each step if the previous phrase is equal with the current phrase. If the phrase is not equal we write it to the output file.
This is the description of an efficient remove duplicates phrases algorithm.This function will work even for 1 million phrases or words. Here is the source code of the procedure:
procedure RemoveDuplicates(pathtofile:string);
var f:textfile;
phrases:array[1..1000000] of string;
nr,i,nrduplicates:integer;
exists:boolean;
s:string;
begin
nrduplicates:=0;
nr:=0;
exists:=false;
assignfile(f,pathtofile);
reset(f);
while not eof(f) do
begin
inc(nr);
readln(f,phrases[nr]);
end;
closefile(f);
QuickSort(phrases,1,nr);
assignfile(f,pathtofile);
rewrite(f);
s:='';
for i:=1 to nr do
if strIcomp(pchar(s),pchar(phrases[i]))<>0 then
begin
writeln(f,phrases[i]);
s:=phrases[i];
end
else
inc(nrduplicates);
closefile(f);
showmessage(inttostr(nrduplicates)+' duplicates removed');
end;
Tags:
Algorithms,
borland delphi,
Delphi