Joel Badinas dot Com: Web Programming Tutorials

Friday, February 27, 2009

How to Pass Value from Javascript to PHP

Although JavaScript and PHP is not the same technology, JavaScript being a client-side technology and PHP a server-side, you can actually pass values from PHP to JavaScript and vice-versa. To do this, all you need is to use a cookie.

In this example source code, I will create a cookie in JavaScript and retrieve the cookie value using PHP. Read on.

JavaScript code to create cookie.

<script type='text/javascript'>
function createCookie(name, value,expiredays)
{
var expiry_date = new Date();
expiry_date.setDate(expiry_date.getDate() + expiredays);
document.cookie=name+ "=" +escape(value)+
((expiredays==null) ? ""
:";expires="+expiry_date.toGMTString());
alert("'" + name + "' cookie created.");
}
</script>


HTML code to call the createCookie function.

<input type="button" value="Create Cookie using JavaScript" 
onclick="createCookie('YourName', 'Joel Badinas')"/>


HTML form for submitting request to the server for the PHP code.

<form method="POST" action=""> 
<p>
<input type="submit" name="submit" value="Get Cookie using PHP"/>
</p>
</form>


PHP code that will read the cookie.

<?php
if (isset($_POST["submit"]))
{
print "Cookie value is '".$_COOKIE["YourName"]."'";
}
?>


Putting it all together.

<html>
<head>
<title>Practical Web Programming</title>

<script type='text/javascript'>
function createCookie(name, value,expiredays)
{
var expiry_date = new Date();
expiry_date.setDate(expiry_date.getDate() + expiredays);
document.cookie=name+ "=" +escape(value)+
((expiredays==null) ? ""
:";expires="+expiry_date.toGMTString());
alert("'" + name + "' cookie created.");
}
</script>

</style>

</head>
<body>

<p method="POST" action="">
<p>
<input type="button" value="Create Cookie using JavaScript"
onclick="createCookie('YourName', 'Joel Badinas')"/>
<input type="submit" name="submit" value="Get Cookie using PHP"/>
</p>
</form>

<?php
if (isset($_POST["submit"]))
{
print "Cookie value is '".$_COOKIE["YourName"]."'";
}
?>

</body>
</html>


There you have it.

Thursday, February 19, 2009

PHP: How to Get the Time Elaped

Using PHP's time function, you can get the time elapsed of any process in your web application. The time function returns the current Unix timestamp.

Here's a simple script to demonstrate it.


<?php

$t1 = time();

print "Start time : ".$t1."<br>";

for ($i = 0; $i < 90000000; $i++)
{
print "";
}

$t2 = time();
print "End time : ".$t2."<br>";
print "Time elapsed (s) : ".($t2 - $t1)."<br>";

?>


The script above will output the following.


Start time : 1235100956
End time : 1235100980
Time elapsed (s) : 24

Sunday, February 15, 2009

Solved: Can't Change Blogger Blog Shortcut Icon

Ok, you followed my instructions on how to change your blog/website shortcut icon but your Blogger blog is still showing the default Blogger shortcut logo. Don't despair, you are not alone. I myself was in that situation before when I tried to change this blog's shortcut icon.

In your Blogger template head tag section, you will see a b:include tag named all-head-content (highlighted in red) . When your is blog is visited (or loaded in HTML), the Blogger engine will replace that tag with all the meta tags for you blog including the shortcut icon, and you have no control over this.

<head>
<b:include data='blog' name='all-head-content'/>
<title><data:blog.pageTitle/></title>
<b:skin><![CDATA[/*


Fortunately, I found a simple trick to outsmart Blogger. When you insert your HTML shortcut icon code, put it after the b:include tag named all-head-content. Here's an example from this blog.

<head>
<b:include data='blog' name='all-head-content'/>
<title><data:blog.pageTitle/></title>
<link href='http://kabalweg.googlepages.com/joelbadinas.com.ico' rel='shortcut icon'/>
<b:skin><![CDATA[/*


Doing it this way will override the shortcut icon from the Blogger enginge.

Friday, January 30, 2009

PHP: How to Get the Last Element of an Array

If you know it's length, getting the last element of an array is easy. You just put the index of the last element and you have it's value. But what if you don't know it's length or your array is populated at runtime and it's length is dynamic? Now you got a problem :).

To solve this, you also need a dynamic approach. Using PHP's count function, you can dynamically get the last element of an array. Here's how.

<?php

//Getting the last element of an array dynamically

$arr = array("one", "two", "three", "four", "five");
print "Last element: " . $arr[count($arr) -1];

?>


Take note that in PHP, arrays starts at 0, so if you have five elements, the index of the first element is 0 and the last's is 4. So the code count($arr) will return 5, while count($arr) - 1 will return 4.

Thursday, January 29, 2009

Types of Loops in PHP

A programming loop is a sequence of statements which is specified once but can also be performed several times in succession. Looping construct is one of the most powerful feature of all programming language. Using loops, you can duplicate task to any number of repetitions.

If PHP, this are four types of looping construct, the while, do...while, for and foreach loop. The following example demonstrates how to use each loop.

Using the while loop.

<?php

$x=1;
while($x<=10)
{
echo "The number is " . $x . "<br />";
$x++;
}

?>


while loop output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10


Using the do...while loop.

<?php

$x=1;
do
{
echo "The number is " . $x . "<br />";
$x++;
}
while ($x<10);

?>


do...while loop output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9


Using the for loop.

<?php

for ($x=1; $x<=10; $x++)
{
echo "The number is " . $x . "<br />";
}

?>


for loop output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
The number is 10


Using the foreach loop.

<?php

$arr=array("one", "two", "three", "four", "five");
foreach ($arr as $value)
{
echo "Value: " . $value . "<br />";
}

?>


foreach loop output:

Value: one
Value: two
Value: three
Value: four
Value: five

Wednesday, January 28, 2009

PHP: How to Parse XML Using the DOMDocument Class

I this example, I will show you how to parse (or read) XML documents using PHP. I will be using the XML that I created in the Output MySQL Records to XML Using PHP post.

To parse XML, I will be using PHP's DOMDocument class. Here's the example.

<?php

//CREATE AN INSTANCE OF DOMDocument() CLASS
$doc = new DOMDocument();

//LOAD THE XML
$doc->loadXML($xml);

//READ THE <employee> AND LOOP THROUGH IT

$employees = $doc->getElementsByTagName("employee");
foreach($employees as $employee)
{
//READ THE <firstname> AND GET THE NODE VALUE
$firstnames = $employee->getElementsByTagName("firstname");
$firstname = $firstnames->item(0)->nodeValue;

//READ THE <lastname> AND GET THE NODE VALUE
$lastnames = $employee->getElementsByTagName("lastname");
$lastname = $lastnames->item(0)->nodeValue;

//DISPLAY IT
print $firstname." ".$lastname."<br/>";
}

?>


The above source code will have the following output.

Steven King
Neena Kochhar
Lex De Haan
Alexander Hunold
Bruce Ernst
David Austin
Valli Pataballa
Diana Lorentz
Nancy Greenberg
Daniel Faviet
John Chen
Ismael Sciarra
Jose Manuel Urman
Luis Popp
Den Raphaely
Alexander Khoo
Shelli Baida
Sigal Tobias
Guy Himuro
Karen Colmenares
Matthew Weiss


If you want to parse an physical XML file (an XML file that is saved in your server), use load rather than loadXML.

Tuesday, January 27, 2009

PHP: How to Create XML Document from MySQL Records

In this example, I'll be showing how to create XML document from MySQL records using PHP.

XML (Extensible Markup Language) is a general-purpose specification for creating custom markup languages. Aside from creating web pages, the most important use of XML is data sharing. Using XML you can pass data to different computer and applications without it being converted into another form.

Fortunately for PHP developers, creating XML from MySQL data is just like creating HTML. I'll be using the database table from this post. Here's the source codes.

<?php

//CREATE A DATABASE CONNECTION
$db_conn = mysql_connect("localhost", "root", "root1")
or die("Cannot connect to the database. ".mysql_error());
//SELECT THE DATABASE TO USE
mysql_select_db("test");

$sql = "SELECT
first_name, last_name, email
FROM employees";

$result = mysql_query($sql, $db_conn);

$xml = "<?xml version='1.0' encoding='UTF-8'?>
<employees>";
while ($row = mysql_fetch_assoc($result))
{
$xml .= "<employee>";
$xml .= "<firstname>".$row["first_name"]."</firstname>";
$xml .= "<lastname>".$row["last_name"]."</lastname>";
$xml .= "</employee>";
}
$xml .= "</employees>";

//DISPLAY THE XML
print $xml;

?>


This will output the following. I added line breaks (using enter key) at the end of every </employee> tags to make it more readable.

<?xml version='1.0' encoding='UTF-8'?>
<employees>
<employee><firstname>Steven</firstname><lastname>King</lastname></employee>
<employee><firstname>Neena</firstname><lastname>Kochhar</lastname></employee>
<employee><firstname>Lex</firstname><lastname>De Haan</lastname></employee>
<employee><firstname>Alexander</firstname><lastname>Hunold</lastname></employee>
<employee><firstname>Bruce</firstname><lastname>Ernst</lastname></employee>
<employee><firstname>David</firstname><lastname>Austin</lastname></employee>
<employee><firstname>Valli</firstname><lastname>Pataballa</lastname></employee>
<employee><firstname>Diana</firstname><lastname>Lorentz</lastname></employee>
<employee><firstname>Nancy</firstname><lastname>Greenberg</lastname></employee>
<employee><firstname>Daniel</firstname><lastname>Faviet</lastname></employee>
<employee><firstname>John</firstname><lastname>Chen</lastname></employee>
<employee><firstname>Ismael</firstname><lastname>Sciarra</lastname></employee>
<employee><firstname>Jose Manuel</firstname><lastname>Urman</lastname></employee>
<employee><firstname>Luis</firstname><lastname>Popp</lastname></employee>
<employee><firstname>Den</firstname><lastname>Raphaely</lastname></employee>
<employee><firstname>Alexander</firstname><lastname>Khoo</lastname></employee>
<employee><firstname>Shelli</firstname><lastname>Baida</lastname></employee>
<employee><firstname>Sigal</firstname><lastname>Tobias</lastname></employee>
<employee><firstname>Guy</firstname><lastname>Himuro</lastname></employee>
<employee><firstname>Karen</firstname><lastname>Colmenares</lastname></employee>
<employee><firstname>Matthew</firstname><lastname>Weiss</lastname></employee>
</employees>


Note: To view the full output, right click on the browser and select 'View Source' or 'View Page Source'.

Recent Post