Banner

Sponsor

Login


Welcome Back!
Guest
Guest

Register

Lost your password?

77 users online



In Depth Tutorials [May 30, 2004]

In Depth Tutorials [May 30, 2004]

Currently viewing this thread: 1 (0 members and 1 guests)


Thread closed

Closed by Noel on August 24th, 2005 03:41 PM

Not discussion.

Page 1 out of 4
Adam

Adam

Status: Offline!

In Depth Tutorials [May 30, 2004]

Here is a thread dedicated to all the user written tutorials in this Forum. Each tutorial will be in another reply, with credit given to the apporite author. This will be locked to keep it clean and easy to read. If you've found another thread that should be added to the list pm me.

Edit by Noel: I've done my best to fix all of the problems with the BBcode (as well as some other minor typos) in the thread. If something doesn't work, please tell me. :D

Table of Contents

If you are having problems with the table stretch, scroll all the way to the right and/or increase your resolution.

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Noel, August 24th, 2005 03:41 PM (Edited 4 times)

Adam

Adam

Status: Offline!

Tutorial : Troubleshooting PHP Scripts

A part of most every PHP author's script making process is figuring out where you screwed up and fixing it. The way PHP handles errors makes this pretty easy by pointing out where the errors are. However, that doesn't always make it easy to solve Grin

Think your script is error free? Put error_reporting('E_ALL'): at the top of your script or change the php.ini setting to E_ALL. You may be suprised.

ERROR:

Quote:


Notice: Undefined variable: cdsonfig in E:\server\abb_PA1\adm\acp.php on line 10


An undefined variable means you are attempting to use or manipulate a variable that doesn't exist. To fix it, we look at the 'on line 10' part. When I check my PHP script (the actual script, not the output) I see this :

'CELL_ALT_A_COLOR' => $config['cellAColor'],

$cdsonfig should be $config. I change it and the error is solved. This type of error happens a lot if your going to a page thats expecting a get or post variable, and it isn't set. You can often solve it by doing this:

PHP:

<?php

if(isset($_GET['variable'])) {
// code
} else {
echo 
'Expected variable \'variable\' was not set.'
}

?>

ERROR:

Quote:


Fatal error: Call to a member function query() on a non-object in E:\server\abb_PA1\adm\acp.php on line 51

This means that if you are trying to use an object, it is not initialized. Make sure that you have something like

PHP:

<?php

$db 
= new dbClass;

?>


at the top of your script.

ERROR:

Quote:

Parse error: parse error, unexpected '>' in E:\server\log.php on line 7


Unexpected char usually means you forgot a ending ' or " somewhere in your script. If we look at the script, we see this:

PHP:

<?
$file 
file('log.html');

print 
'my dogs name is doggy;
// interpret
foreach($file as $name) {
    $name = str_replace('
<br>','',$name); #line 7
}


If we look up a few lines, we can see the error. When we were printing 'my dogs name is doggy' we didn't type the extra '. Changing that line to
print 'my dogs name is doggy';
and the problem is solved.

ERROR:

Quote:


Fatal error: Call to undefined function: add_slashes() in E:\server\log.php on line 4


This error means that the function we are trying to use doesn't exist. This happens often to a mispelling of the function (ie add_slashes instead of addslashes, mysql_qeury, etc) or if you wrote the function in a different file and didn't include it.

ERROR:

Quote:

Notice: Use of undefined constant Tom - assumed 'Tom' in E:\server\log.php on line 6


A lot of times this error is unnoticable if you suppress error reporting because in many cases it still does what you expect. Say we have this script :

PHP:

<?php

$nameNumber
['Tom'] = '730-3678';
$nameNumber['Jane'] = '533-7650';
print 
$nameNumber[Tom] . '<br />';

?>


When we did this:
$nameNumber[Tom]
PHP looked for a constant named 'Tom' and when it couldn't find it, it use the key Tom. This could be solved by doing this:
$nameNumber['Tom']

ERROR:

Quote:


Warning: Cannot modify header information - headers already sent by (output started at E:\server\log.php:6) in E:\server\log.php on line 7

This often happens when you try to start a session, send a cookie, or use header function. This is because all of these modify / change the headers of the page, and they cant be done if they are already set. Sessions are automatically sent when you send anything to the page - in this case I was using this script.

PHP:

<?
$file 
file('log.html');

$nameNumber['Tom'] = '730-3678';
$nameNumber['Jane'] = '533-7650';
print 
$nameNumber['Tom'] . '<br />';
header('Location: phpinfo.php');
#more code


We had already outputed Tom's number, from the earlier example. The header was actually sent on line 7 as indicated in the error. Theres a few ways we can fix this - way one is to rearrange the script so that the headers are above the text. This is almost ALWAYS possible but requires more work then solution two. At the very top if the script, put

PHP:

<?php

ob_start 
('ob_gzhandler');

?>


If your script is mixed html and php, you want to put this even before the <html> tag.

ERROR:

Quote:


Warning: main(usFederalDocuments.mcl): failed to open stream: No such file or directory in E:\server\log.php on line 8

Fatal error: main(): Failed opening required 'usFederalDocuments.mcl' (include_path='.;c:\php4\pear') in E:\server\log.php on line 8


OR

Quote:


Warning: main(usFederalDocuments.mcl): failed to open stream: No such file or directory in E:\server\log.php on line 8

Warning: main(): Failed opening 'usFederalDocuments.mcl' for inclusion (include_path='.;c:\php4\pear') in E:\server\log.php on line 8


The script used for this was:

PHP:

<?
$file 
file('log.html');

$nameNumber['Tom'] = '730-3678';
$nameNumber['Jane'] = '533-7650';
print 
$nameNumber['Tom'] . '<br />';

require 
'usFederalDocuments.mcl';
# more


Note that 'usFederalDocuments.mcl' doesn't exist. Anyways, we get the first error because PHP couldn't find the file we were attempting to search in the place we specified - in the script we specified the current directory we were in. We got the second one when PHP couldn't located the script in the default include path as set in your php.ini.

Now why did this cause a fatal error in the first quote and a second warning in the first? To be honest, I changed the script in between runs. In the first one, I used require, which sticks out a fatal error if it can't find the script. In the second, I use include which only puts out a warning.

ERROR:

Quote:


Warning: fopen(counter.txt) [function.fopen]: failed to create stream: Permission denied in /hsphere/local/home/martymcf/deathbyplane.martymcfly.net/beta2/pop.php on line 116


Alrite, so I stole this error and didn't write the script. We can solve it anyways Grin.

There are two possible reasons this error happened. Either the file doesn't exist or we don't have pemissions to use it. To check if the file exists, we could do

PHP:

<?php

$e 
file_exists('counter.txt') ? print 'File exists' : print 'File not found';

?>


That will tell us if the file exists or not. If it exists and we can't use it for permission reasons, we need to CHMOD it. Either use your ftp client or chmod() function, or telenet. Either way, 777 will do the job.

ERROR:

Quote:


Parse error: parse error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in E:\server\fe.php on line 5

This usually happens when you use an array an a quoted string because PHP gets confused as to what to do. The script we used was this:

PHP:

<?php
$nameNumber
['Tom'] = '730-3678';
$nameNumber['Jane'] = '533-7650';

print 
"Tom's phone number is $nameNumber['Tom']";
?>


To solve it we might do either of these :

PHP:

<?php
$nameNumber
['Tom'] = '730-3678';
$nameNumber['Jane'] = '533-7650';

print 
"Tom's phone number is " $nameNumber['Tom'];
print 
"Tom's phone number is  {$nameNumber['Tom']}";
print 
"Tom's phone number is  $nameNumber[Tom]";
?>

ERROR:

Quote:

Warning: mysql_connect(): Can't connect to MySQL server on 'localhost' (10061) in E:\server\fe.php on line 2
Can't connect to MySQL server on 'localhost' (10061)


First: If its MySQL ALWAYS add or die(mysql_error()). It will help you immensely.

This error means it can't even find the server - make sure mysql is running!.

ERROR:

Quote:

Warning: mysql_connect(): Access denied for user: 'root@localhost' (Using password: YES) in E:\server\fe.php on line 2
Access denied for user: 'root@localhost' (Using password: YES)

This means that your user/password combination is invalid. Double check them and make sure they are right.

ERROR:

Quote:


You have an error in your mysql query...


Thats a different topic then what this thread covers, but check out mysql.com and make sure your using the right syntax.

ERROR:

Quote:


Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/virtual/site228/fst/var/www/html/adminrate/p.php on line 9

This means the result your trying to give it to a) doesn't exist b-c) has 0 rows. This could be either because it worked and selected no querys pr because the script never executed. Again, remember
always mysql_query() or die(mysql_error());

Alright, thats as many errors I could make by trying to screw up my PHP scripts. If you know of any other NON LOGIC (those need to be troubleshooted on a per case basis) post them and I'll see what I can make of it. Usually I can fold them into swans, and airplanes, and triangles, and cups...

By Phil

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Noel, May 7th, 2005 10:00 PM (Edited 1 times)

Adam

Adam

Status: Offline!

Tutorial: OOP Coding in PHP (version 1.1)

I see many people talking about OOP. And some of them asked for a tutorial, and since I didnt found any using the search function, I though i could write one Wink

This is my second tutorial. And I assume here that you have basic knowledge of PHP.

[EDIT]: I added the timer class example and the description and usage of 'structures'

What is OOP and understanding it
OOP stands for Object-Oriented-Programming.
These objects are a regroupment of variables and functions (called properties and methods)

You must make the difference between classes and objects. Classes are the 'structures' and objects the instances of these structures. You can have a 'fruits' class, and create the 'apple', 'banana', 'lemon' and 'orange' objects from this class, each one having the same properties and methods. But acting indepently from each other

The first thing to do is to learn how OOP works. The easiest way is to compare it to real life objects (like I did with fruits). I'll take a bike as example here.

Our Bike class will have the properties 'num_speeds', 'speed', 'rotation' and 'running'. And the methods 'change_speed', 'pedal', 'brake' and 'turn'

You can then create as many bike objects as you wish, each one will act indepently. You can call the brake() method of an object while calling the pedal() method of another.

Creating a class and objects from it
A class' syntax is fairly simple. It's like creating a function. Except that you are using the 'class' keyword.
You define properties with the 'var' keyword followed by the property name. You use it the same way as you would use the 'global' keyword in a function.
Methods are defined the same way functions are.

let's build the skeleton of our bike class:

PHP:


<?php
class Bike
{
    var 
$num_speeds$speed;
    var 
$rotation;
    var 
$running FALSE// You can set default values for properties, these values must be constant

    // Change speed method
    
function change_speed$increment TRUE )
    {
        
// ...
    
}

    
// Pedal and brake methods
    
function pedal()
    {
         
// ...
    
}
    function 
brake()
    {
         
// ...
    
}

    
// Turn method
    
function turn$angle )
    {
        
// ...
    
}
}
?>

Now that our class is defined, we can create objects from it, using the 'new' keyword:
$my_bike_object = new Bike;
and then access this object's properties and methods using the '->' operator:
$my_bike_object->pedal();

Easier than you though isn't it?

Accessing properties and methods within the class
Within the class, you need to access properties and methods using the $this variable. It is a reference to the current object.
Let's use it to code our change_speed() method:

PHP:


<?php
// Inside the change_speed() method
if( !$this->running )
{
    return;
}

if( 
$increment && $this->speed != $this->num_speeds )
{
    
$this->speed++;
    return;
}

if( 
$this->speed != )
{
    
$this->speed--;
}
?>

Using $this also make it easier to separate local variables from properties.

Constructors and Destructors
These are special methods that are automatically called when an object is created or destroyed.
Constructors are methods that have the same name than the class. While PHP doesn't supports Destructors, there is a simple workaround for this.

Here we'll add a constructor and destructor to our Bike Class

PHP:

<?php

<php
// Inside the class
function Bike$num_speeds )
{
    
$this->num_speeds $num_speeds// Set the number of speed of this bike

    // Simple workaround for destructors
    
register_shutdown_function( array( &$this'destructor' ) );
}

// Our destructor
function destructor()
{
    
// Simply stop the bike
    
$this->brake();
}

// This will automatically call the constructor:
$bike = new Bike15 );

// The destructor will be called when the script execution will end
?>

?>

Note how I used an array as the parameter of register_shutdown_function(), that is how you send method names to functions that wants functions names

Also note that neither constructors nor destructors can return a value.

The :: operator
This operator is used to access class members without any object of this class. You use it like this:

PHP:


<?php
class Foobar
{
    function 
foo()
    {
        echo 
'I am foo!';
        
Foobar::bar();
    }

    function 
bar()
    {
        echo 
'I am bar!';
    }
}

// Call the bar method without creating any objects!
Foobar::foo();
?>

This have some limitations though.. you can't use the $this variable in this function. Which means you can't access classes properties.

You can still access other members using the same :: operator.

That covers the basics of OOP.
Now we'll get into the last part of this tutorial, using derived classes.

Derived classes
These classes use another class as a base. They get all the base class properties and methods.

A good example is humans.. we can have our human base class, and created the derived classes Men and Women from it

Let's code that:

PHP:

<?php

// Base class
class Human
{
    var 
$age;

    function 
Human$age )
    {
        
$this->age $age;
    }
}

// Men class
class Men extends Human // Note the extends keyword here
{
    function 
earn_money()
    {
        
// ...
    
}
}

// Women class
class Women extends Human
{
    function 
spend_money()
    {
        
// Yeah I know the joke isnt funny Tongue
    
}
}

// We can create objects of the three classes
$human = new Human10 );
$men = new Men25 );
$women = new Women32 );

?>

Notice how I created the objects of Men and Women using Human's constructor. Derived classes use their base class' constructor unless they have their own ones. If you have a constructor in your derived class and want to use the one of the base class too, you have to call it yourself in the derived class' constructor.

Overwriting methods and calling base class methods
You can overwrite a method of the base class by defining a method with the same name in the derived class.
You can still call the base class' method, which brings me to the next point of this section:

The 'parent' keyword is used to point to the base class.
in our last example, we could call the base class' constructor using:
parent::Human( $age );

you could also use the $this variable, since the derived class object contains all the base class methods and properties, but I personally prefer the parent:: way, it is easier to see that Human is a method of the base class.

Serializing objects
You can serialize objects as you would do with arrays. Only the class type and the properties values are stored.
The class definition also need to be present when unserializing the object.

You can use the __sleep() and __wakeup() methods with serialize() and unserialize()
When you serialize an object, php looks if this object have a __sleep() method and executes it. The same is done with unserialize and __wakeup.

__sleep should return an array of the properties names that you want to serialize, so you can only serialize a part of the object

basically you would want __sleep() to clean everything before serializing and/or serializing only a part of the object. and __wakeup() to recreate the data that was cleaned (database connection, reopenning files, etc) and/or check if the unserialized data is valid.

here is a simple script using serializing:

PHP:


<?php
class Foo
{
    var 
$was_serialized FALSE;
    var 
$bar 0;

    function 
__sleep()
    {
        
$this->bar 1;

        return array( 
'bar' ); // Only serialize the bar property
    
}

    function 
__wakeup()
    {
        
$this->was_serialized TRUE;

        if( 
$this->bar != )
        {
            echo 
'Invalid serialized data!';
        }
    }
}

$Foo = new Foo;

//serialize this object
$serialized serialize$Foo );

//unserialize it
$Foo unserialize$serialized );
?>

This is great when you have your custom session class and want to save the session data in a cookie, but not every class properties, and check if that data is still valid when unserializing it

OOP in work
Now it's time to get what you learnt to practice!
I'll use a simple timer class here, it will be useful for many people here!

so here goes the class definition:

PHP:


<?php
class Timer
{
    var 
$precision;
    var 
$start_mt;
    var 
$is_started FALSE;
    var 
$total_time 0;

    function 
Timer$precision 4$start TRUE )
    {
        
$this->precision $precision;

        if( 
$start )
        {
            
$this->start();
        }
    }

    function 
start()
    {
        if( 
$this->is_started )
        {
            return;
        }

        
$mtime explode' 'microtime() );
        
$this->start_mt $mtime[0] + $mtime[1];

        
$this->is_started TRUE;
    }

    function 
stop()
    {
        if( !
$this->is_started )
        {
            return;
        }

        
$mtime explode' 'microtime() );
        
$end_mt $mtime[0] + $mtime[1];

        
$this->total_time += ( $end_mt $this->start_mt );
    }

    function 
get_time()
    {
        return 
round$this->total_time$this->precision );
    }
}
?>

I didn't commented the class, i'm sure you will be able to understand how it works.

Now let's use our timer class to time different events:

PHP:


<?php
$php_timer 
= new Timer();
$sql_timer = new TimerFALSE);
$tpl_timer = new TimerFALSE);

// ...

$sql_timer->start();
// some queries here...
$sql_timer->stop();

// ...

$tpl_timer->start();
// compiling some templates...
$tpl_timer->stop();

// ...

$php_timer->stop();

echo 
'Page created in ' $php_timer->get_time() . 'seconds ( SQL: ' 
$sql_timer->get_time 'seconds, Templates: ' 
$tpl_timer->get_time() . 'seconds )';
?>

See how I created 3 objects from the same class and used them to time different things?
This is the point of OOP. If you got it this far, congratulations! You now know how to code, use and understand OOP!

Structures
Before I finish the tutorial, i'd like to talk about structure.
These are not considered OOP but simply a regroupment of variables.
So a structure is a class without any methods. What is the use of this you may ask? It's simple, check the following example:

PHP:


<?php
// We call this class a structure, because it doesn't have any members
// We'll use this structure to store the options data of a poll
class poll_option
{
    var 
$text;
    var 
$vote_text;
    var 
$num_votes;
}

// Now we can use this structure to store our poll options:
$options = array();
$i = -1;
while( 
$row mysql_fetch_assoc$result ) )
{
    
$options[--$i] = new poll_option// the structure object is created the same way

    // We then assign values to the structures values
    
$options[$i]->text $row['text'];
    
$options[$i]->vote_text $row['vote_text'];
    
$options[$i]->num_votes $row['num_votes'];
}
?>

This is the use of structures, you could still do the same thing with arrays, but I personally prefer this way.

*****

That closes this tutorial. I hope you enjoyed it!

Comments and questions are welcome!

EvilGenius

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Adam, July 23rd, 2003 04:30 PM (Edited 1 times)

Adam

Adam

Status: Offline!

MySQL/phpMyAdmin Access Denied Fix

Time to dedicate a thread to fixing these problems. This thread is meant to address the problem of :

Access Denied: root@127.0.0.1
UsingPassword(YES)

First step is to make sure your mysql server is started. In windows, bring up the Run dialog and type
net stop mysql [ENTER]
net start mysql [ENTER]

Ok, test you login information. Open up your command prompt, and navigate to your mysql/bin dir, if it were C:\mysql\bin. you would do:
c: [ENTER]
cd mysql\bin [ENTER]
mysqlshow [ENTER]

You should see to databases, test and mysql. Now type:
mysqlshow -uUSERNAMEHERE -p mysql [ENTER]
Then enter your password, if it is correct you should see some table listing and what not. If that works you just have the wrong information in your phpmyadmin config.php file. Set the information in that file to what you entered in thes steps above.

IF THAT DID NOT WORK

    [*]Make sure you have the correct information [*]Try one of the next to fixes

Fix1
Get to your mysql\bin directory and type this in, via command prompt:
mysql -u root mysql [ENTER]
use mysql; [ENTER]
UPDATE user SET Password=PASSWORD('mynewpassword') WHERE User='root'; [ENTER]
LUSH PRIVILEGES; [ENTER]
Now restart your server using the net start and stop commands like I already went over. Test your infomation through the mysql show method I disscussed earlier also.

Fix2
Locate your hostname.pid file and delete it.
Open up your mysql\bin dir and type
mysqadmin -uroot password 'mynewpasswordhere';

Now either restart your server via the net start stop commands or by using
mysqladmin -h hostname flush-privileges
[ENTER]
Now test your information again, if the problem still precedes, contact me.

MISC Fixes
I've heard restarting your server works sometimes too. If you have downloaded and installed MySQL 4.xxx for windows and set up your root password via phpmyadmin through windows, not command line, it may have lost your root password, as it did for me. I fixed this problem via Fix1 If you look at your my.ini file it also has values for root user name and password, you could try to change those values and restart your server.

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Adam

Adam

Status: Offline!

Learning PHP: volumes 1, 2, & 3

Learning PHP: volume 1
You can use any style of programming with PHP, but some things work better than others - I will try to hit all the quirks in this section.

Syntax
You can insert PHP in to a HTML file by typing the first line of code shown here. The second line shows a one-line PHP script that includes a print statement; lines three through six show a multiple-line PHP script:

PHP:

<?php ?>

<?php print("Sup"); ?>

<?php
$message 
"Sup";
print(
$message);
?>

<?php starts PHP code. You can start it anywhere in a HTML page and the code is XML compatible, so always use the syntax <?php. You can also use things like <?, but that does not work with XML. ?> ends the PHP code.

When you include a PHP file within a PHP file, PHP starts reading the included file as HTML, so be sure to start the included file with <?php to get straight into PHP.

Every statement ends with a semicolon, ;, and statement blocks are surrounded with braces, { }, as in:

PHP:

<?php

if("a" == "a") {
    print(
"true");
}

?>

You can leave out the semicolon and braces in certain circumstances, but it makes code hard to understand and leads to mistakes when you modify code.

You can add a commend to the end of a line with // as in:

PHP:

<?php

print("true");  // This is a comment.

?>

You can add blocks of comments with /* and */ as in:

PHP:

<?php

/* This is a pretty long
comment don't you think?
This can go as far as you want
til you add this -> */

?>

Variables are created by adding $ to the front of a name, and a variable name is case-sensitive. When you add the following two lines to your code, you can print out $a and get the value assigned to $a, not the value assigned to $A:

PHP:

<?php

$a 
"the contents here";
$A "different contents here";

?>

Numeric variables do not require quotes. If you use quotes, the variable will be stored as a string, but will be converted to a number when needed as a number.

PHP:

<?php

$a 
20;

?>

You can also use names defining logical values, including the following:

PHP:

<?php

$a 
null;
$b true;
$c false;

?>

If, Then, Else
PHP automatically converts between data types, so testing data become more important. Consider the following sections of code:

PHP:

<?php

if($a == 0) {
    
//do this
}
if(
$a == 1) {
    
//do this
}

?>

In a language with strong typing and a binary field, the code will work perfectly because $a can contain only 0 or 1, and the code has an action for each value. The following code also works for that type of language:

PHP:

<?php

if($a == 0) {
    
// do this
} else {
    
// do this
}

?>

What if another programmer comes along and defines the type as integer? The test using if else will most likely work as intended, because any value over 1 will work as 1. The code using the two if statements will not work, because it will ignore any value greater than 1. What if the same programmer uses a negative number; should -1 be treated like +1 or as a special case? Of there is no logical else, *** a warning message, like this:

PHP:

<?php

if($a == 0) {
    
// do this
} elseif($a == 1) {
    
// do this
} else {
    print(
"Warning message");;
}

?>

PHP is more liberal with data types, and PHP 4 add the === comparison to let you check values by type; but you still cannot lock in data types, so you have to be careful when interpreting data. Here is an attempt at defining all the possibilities for what you might think is a simple binary field:

PHP:

<?php

if(!isset($a)) {
     
// some sort of warning
} elseif($a === false) {
    
// do this
} elseif($a === true) {
    
// do this
} elseif($a == 0) {
    
// do this
} elseif($a 0) {
    
// do this
} else {
    
// do this
}

?>

First, you have to check that a field exists, because PHP replaces missing fields with a variable of the same name. The next test is to check if a firls is true or false. You have to replace == with ===, because == lets PHP convert numeric and string fields to true or false, whereas === checks that the field is the correct type in the first place.

By ProQ

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Noel, May 7th, 2005 10:02 PM (Edited 1 times)

Adam

Adam

Status: Offline!

Learning PHP Volume 2 & 3

Learning PHP: volume 2
Data is the foundation of your program. If you define your data the wrong way. the program will run, but it will produce the wrong results, which can be absolutely frustrating. PHP has an automatic type conversion that can increase the difficulty of diagnosing problems. Fortunately, PHP4 contributes an extra level of functionality to help you easily test data.

Data Types
PHP lets you define data as strings, integers, floating-point numbers, logical values, and compound mixtures of types. It also provides two sets of special mathematical functions to handle complex math. Here is a simple string:

PHP:

<?php

$a 
"whatever string";

?>

In the section that follows, you will see how to control data types, which PHP does automatically. In the next tutorial, you will see how to compare and change data.

You will find PHP counting from zero in strings, arrays, and all sorts of functions, so the fifth element of an array is [4]:

PHP:

<?php

$fifth 
$a[4];

?>

If you get unusual results with PHP data, check all indexes and references, such as the starting character number in the function substr(), in case you counted from 1 where you should have used 0.

Variables
$a is a variable because you can change its value at any time. Constants cannot be changed, and you cannot change a variable in a different scope. Both those conditions ar described late in the tutorial.

Variables have a defined type, such as integer or string; but PHP automatically changes the type when needed, so you can get unexpected results if you make assumptions about a variable's type. A string containing zero characters, as shown in the first line of the following example code, is a string, but can be converted to null, false, or zero. A string containing one character, the number 0, as shown in the second line, can be converted automatically to the value zero, and the value zero can be converted to null or false:

PHP:

<?php

$a 
"";
$b "0";

?>

When the data type is important, you have to replace the == operator with the === operator, or use a type-testing function like is_integer(), all of which are described in the following sections. All variabes have a case-sensitive name, which means the variable $proq is different from the variable named $Proq, and both are different from the variable named $ProQ.

Variables have a maximum length, but that length is almost unlimited for a string, and anything else can be converted to a string, thus giving you a length from the string representation. If you are working with numbers and storing the numbers in databases, you will find that the length indicated by a PHP function does not help you work out the space the number will occupy in a database on disk.

Automatic Creation
PHP automatically creates missing variables. In the following code example, the variable name is typed as $metre in the variable definition line, and then as $meter in the print() statement. By default, PHP will create an empty variable $meter for the print statement:

PHP:

<?php

$metre 
35;
print(
$meter);

?>

The isset() function tests if a variable exists, and the unset() function removes a variable completely. unset() might be used in situations where your code uses isset() to check if a variable exists. Be careful about using unset() to indicate a special value, because another person may not use isset() as much as you do.

Constants
A constant gets defined once when you type:

PHP:

<?php

define
("a""whatever string");

?>

The define command creates a constant with the name provided in the first parameter and gives the constant the value from the second parameter. In the previous code example, constant a has the value whatever string.

The define command can be used anywhere, and the defined constants have a global scope so your constants are useable inside functions and all sorts of places where variables do not reach. The define command accepts simple data definitions, so it does not handle complex data structures like objects. You could use define to store a name, use the name when you create an object, and then use the defined name to reference the object indirectly, but the resulting application will fry the brain of the next programmer.

Scope
Scope defines where your data is visible. Data defined outside of functions is not visible within functions, and data within functions is not visible outside of functions. This means you can write a function almost independently of the surrounding code. The scope of individual data representations does vary and can be changed: Defined constants cross function boundaries, and ordinary variables can be allowed to cross into a function, if the function has the variables defined as global.

Because PHP automatically creates missing variables, you can be easily confused by variables that are empty when you know they contain data. If you create variable $whiskey in your main code, and then refer to $whisky with a function, $whisky will be empty. You will be confused, and if you are panicking while fixing a broken production application, you will probably be in need of a stiff drink.

By ProQ

Learning PHP: volume 3
PHP offers many expressions, operators, control and structure, functions, classes, and objects, and ways of handling data for databases and HTML.

Expressions
Everything in PHP is an expression. Type your age on a line by itself, and you have an expression with your age as the value. Expand the line to "$age = X;" (X being your age) and you have three expressions with your age as the value: your age; $age, which is now set to your age; and the statement as a whole. The following line will print your age because the print() function prints the value of the expression, and the value of the expression is effectively the value assigned to the left hand side of the expression:

PHP:

<?php

print($age 20);  // 20 being the age

?>

PHP allows multiple equal signs and evalues them from right to left. In the following example, $age is set to 20, then $number is set to 20, and then 20 is returned to the print() statement and printed:

PHP:

<?php

print($number $age 29);

?>

You can slo use the value of an expression in control functions, such as if(), as shown next. Although this example is trivial, you can use the feature by wrapping if() and while() control functions around file and database functions, graphics functions -- and almost every other function -- to control the flow of processing based on what is returned from a function:

PHP:

<?php

if($age 20) {
    print(
"Age is true");
}

?>

The next example uses mysql_fetch_row() to read a row of data produced by an SQL query on a MySQL database. mysql_fetch_row() returns data until the rows run out, and then it returns false. When false is assigned to $row, false also becomes the value of the whole expression ($row = mysql_fetch_row($query_result)), so false is the value passed to while(). The while() loop loops back to the expression until the expression turns false, and then drops through to the rest of the program. In you program, you would have more than the example print statement within the loop; you would have code to process $row:

PHP:

<?php

while($row mysql_fetch_row($query_result)) {
    print(
"Another tow from the SQL query");
}

?>

PHP goes to extraordinary lengths to evaluate expressions in useful ways. In a future tutorial on arrays, you will see the following while() structure used to step through arrays. each() returns an element of an array, steps to the next element, and returns false when it hits the end of the array. list() splits the element into key and value, and returns true. While each() is feeding data to list(), while() interprets the expression as true and continues looping. When each() passes false to list(), list() passes false to while(), and the while() loop ends:

PHP:

<?php

while(list($key$value) = each($array))

?>

Early PHP functions did strange things to indicate the end of a process, but PHP functions now almost universally return false at the end of the data, or on encountering an error. That means expressions can differentiate between instances where a function works and returns no data versus instances where a function fails. PHP4's new === operator, explained in the next section, is crucial to handling expressions and functions.

Expressions are mixtures of variables, values, and operators, so there is little more I can tell you without including operators. If you know Perl, you already know enough to make the right guess most of the time and become really frustrated at other times because PHP picks the best out of Perl without picking up all the arcane tricks and traps of it. Some of your favorite tricks may not work, but the majority that do work are the ones understandable by mere humans.

Operators
Start memorizing =, ==, ===, !=, !==, +=, .=, +, -, *, /, $, &, and all the other characters on the keyboard that require strange hand movements. They are your PHP operators. 'http://www.php.net/manual/en/language.operators.php' is a chapter in PHP's official documentation all about PHP operators. Go through it to get acquainted with them because they are very important.

By ProQ

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Noel, May 7th, 2005 10:03 PM (Edited 2 times)

Adam

Adam

Status: Offline!

Learning PHP Volume 4

Learning PHP: volume 4
This tutorial covers all the statements you use to control the flow through your script, including making decisions with if(), else, and elseif(), and then talks about an alternative syntax. The switch() statement can be a great replacement for long sets of if() statements and is similar to the select statement availbable in other languages. The while() and for() statements let you loop through code based on certain conditions and seem to work like while() and for() in other languages.

The include() and require() statements let you include code from other files, and both work like their equivalents in C. There are a couple of traps to be aware of when using them in PHP, and the new require_once() and include_once() statements help to recude the common problem of including files more than once.

if()
Coding with if() in PHP is similar to coding with if() in other languages. This section will describe the shortcuts for coding with if() in PHP, plus show you some traps to avoid. The next example is a short piece of code to test the value of $a and print "ok" if $a is greater than zero: