Monday, 26 August 2013

IF STATEMENTS IN PHP TUTORIAL 6

Conditional Logic uses the "IF" word a lot. For the most part, you use Conditional Logic to test what is inside of a variable. You can then makes decisions based on what is inside of the variable. As an example, think about the username again. You might have a variable like this:
$User_Name = "My_Regular_Visitor";
The text "My_Regular_Visitor" will then be stored inside of the variable called $User_Name. You would use some Conditional Logic to test whether or not the variable $User_Name really does contain one of your regular visitors. You want to ask:
"IF $User_Name is authentic, then let $User_Name have access to the site."
In PHP, you use the "IF" word like this:
if ($User_Name == "authentic") {
//Code to let user access the site here;
}
Without any checking, the if statement looks like this:
if ( ) {
}
You can see it more clearly, here. To test a variable or condition, you start with the word "if". You then have a pair of round brackets. You also need some more brackets - curly ones. These are just to the right of the letter "P" on your keyboard (Well, a UK keyboard, anyway). You need the left curly bracket first { and then the right curly bracket } at the end of your if statement. Get them the wrong way round, and PHP refuses to work. This will get you an error:
if ($User_Name = = "authentic") }
//Code to Let user access the site here;
{
And so will this:
if ($User_Name == "authentic") {
//Code to Let user access the site here;
{
The first one has the curly brackets the wrong way round (should be left then right), while the second one has two left curly brackets.
In between the two round brackets, you type the condition you want to test. In the example above, we're testing to see whether the variable called $User_Name has a value of "authentic":
($User_Name = = "authentic")
Again, you'll get an error if you don't get your round brackets right! So the syntax for the if statement is this:
if (Condition_or_Variable_to_test) {
//your code here;
}
In the next lesson, we'll use if statements to display an image on the page.
We'll use the print statement to "print out" HTML code. As an example, take the following HTML code to display an image:
<IMG SRC =VISHWA.jpg>
Just plain HTML. But you can put that code inside of the print statement:
print ("<IMG SRC =images/VISHWA.jpg>");
When you run the code, the image should display. Of course, you'll need an image called VISHWA.JPG, and in a folder called images.
You can find these amongst the files you can download for this course, in the folder called images.
Copy the images folder to your www (root) directory. Then try the following script:
<?PHP
print ("<IMG SRC =images/VISHWA.jpg>");
?>
Save your script to the same folder as the images folder 

No comments:

Post a Comment