Workshop in Computational Bioskills - Spring 2007
Lesson 11 - PHP Advanced (2)
Connecting to Databases
Running External Programs
File System
Sending an eMail
Connecting to database with PHP
o PHP interface is very friendly.
o The methods embedded within PHP, and you don't need
to import modules for this.
o List of methods (there are many) can be found here
snp.php
See a demo
# Connecting to the DB server. If succeeded
# returns a linker object, otherwise returns false.
# The arguments are: host, user, password
$link = mysql_connect('lightning','bioskill','bioskill');
# Checking connection. If failed - print error message
if (!$link) die("connection error: ".mysql_error());
# Selecting the database
# [, $link] specifies what is the relevant connection (if several exist).
mysql_select_db('BioEx3'[,$link])
or die("could not select db".mysql_error());
# Sending a query. $link specifies what is the relevant connection.
($result = "mysql_query("select * from snpNih limit 5"[,$link]))
or die("query failed".mysql_error() );
# Printing the result.
print "<table>";
while ($line = mysql_fetch_array($result))
{
print "<tr><td>";
foreach ($line as $col)
{ print "$col"."</td><td>"; }
print "</td></tr>";
}
A few more useful functions:
Now let's see how to use all this to do a smart query and create new tables.
create_table.php(this runs the program).
Here is a demo of the form and the result
Running External Programs
o Many things can be written in PHP, but sometimes there is a
need to run an external program.
o This can be done in a similar way to perl, with backticks
operator, or with system() or exec() calls.
o The program must be executed from a safe jailed
directory /cs/jailbird/home/.
# returns the command output
$tree = `tree`;
print $tree;
# Does the same but return only the last line of the output.
# $retval is the return value of the command
$tree = system('tree', $retval)
print $tree;
# exec returns the last line of the command output.
# $array argument is filled with the output, where each element is a row.
$output = exec('ls -l', $output_array);
foreach ($output_array as $line)
{
print $line.'<br>';
}
The File System
As you could have guessed, all the commands required for
traversing and changing the file system exists.
chdir,
mkdir,
chmod,
touch,
copy,
delete,
symlink
file_system.php, see the code
Sending an e-Mail
# mail(to, subject, message[, additional parameters])
# additional parameters are string headers.
$message_body = "this is the body";
mail('bioskill@cs.huji.ac.il','header',
$message_body, 'From: naomih@cs.huji.ac.il');
mail.php