Practical Web Programming
Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Monday, January 26, 2009

PHP: How to Print Each Character in a String

With PHP's growing string functions, you will be able to find one that will suit your need. For instance the substr, this function will return the portion of string specified by the start and length parameters. You can you use it to print each character in a string.

Here's an example.

    
$string = "Joel P. Badinas";

for ($i = 0; $i < strlen($string); $i++)
{
print "[" . $i . "] " . substr($string, $i, 1) ."<br/>";
}

?>


The output will be like this.

  [0]  J
[1] o
[2] e
[3] l
[4]
[5] P
[6] .
[7]
[8] B
[9] a
[10] d
[11] i
[12] n
[13] a
[14] s

Friday, January 23, 2009

How to Submit an HTML Form to a New Window

Sometimes, for whatever reason, you want to submit an HTML form to a new window. To do this, you just need to add the attribute target='_blank' to your HTML form. Here's an example.

<form target='_blank' method='POST' action='index.php'>
<br/>First Name: <input type='text' name='firstname' value='' />
<br/>Last Name: <input type='text' name='lastname' value='' />
<br/><input type='submit' name='submit' value='Submit' />
</form>


And here's the PHP version.

<?php

print "<form target='_blank' method='POST' action='index.php'>
<br/>First Name: <input type='text' name='firstname' value='' />
<br/>Last Name: <input type='text' name='lastname' value='' />
<br/><input type='submit' name='submit' value='Submit' />
</form>";

?>


Once you click the Submit button, the browser will submit and open a new window where the form will be handled.

Thursday, January 22, 2009

PHP: Using foreach to Loop Through Array

The foreach looping construct in one of the less used looping construnct in the programming language, and PHP is not an exception. This is because in PHP, the foreach works only with arrays and will spit an error if used with other data type.

Anyways, using the foreach loop construct is really easy. See example below.

$array = array("j", "o", "e", "l", "b", "a", "d", "i", "n", "a", "s");

foreach ($array as $char)
{
print $char."<br/>";
}


The above example will output below.

j
o
e
l
b
a
d
i
n
a
s

Wednesday, January 21, 2009

How to Truncate Text in PHP

Here's a simple tutorial on how to truncate text in PHP. In this tutorial, I'll be using the substr function. See the sourcecode below.

<?php

$text = 'The quick brown fox jumps over the lazy dog';
$truncated1 = substr($text, 0, 20);
$truncated2 = substr($text, 20, 40);

print "<br/>The original text: ". $text;
print "<br/>The truncated text 1: ". $truncated1;
print "<br/>The truncated text 2: ". $truncated2;

?>


Using the substr function, you can truncate a text to whatever length you want by changing the third parameter and also change the start position by changing the second parameter.

The above PHP script will output the following:

The original text: The quick brown fox jumps over the lazy dog
The truncated text 1: The quick brown fox
The truncated text 2: jumps over the lazy dog

Thursday, January 15, 2009

PHP: How to Delete the First and Last Character in a String

Using PHP's substr and strlen functions, you can delete the first and last character in a string. Here's the syntax of the functions from the PHP documentation website.

string substr  ( string $string  , int $start  [, int $length  ] )

int strlen ( string $string )


substr returns a part of a string, while strlen returns the length of a string. See below for the example.

<?php

$my_name = "Joel Badinas";
$str_length = strlen($my_name);

$no_first_char = substr($my_name, 1, $str_length);
$no_last_char = substr($my_name, 0, $str_lenght - 1);

print ("Original String : " . $my_name . "<br/>");
print ("No first character: " . $no_first_char . "<br/>");
print ("No last character: " . $no_last_char . "<br/>");

?>


The above source code will display the following:

Original String : Joel Badinas
No first character: oel Badinas
No last character: Joel Badina

Tuesday, January 06, 2009

PHP: How to Format Date Using date and strtotime Functions

In PHP formatting a date to your desired format is so easy using the date and strtotime functions.

According to the PHP documentation strtotime parses any English textual datetime description into a Unix timestamp. It expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC)

Syntax:

int strtotime  ( string $time  [, int $now  ] )


Example:

print strtotime("Dec. 25, 2008 10:00 AM");


The date function on the other hand returns a string formatted time/date according to the given format string using the given integer timestamp or the current time if no timestamp is given.

Syntax:

string date  ( string $format  [, int $timestamp  ] )


Example:

print date("M d, Y H:i:s A");


So much for the long explanation. Here's how to format a date using the both functions.

print date("M d, Y H:i:s A", strtotime("Dec. 25, 2008 10:00 AM"));


For the complete list of format for the date functions, visit the PHP documentation here.

Tuesday, December 30, 2008

PHP: How to Dynamically Alternate the Table Row Background Color

In PHP, making the <table> row background color alternate dynamically is relatively easy. The key here is PHP's modulo (%) operator. Using the % operator inside a loop construct, you can reference every other row in an HTML <table>. See the example below.

Create the CSS rules.
.alt-color-1{
background-color:red;
}

.alt-color-2{
background-color:green;
}


Create the PHP script.
<?php
print "<table width='200' border='1' cellspacing='1' cellpadding='1'>";
for ($i = 0; $i < 10; $i++)
{
if (($i % 2) == 0)
{
$alt = "alt-color-1";
}
else
{
$alt = "alt-color-2";
}

print "<tr class='".$alt."'>";
print "<td>".$i."</td>";
print "<td>".$i."</td>";
print "</tr>";
}
print "</table>";
?>


Put it all together.
<html>
<head>
<title>Alternate Color in Table Rows</title>

<style>
.alt-color-1{
background-color:red;
}
.alt-color-2{
background-color:green;
}
</style>

</head>
<body>

<?php
print "<table width='200' border='1' cellspacing='1' cellpadding='1'>";

for ($i = 0; $i < 10; $i++)
{
if (($i % 2) == 0) //USE THE MODULO OPERATOR
{
$alt = "alt-color-1";
}
else
{
$alt = "alt-color-2";
}

print "<tr class='".$alt."'>";
print "<td>".$i."</td>";
print "<td>".$i."</td>";
print "</tr>";
}
print "</table>";
?>

</body>
</html>


After executing the PHP script, here's what the webpage will look.

PHP: How to Dynamically Alternate the Table Row Background Color

Friday, December 26, 2008

PHP: How to Display The Current Month in Calendar Style

Displaying the current month in a calendar style is very handy and user-friendly for a website, specially for a blog. Using a calendar-style navigation your visitors can easily navigate through your previous posts and articles.

Fortunately, in PHP, this seemingly difficult task in HTML is relatively easy. Just by using a nested For Loop and PHP's Date functions, use can build your own calendar.

Here's the simple source code.

<?php
$now = getdate(time());
$time = mktime(0,0,0, $now['mon'], 1, $now['year']);
$date = getdate($time);
$dayTotal = cal_days_in_month(0, $date['mon'], $date['year']);

print '<table><tr><td colspan="7"><strong>' . $date['month'] . '</strong></td></tr>';
for ($i = 0; $i < 6; $i++)
{
print '<tr>';
for ($j = 1; $j <= 7; $j++)
{
$dayNum = $j + $i*7 - $date['wday'];
print '<td';
if ($dayNum > 0 && $dayNum <= $dayTotal)
{
print ($dayNum == $now['mday']) ? ' style="background: #aaa;">' : '>';
print $dayNum;
}
else
{
print '>';
}
print '</td>';
}
print '</tr>';
if ($dayNum >= $dayTotal && $i != 6)
{
break;
}
}
print '</table>';
?>

Here's how the calendar will look like.


To make it fancier, all you have to do now is use CSS to add colors and styles.

Saturday, December 20, 2008

PHP: Checking If Email is Valid with filter_var Function

In PHP 4, checking if an email is valid uses regular expressions. But with PHP 5, you can use the filter_var function. This function returns the filtered data, or false if the filter fails.

Here's the syntax.

mixed filter_var ( mixed $variable [, int $filter [, mixed $options ]] )

Where:
variable = Value to filter.
filter = ID of a filter to use. Defaults to FILTER_SANITIZE_STRING.
options = Associative array of options or bitwise disjunction of flags.


Here's how to use the function.

if (filter_var(trim($email), FILTER_VALIDATE_EMAIL))
{
echo $email . " is valid.";
}
else
{
echo $email . " is invalid.";
}

Friday, December 05, 2008

PHP: A Simple Function to Create an HTML Select Date Options

Here's a simple PHP function to create a select date options that you can use in your HTML forms to let users select a date. This is simple and easy to use. Below is the function definition.

//RETURN DATE OPTIONS IN HTML
function get_date_options($year = 0000, $month = 00, $day = 00)
{
$ret_val = "";

//ASSEMBLE MONTHS
$options = "<option value='00'>MM</option>";
for ($i = 1; $i < 13; $i++)
{
$attribute = "value='".$i."'";
if ($i == $month)
{
$attribute .= " selected ";
}
$options .= "<option ".$attribute.">".str_pad($i,2,0,STR_PAD_LEFT)."</option>";
}
$ret_val .= "<select name='month'>".$options."</select> / ";

//ASSEMBLE DAYS
$options = "<option value='00'>DD</option>";
for ($i = 1; $i < 32; $i++)
{
$attribute = "value='".$i."'";
if ($i == $day)
{
$attribute .= " selected ";
}
$options .= "<option ".$attribute.">".str_pad($i,2,0,STR_PAD_LEFT)."</option>";
}
$ret_val .= "<select name='day'>".$options."</select> / ";

//ASSEMBLE YEARS
$options = "<option value='0000'>YYYY</option>";
for ($i = 2008; $i < 2051; $i++)
{
$attribute = "value='".$i."'";
if ($i == $year)
{
$attribute .= " selected ";
}
$options .= "<option ".$attribute.">".$i."</option>";
}
$ret_val .= "<select name='year'>".$options."</select>";

return $ret_val;
}


Here's a simple way to use it.

Enter your birthday : <?php print get_date_options() ?>


And here's a way to use it to make default to a date.

Enter your birthday : <?php print get_date_options("2008", "12", "05") ?>

Tuesday, December 02, 2008

PHP: Simple String to Date / Date to String Conversion Functions

In PHP even a simple INSERT and UPDATE to the database, MySQL specially, can lead to bugs in DATETIME fields. Whenever I do database insertion, I run into this kind of problem. Instead of the actual date, the string "0000-00-00 00:00:00" appears. This string represents NULL in date.

To combat this problem, I created simple String to Date / Date to String conversion functions. Before inserting/updating date to a MySQL database, convert first the date using text_to_date_format. Then, when querying, use the date_to_text_format to make the date more human readable.


//FORMAT DATE TO STRING
function date_to_string_format($date)
{
if (strtotime($date))
{
return date("M. d, Y h:i A", strtotime($date));
}
else
{
return "";
}
}

//FORMAT STRING TO DATE
function string_to_date_format($date)
{
if (strtotime($date))
{
return date("Y-m-d H:i:s", strtotime($date));
}
else
{
return "0000-00-00 00:00:00";
}
}


Here's what your INSERT SQL statement should look like using the above function.


$sql = "INSERT INTO my_table (
my_id,
my_date
) VALUES (
1, ".
string_to_date_format($var_date).")";

Thursday, November 06, 2008

PHP: How to Print/Echo HTML Tags More Effeciently

PHP is very good at handling strings. But sometimes you have to help PHP do it's job more efficiently. In my recent web development job, I noticed that I always use PHP to print HTML tags. Here's an example of how I would do it before.


<?php
echo "<table>";
echo "<tr>";
echo "<td>"."How to print/echo HTML tags in PHP."."</td>";
echo "</tr>";
echo "</table>";
?>


Now, here's how I do it now which I think is more efficient and HTML readable.

<?php
echo "
<table
<tr>
<td>"."How to Print/Echo HTML tags in PHP More Effeciently"."</td>
</tr>
</table>
";
?>


Notice the difference? In the first PHP sourcecode, I use the echo five times, while in the second one, I use only once.

Using echo to print HTML tags is not expensive in terms of server resources, but if you're using it the way I did in the first example for all your pages and and you have thousands of users to your website, you'll see the difference.

Saturday, October 11, 2008

Developers Definitely Need a Hug Sometimes

Monday, August 04, 2008

PHP: How to Display Errors Without Tweaking the Configuration File

Displaying errors in your PHP applications by tweaking the configuration file is sometimes troublesome, especially for most beginners. Luckily, you don't have to get your hand dirty to deal with it.

After installing MAMP (Mac, Apache, MySQL, PHP) in my MacBook, I had a hard time debugging my PHP codes as MAMP's default configuration do not allow showing of error.

In production environment, showing errors is a big mistake you can commit as your website is more vulnerable to hack attacks. But in development environment such as localhost, showing errors save you a lot of time in debugging.

Here's what I did.


ini_set('display_errors', 1);
error_reporting(E_ALL);


Put this two lines of codes in your index file and you'll see all the errors in your PHP codes will show off, if there are any (minus the links, of course).

Friday, February 29, 2008

PHP: How to Get the Current Server Date and Time

Adding date and time to your website gives it an impression of being fresh and updated regularly. In PHP, getting the current server date and time is a no brainer using the getdate() function.

To add date and time, see the PHP script below.

<html>
<head>
<title>DATE and TIME</title>
</head>

<body>
<?php
$date_array = getdate();
print "Server Date : $date_array[month] $date_array[mday], $date_array[year].<BR>";
print "Server Time : $date_array[hours]:$date_array[minutes]:$date_array[seconds]<BR>";
?>
</body>
</html>

Wednesday, February 27, 2008

Types of Looping Construct in Visual Basic

A loop is a sequence of instructions that is continually repeated until a certain condition is reached. It is a fundamental programming idea that is commonly used in writing programs. Without looping in a programming language, hundreds to thousands of repeated computer instructions would be time consuming, if not impossible to perform.

Here are the four types of looping construct in Visual Basic.

For Loop example
Private Sub ForLoop()
Dim intX As Integer

'-->INCREMENTING
For intX = 0 To 10
MsgBox "For Loop #" & intX, vbInformation, _
"Visual Basic Looping"
Next

'-->DECREMENTING
For intX = 10 To 0 Step -1
MsgBox "For Loop Step -1 #" & intX, vbInformation, _
"Visual Basic Looping"
Next
End Sub


Do While Loop example
Private Sub DoWhileLoop()
Dim intX As Integer

intX = 0
Do While intX < 10
MsgBox "Do While Loop #" & intX, vbInformation, _
"Visual Basic Looping"
intX = intX + 1
Loop
End Sub


While Wend Loop example
Private Sub WhileWendLoop()
Dim intX As Integer

intX = 0
While intX < 10
MsgBox "While Wend Loop #" & intX, vbInformation, _
"Visual Basic Looping"
intX = intX + 1
Wend
End Sub


Do Loop Example
Private Sub DoLoop()
Dim intX As Integer

intX = 0
Do
MsgBox "Do Loop #" & intX, vbInformation, _
"Visual Basic Looping"
intX = intX + 1
Loop While intX < 10
End Sub

Tuesday, February 26, 2008

PHP: How To Redirect To Another Website

Redirecting to another website in PHP is very simple and straightforward. Just by using the PHP header function and the the URL where to you want to redirect as a parameter, you can accomplish this task.

Here's the example below.
<html>

<header>
<title>PHP Redirection</title>
</header>

<body>

<?php
$url= "http://www.joelbadinas.com/";

/* Redirect browser */
header("Location: $url");

/* Make sure that code below does not
get executed when we redirect. */
exit;
?>

</body>

</html>


To use this script, just copy and paste it to your favorite PHP/HTML text editor, save it with a .php extension and put it in you web server. When you run it, you will be redirected to this blog.

Enjoy, and comments are welcome. (^_^)

Monday, February 25, 2008

How to Get The RGB of a Color Value in Visual Basic

This functions will returns the red, blue and green value of a color value.


'-->RETURNS THE RED COLOR VALUE
Private Function Red(ByVal Color As Long) As Integer
Red = Color Mod &H100
End Function

'-->RETURNS THE GREEN COLOR VALUE
Private Function Green(ByVal Color As Long) As Integer
Green = (Color \ &H100) Mod &H100
End Function

'-->RETURNS THE BLUE COLOR VALUE
Private Function Blue(ByVal Color As Long) As Integer
Blue = (Color \ &H10000) Mod &H100
End Function


Here's how to use this functions (see the image above for the result):

Private Sub Command1_Click()
MsgBox "Red: " & Red(Me.BackColor) & "," & vbNewLine & _
"Blue: " & Blue(Me.BackColor) & "," & vbNewLine & _
"Green: " & Green(Me.BackColor), _
vbInformation, "Form RGB Color"
End Sub

Thursday, February 21, 2008

How to Full Format Date in Visual Basic

This function shows how to full format date in Visual Basic 6.

Here's how to call the function: MsgBox FullFormatDate("02/24/1978")
The result will be: Friday, 24th Mar 1978

Public Function FullFormatDate(ByVal strDate As String) As String
Dim strDay As String

strDay = Format(strDate, "DD")
Select Case strDay
Case 1, 21, 31
strDay = Format(strDay, "#0") & "st"
Case 2, 22
strDay = Format(strDay, "#0") & "nd"
Case 3, 23
strDay = Format(strDay, "#0") & "rd"
Case Else
strDay = Format(strDay, "#0") & "th"
End Select

FullFormatDate = Format(strDate, "DDDD, ") & strDay & _
Format(strDate, " MMM YYYY")
End Function

Sunday, February 10, 2008

Count the Forms Loaded in a Visual Basic Project

Sometimes you want to count the forms loaded in your Visual Basic project during runtime.


This simple and ready to use function will return the number of forms loaded in a project.

Public Function FormCount() As Long
Dim frmForm As Form
For Each frmForm In Forms
FormCount = FormCount + 1
Next
End Function


To use, just call the function like this.

MsgBox "# of forms loaded: " & FormCount

Recent Post