Wednesday, April 23, 2014

PHP and HTML Technique 1


Thus far we have only looked at PHP as a standalone code. However, one of the main reasons PHP is useful as a web programming language  is that it can be blended with html. This allows for hyrbid code that can take the results of a method or function, and display it in a web browser

It is important to keep in mind the differences between the two languages, as doing so will help you  know what to change or modify when it comes time to edit your webpage. As a reminder, HTML is a markup language, and should only be used to render  and  format text and media. PHP is a programming language that should be used to make decisions on  what text and media the html will display,. The two languages complement each other, and neither  should be used as a replacement for the other.

With that in mid, there are two methods to go about blending the two languages. The first is to write have a HTML code with pieces of inserted within it. 
<html> 
 <title>HTML and PHP</title>
 <body>
 <h1>Best Friends for life</h1>

 <?php
 //PHP CODE
?>

 <b>HTML <3 PHP</b>

 <?php
 //MORE PHP CODE
 ?>
 </body>
 </html>

Notice that the PHP code is completely separated by start and close PHP tags, and there exists no HTML within the PHP. However, the HTML tags are not concerned with excluding PHP. 

In other words, there is no HTML in the PHP. But there's PHP in the HTML. 

This is the preferred method for integrating the two languages, especially for content heavy and complicated web pages. However, there is still a place for the integration technique demonstrated in the next blog post.





Monday, April 21, 2014

PHP and MySQL Databases II

Once you open your MySQL database in your PHP code, it is ready to be queried for data. When retrieving data from a database, it is good practice to put the results of the query in a variable. This allows the for the data to be referenced at a later point in code, after the database has been closed.

Assuming that you have already opened your database, retrieving data from it is only a statement away.
The retrieval statement takes twos parameters:
1. the connection statement that you used to open the database
2. the query statement itself

Since MySQL databases must be queried using SQL, parameter number 2 needs to be an SQL statement,

$mycon=mysqli_connect("example.com","peter","abc123","my_db");

$myresult = mysqli_query($mycon,"SELECT * FROM cities");


The above statement takes all of the data in the "cities" table of "my_db",
and stores it into a variable called myresult. 

As mentioned earlier, long after the database connection has been closed, the information in the "cities" table can still be used through referencing the myresult variable.

Deleting information dynamically, through PHP code, works in a similar fashion. The select statement is replaced with a delete  statement. 

mysqli_query($con,"DELETE * FROM cities");

The above statement will remove all of the data in the "cities" table of "my_db".
Since data is being deleted and not retrieved, there is no need to store the results of the statement. in a local variable.


PHP and MySQL Databases

Part of what makes programming in PHP so useful for web development is its compatibility with MySQL database.  If you are not already familiar, MySQL is a simple, open source database management system that allows a user to store large amounts of data in an organized fashion.

This tutorial assumes that you have  already created and saved your MySQL database, and are now preparing to retrieve data from it within your PHP code.


Opening your PHP database is the firs step. This is done through the MySQL connection command,
The command takes four parameters:
    • The host of the machine hosting the database. This can be a website or database,
    • The database username 
    • The database password
    • The database name.
Here is an example

$con=mysqli_connect("example.com","peter","abc123","my_db");

Once the database is opened, you can query it for the data you need. Specific details on MySQL querying will be covered in a future blog post. 

After you have completed and stored the retrieved information, it is important that you remember to close your connection to the database. This is important as it helps to conserve the host's resopurces, as well as prevent unauthorized access to the database. 

Here is an example of a close statement.

mysqli_close($con);




Monday, March 31, 2014

PHP Switches



The switch block allows a program to choose what code to execute based on the value of a variable. This is helpful in handling multi-case scenarios where you are unsure about what the variable's value will be at the time of execution. It also servers as a more organized alternative to multiple "if else" statements.

The following example deals with code that executes based on the numeric value of variable $x

switch ($x)
{
case 4:
  $x=$x+2
  break;

case 5:
$x=$x+4  break;

case 6:
$x=$x+10
  break;

default:
  $x=7;
}

The code above determines what value to add to $x, based on what value it holds going into the switch statement. For example, 2 is added to $x if $x=4 at the time of execution. If $x is not equal to 4, 5, or 6 at the time of execution, then the "default" code is executed, setting $x=7.

While it would be possible to execute the same code with a handful of "if and else" statements, most would agree that the switch option provides for a cleaner code.


Saturday, March 15, 2014

Arrays in PHP

In most languages, including PHP, an array is a collection of objects of the same data type. An array could consist of strings,  integers,  or virtually any other data type supported by PHP. Using array's can add some organization to code, when they are strategically used in place of local variables


To define an array, the following two syntax's can be used

1. Declaring and defining the array at the same time
$colors= array("blue", "green", "red", "yellow");

2. Declaring the array, and defining it later

$colors=array()
$colors[0]="blue"
$colors[1]="green"
$colors[2]="red"
$colors[3]="yellow"

No matter what syntax you used to define the array, individual array elements can be referenced by their position at a later point in time

echo $colors[1]
//would print "green"

In addition to referring to individual array elements, PHP allows a handful of sorting mechanisms for arrays:
  • sort() - sort arrays in ascending order
  • rsort() - sort arrays in descending order
  • asort() - sort associative arrays in ascending order, according to the value
  • ksort() - sort associative arrays in ascending order, according to the key
  • arsort() - sort associative arrays in descending order, according to the value
  • krsort() - sort associative arrays in descending order, according to the key
[provided by W3 schools]

Finally, a very useful feature with Arrays in PHP is the ability to manually choose and assign a key to each array element.
Picture a situation in which instead of referring to a colour by its number, we could use a person's name. This would be useful in a situation where we were keeping track favorite colours.

$age=array();
$favorite['jon']="green";
$favorite['mike']="red";
$favorite['sam']="blue";
$favorite['andrew']="yellow";


$favorite['jon'] would equal 'green'
echo "Jon's favorite colour is". $favorite['jon']



Midsize Program



The following is a simple Binary to decimal converter program written in PHP.
Please note that the Binary input is hard coded, as this blog has yet to cover user inputs within PHP.
However, the program will run and execute for any Binary number that is written in.

<?php

$BinaryNumber="1010";
$StringLength=strlen($BinaryNumber);
 $DecimalTotal=0;
$NumericvalueofDigit=0;

for ($i=1; i<=$StringLength; $i++){

$BinaryDigit=substr($BinaryNumber, ($i*-1),1);
$NumericvalueofDigit=((int)$BinaryDigit)*pow(2,($i-1));
$DecimalTotal=$DecimalTotal + $NumericvalueofDigit;
}

echo $DecimalTotal;

?>

Friday, February 28, 2014

Conditional Logic in PHP

This week's post is a bit shorter, due to number of midterms that have demanded my attention away from learning PHP. However, I think that it would be at least helpful to share a few comments on conditional statements within PHP.

At the heart of conditional logic in PHP is the If statement
The logic behind the if statement in PHP matches that of most other languages. If this condition is met, then execute this  code.

The syntax is as follows:
if ($t<"10")
  {
  echo "Hello World!";
  }

In this particular IF statement, the  "Hello World" text will only be displayed if the variable t is less than 10.

If statements are sometimes supplemented with else and elseif clauses to help specify alternate routes of action when the "if" test is false.

if ($x=="10")
  {
  echo "Hello World!";
  }
elseif ($x=="20")
  {
  echo "How are you, World?";
  }
else
  {
  echo "Goodbye World!!";
  }

In this example, the text "Hello World!" will only be executed if x is equal to 10. If x is not equal to 10, but equal to 20, the text "How are you, World?" will be displayed. If x is not equal to 10 nor 20, the the text "Goodbye World" will be displayed.

What is interesting about the if statement in PHP is that it is absolutely identical to the if statement syntax in Java. So which language copied which? Both languages were debuted 19 years ago in 1995, so it is likely that both were in development around the same time. What is more likly is that both languages borrowed some syntax, including the if statement, from a common predecessor language like C or C#.