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#.






Saturday, February 22, 2014

Numeric Functions

This week's post will take a closer look at numeric data types within PHP. Specifically, it will explore some of the built in operators and functions that are commonly used with each.

Numbers:

PHP supports all of the basic mathematical operations that are found within most other programming languages. Here are a few examples;

$q=5; 
$r=3;

-------

  • $z=$q * $r Multiplication
  • $z=$q / $r division
  • $z=$q + $r Addition
  • $z=$q - $r  subtraction
  • $z=$q % $r remainder calculation


These  calculations can be stored in a variable  for later printing/returning like in the examples above. Conveniently, PHP also allows you to directly print or return the results of the calculations:


  • echo ($x % $y); 



Interestingly enough, PHP also has quite an extensive mathematical library that can be used for more advanced calculations. Usually, when I think of a web based programming language, I don't associate it with programs that require advanced mathematical calculations. Here are a few examples of the more advanced operations;


  • $z=abs($z) Absolute Value
  • $z=sqrt($q) Square Root
  • $z=sin/cos/tan($q) Trig Functions
  • $z=ceil($q) round decimal up to nearest whole number
  • $z=floor($q) round decimal down to nearest whole number



Another interesting fact about  equations in PHP is that even the more advanced calculations are part of the PHP core library. From a user's perspective, this means that there is no importing needed. This is something that isn't often seen in other object oriented languages, as Very few of them include anything other than basic addition/subtraction/multiplication/division without importation.






Friday, February 14, 2014

Variables Part 2

In the last post, I talked about how to declare a variable in PHP. In this post, I will cover the differences between the three levels of variables in PHP.

In PHP, a given variable will exist on one of three levels:

1. Global
2. Local non static
3. Local static

1. Global Variables
If you have had experience with other programming languages before, then this might seem a bit familiar.
A global Variable is a variable that can be accesses and/or changed from every function in a particular PHP class.These variables are helpful if you need to reference the same stored value for a variety of different processes.

What is a bit different in PHP , is that Global Variables are only distinguished by their declaration location in the program. Unlike in many other languages, there is no "Global" modifier.
To ensure a variable is declared as Global, it must be declared before and outside of any functions in the program.

<?php

$X=the global variable
function LearnPHP1()
{

echo "I can see " + $X;

}


function LearnPHP2()
{
echo "I can also see " + $X;
}

>


2.Non-Static Local Variables
 A Local non-static variable have two key properties that distinguish it: itcan only be accessed and modified within the function it is defined, and any changes made to the value of the variable are discarded after the 
function  it is in  has finished executing.

A variable is declared as local if it is declared within a specific function. All local variables are considered to be non-static by default-  so it is not necessary to specify it.

<?php

function LearnPHP()
{
$X=0;
echo $X;
$X++;
}


LearnPHP();
LearnPHP();

>


Even though LearnPHP is called twice, the changes to $X from the first call are not carried over to the second call.

At the end of the second call to LearnPHP();, $X only equals 1.



3. Static Local Variables
A local static variable can only be accessed within the function it is defined, but  changes made to the value of the variable are not discarded- all changes to it carry over for the next times the function is called.

A local variable can be declared as static with the "static" modifier upon deceleration

Example:


<?php

function LearnPHP()
{
static $X=0;
echo $x;
$x++;
}


LearnPHP();
LearnPHP();

>

Since $X is declared as static, the changes made to $X in the first call of LearnPHP are carried into the second call. At the end of the second call, the value of $X is 2.


Variables Part 1

PHP and Variables

Like any programming language, PHP supports the use of variables to store data. However, there are several unique characteristics of PHP that should be remembered when working with them.

The syntax for creating variables in PHP:

  • $X=5;


1. All PHP variables must start with the '$' character.

 I agree that  it's kind of strange, but once I could see where a universal starting character would be helpful in easily identifying all variables in a program.

Examples

  • If you wanted a variable called X, you would have to create it as $X
  • If you wanted a variable called 'textstring' you would have to create it as $textstring



2. PHP is a loose language.

So you probably know that it many other programming languages declaring the type of information that a variable will hold is important. Not in PHP.  PHP automatically determines a variable's type based on the value that is first assigned.

Examples:

  • If you set your variable '$X' to equal 5, PHP will automatically store its data type as an integer.
  • If you set your variable '$textstring' to equal "Hello World", PHP will automatically store its data type as a string.


3. In PHP, declaring and assigning a value to a variable must happen in the same step.

In many other programming languages it is possible to declare a variable on one line, and then assign it its first value at another point in the program. Because PHP determines the variable type based off of the value given to it (see point 2), it is necessary that you give each variable a value during the declaration stage.

Example:

  • Allowed:  $X=5;
  • Not Allowed: $X;





Wednesday, January 29, 2014

My PHP told me to tell you "Hello World"

A few weeks ago I started exploring the PHP language. PHP stands for  PHP: Hypertext Preprocessor, and is usually used for server side programming. PHP is an open source language.

As I have started to familiarize myself with the language, I can't help but draw comparisons to Microsoft's Visual Basic language. Both languages specialize in server side web programming, and support many of the same functionalists. However, where PHP is open source, Visual Basic is Microsoft owned. Another key difference is the support of WYSIWYG design for Visual Basic, through Microsoft's Visual Studio software. This makes designing webpages in Visual Basic quick, and shortcuts a lot of the programming language and html integration. 

Unfortunately, I have not found such a program to aid in PHP design. In fact, I have found that it is common for most PHP programs to be written only in Notepad++, and then saved with the .PHP extension. Ultimately this will mean that I will have to become more familiar with manually  combining HTML and object oriented programming.


_____________________________________________________________________________

Here is a simple "Hello World" program in PHP.

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'?> 
 </body>
</html>


Here is a working link of it in action http://stuweb.jcu.edu/jfox14/hello.php

You can make your very own php  program by using notepad, and the .php extension when you go to save.