goweb99 adds another satisfied client – Edward Sayfie – http://lakemichigancottagerental.com

Posted by admin | Posted in GoWeb99, Testimonials | Posted on 31-12-2009-05-2008

0

We use this service for the first time and were not sure what to expect. We are happy to report that they are very professional in every aspect of web design. We had a gentleman by the name of Tony Walker who did our design, he was in contact with us often, and made changes for us to our satisfaction. Very pleased with the work, and staff from Go Web 99. A special thanks to Tony Walker.
Edward Sayfie – http://lakemichigancottagerental.com

Mr. M R Malik http://awesomepizza.ca likes website designed by goweb99

Posted by admin | Posted in GoWeb99, Testimonials | Posted on 24-12-2009-05-2008

0

Go Web 99 values customer satisfaction and they are very true to their word. The technicians are honest and very hard working. Tony Walker, our support technician was very responsible and prompt with any changes I had wanted to make to our website. They consulted us with every little detail, and made sure that it was exactly what we wanted. I would recommend GoWeb99 to anyone who wants an organized and professional website that is wallet friendly. We were so pleased with them that we are currently working on our second website with them. Thank-you Go Web 99 for the hard work you have put in to our website, and keep up the good work!
Mr. M R Malik – http://awesomepizza.ca

An XML File

Posted by tutor | Posted in PHP Tutorial | Posted on 22-12-2009-05-2008

0

An XML file looks like this:

    <?xml version=”1.0″ encoding=”ISO-8859-1″?>
    <message>
    <sentto>Tutor</sentto>
    <sentby>Goweb99</sentby>
    <subject>Tutorial</subject>
    <content>This is a good tutorial!</content>
    </message>

Initializing the XML Parser

We need to first initialize the XML parser in PHP, then define some handlers for different XML events, and then parse the XML file.

    For eg:

    <?php
    //Initialize the XML parser
    $parser=xml_parser_create();
    //Function to use at the start of an element
    function start($parser,$element_name,$element_attrs)
    {
    switch($element_name)
    {
    case “MESSAGE”:
    echo “…………Message………….<br />”;
    break;
    case “SENTTO”:
    echo “Meant for: “;
    break;
    case “SENTBY”:
    echo “Msg From: “;

    break;
    case “SUBJECT”:
    echo “Subject: “;
    break;
    case “CONTENT”:
    echo “Message: “;
    }
    }
    //Function to use at the end of an element
    function stop($parser,$element_name)
    {
    echo “<br />”;
    }
    //Function to use when finding character data
    function char($parser,$data)
    {
    echo $data;
    }
    //Specify element handler
    xml_set_element_handler($parser,”start”,”stop”);
    //Specify data handler
    xml_set_character_data_handler($parser,”char”);
    //Open XML file
    $fp=fopen(”sample.xml”,”r”);
    //Read data
    while ($data=fread($filePointer,4096))
    {
    xml_parse($parser,$data,feof($filePointer)) or
    die (sprintf(”XML Error: %s at line %d”,
    xml_error_string(xml_get_error_code($parser)),
    xml_get_current_line_number($parser)));
    }
    //Free the XML parser
    xml_parser_free($parser);
    ?>

    Output:

    –Message–
    Meant for:Tutor
    Msg From:Goweb99
    Subject: Tutorial
    Message: This is a good tutorial!

The above example works as:

  • Initialize the XML parser with the xml_parser_create() function
  • Create functions to use with the different event handlers
  • Add the xml_set_element_handler() function to specify which function will be executed when the parser encounters the opening and closing tags
  • Add the xml_set_character_data_handler() function to specify which function will execute when the parser encounters character data
  • Parse the file “test.xml” with the xml_parse() function
  • In case of an error, add xml_error_string() function to convert an XML error to a textual description
  • Call the xml_parser_free() function to release the memory allocated with the xml_parser_create() function

Trish Chipchura http://bclakeshoremanor.com recommends goweb99

Posted by admin | Posted in GoWeb99, Marketing of your Vacation Rentals, RM e-Services, Testimonials | Posted on 21-12-2009-05-2008

0

I LOVE the look of my new website!!! The group at Goweb99 are amazing! They came through with everything they promised. Tony worked with me to get the look and function of the site I wanted. I really appreciated his attention to calling promptly when he promised and being patient with me. I think the value for what you get from goweb99 is affordable and the service is great.
Trish Chipchura – http://bclakeshoremanor.com

XML & EXPAT

Posted by tutor | Posted in PHP Tutorial | Posted on 19-12-2009-05-2008

0

XML

XML is used to describe data. It focuses on what the data is. An XML file describes the structure of the data.

In XML, no tags are predefined. You must define your own tags.

PHP can process XML files with the help of built-in XML Expat Parser.

Expat

To do the manipulation with a file we need to understand it, this is the work of a parser. Similarly to create, read, update and do other manipulations an XML document, you will need an XML parser.

There are two basic types of XML parsers:

  • Tree-based parser: This parser transforms an XML document into a tree structure. It analyzes the whole document, and provides access to the tree elements. e.g. the Document Object Model (DOM)
  • Event-based parser: Views an XML document as a series of events. When a specific event occurs, it calls a function to handle it. For e.g. the Expat XML parser

Event-based parsers focus on the content of the XML documents, not their structure. Because of this, event-based parsers can access data faster than tree-based parsers.

    For eg:

    <sent>Data</sent>

An event-based parser reports the XML above as a series of three events:

  • Start element: sent
  • Start CDATA section, value: Data
  • Close element: from

The XML example above contains well-formed XML. However, the example is not valid XML, because there is no Document Type Definition (DTD) associated with it.

However, this makes no difference when using the Expat parser. Expat is a non-validating parser, and ignores any DTDs.

As an event-based, non-validating XML parser, Expat is fast and small, and a perfect match for PHP web applications.

Note: XML documents must be well-formed or Expat will generate an error.

PHP Database ODBC

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

ODBC is an Application Programming Interface (API) that allows you to connect to a data source like an MS Access database.

    ODBC stands for Open DataBase Connectivity

With an ODBC connection, you can connect to any database even if it on some other computer in your network, as long as an ODBC connection is available.

Here is how to create an ODBC connection to a MS Access Database:

  • Open the Administrative Tools icon in your Control Panel.
  • Double-click on the Data Sources (ODBC) icon inside.
  • Choose the System DSN tab.
  • Click on Add in the System DSN tab.
  • Select the Microsoft Access Driver. Click Finish.
  • In the next screen, click Select to locate the database.
  • Give the database a Data Source Name (DSN).
  • Click OK.

Note that this configuration has to be done on the computer where your web site is located. If you are running Internet Information Server (IIS) on your own computer, the instructions above will work, but if your web site is located on a remote server, you have to have physical access to that server, or ask your web host to to set up a DSN for you to use.

Connecting to an ODBC

The odbc_connect() function is used to connect to an ODBC data source. The function takes four parameters: the data source name, username, password, and an optional cursor type.

In this case, the odbc_exec() function is used to execute an SQL statement.

    For eg:

    $conn=odbc_connect(’northwind’,”,”);
    $sql=”SELECT * FROM customers”;
    $rs=odbc_exec($conn,$sql);

Retrieving Records

The odbc_fetch_row() function is used to return records from a result-set. This function returns true if it is able to return rows, otherwise false.

The function takes two parameters: the ODBC result identifier and an optional row number:

    Odbc_fetch_row($rs)

Retrieving Fields from a Record

The odbc_result() function is used to read fields from a record.

This function takes two parameters: the ODBC result identifier and a field number or name.

The code line below returns the value of the first field from the record:

    $compname=odbc_result($rs,1);

The code line below returns the value of a field called “CompanyName”:

    $compname=odbc_result($rs,”CompanyName”);

Closing an ODBC Connection

The odbc_close() function is used to close an ODBC connection.

    Odbc_close($conn);

The following example shows how to first create a database connection, then a result-set, and then display the data in an HTML table.

    <html>
    <body>
    <?php
    $conn=odbc_connect(’northwind’,”,”);
    if (!$conn)
    {exit(”Connection Failed: ” . $conn);}
    $sql=”SELECT * FROM customers”;
    $rs=odbc_exec($conn,$sql);
    if (!$rs)
    {exit(”Error in SQL”);}
    echo “<table><tr>”;
    echo “<th>Companyname</th>”;
    echo “<th>Contactname</th></tr>”;
    while (odbc_fetch_row($rs))
    {
    $compname=odbc_result($rs,”CompanyName”);
    $conname=odbc_result($rs,”ContactName”);
    echo “<tr><td>$compname</td>”;
    echo “<td>$conname</td></tr>”;
    }
    odbc_close($conn);
    echo “</table>”;
    ?>
    </body>
    </html>

PHP MySQL Delete

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

You can delete records by using the DELETE statement.

Syntax

    DELETE FROM table_name
    WHERE some_column = some_value

Again we used WHERE clause here in the DELETE syntax. The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted.

    For eg:

    Country Capital
    Zimbabwe Harare
    Poland Warsaw

    <?php
    $conn = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    mysql_select_db(”my_db”, $conn);
    mysql_query(”DELETE FROM Country WHERE Capital=’Warsaw’”);
    mysql_close($conn);
    ?>

After the deletion, the table will look like this:

    Country Capital
    Zimbabwe Harare

PHP MySQL Update

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

The UPDATE statement is used to update existing records of a table in a database.

Syntax

    UPDATE table_name
    SET column1=value, column2=value2,…
    WHERE some_column=some_value

WHERE clause is included in the update statement to conditionally update the records. It specifies which record or records should be updated. If there is no WHERE clause, all records will be updated.

    For eg:

    Zimbabwe Harare
    Poland Warsaw

The following example updates some data in the “Country” table:

    <?php
    $con = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    mysql_select_db(”my_db”, $con);
    mysql_query(”UPDATE Country SET Capital = ‘Poland’
    WHERE FirstName = ‘Poland’”);
    mysql_close($conn);
    ?>

After the update, the “Country” table will look like this:

    Country Capital
    Zimbabwe Harare
    Poland Poland

PHP MySQL Order By

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

The ORDER BY is a keyword which is used to arrange or sort the data in a recordset.

If  you will not specify in which order to arrange the result, ORDER BY will arrange them in ascending order by default.

If you want to sort the records in a descending order, you can use the DESC keyword.

Syntax

    SELECT column_name(s)
    FROM table_name
    ORDER BY column_name(s) ASC|DESC
    For eg:

    <?php
    $conn = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    mysql_select_db(”my_db”, $conn);
    $result = mysql_query(”SELECT * FROM Country ORDER BY Country”);
    while($row = mysql_fetch_array($result))
    {
    echo $row['Country'];
    echo ” ” . $row['Capital'];
    echo “<br />”;
    }
    mysql_close($conn);
    ?>

    Output:

    Poland Warsaw
    Zimbabwe Harare

Order by Two Columns

It is also possible to order by more than one column. When ordering by more than one column, the second column is only used if the values in the first column are same:

    SELECT column_name(s)
    FROM table_name
    ORDER BY column1, column2

PHP MySQL The Where Clause

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

WHERE clause is used to filter records, on the basis of some conditions.

Syntax

    SELECT column_name(s)
    FROM table_name
    WHERE column_name operator value

The following example selects all rows from the “Country” table where Country=’Poland’.

    For eg:

    <?php
    $conn = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    mysql_select_db(”my_db”, $conn);
    $result = mysql_query(”SELECT * FROM Country
    WHERE Country=’Poland’”);
    while($row = mysql_fetch_array($result))
    {
    echo $row['Country'] . ” ” . $row['Capital'];
    echo “<br />”;
    }
    ?>

    Output:

    Poland Warsaw

PHP MySQL Select

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

The SELECT statement is used to select data from a database, based on some conditions or all of the data.

Syntax

    SELECT column_name(s)
    FROM table_name

The following example selects all the data stored in the “Country” table.A * character selects all the data in the table.

    For eg:

    <?php
    $conn = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    mysql_select_db(”my_db”, $conn);
    $result = mysql_query(”SELECT * FROM Persons”);
    while($row = mysql_fetch_array($result))
    {
    echo $row['Country'] . ” ” . $row['Capital'];
    echo “<br />”;
    }
    mysql_close($conn);
    ?>

The example above stores the data returned by the mysql_query() function in the $result variable.

Next, we use the mysql_fetch_array() function to return the first row from the recordset as an array. Each call to mysql_fetch_array() returns the next row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable.

    Output:

    Zimbabwe Harare
    Poland Warsaw

Display the Result in an HTML Table

The following example selects the same data as the example above, but will display the data in an HTML table:

    <?php
    $conn= mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$con)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    mysql_select_db(”my_db”, $conn);
    $result = mysql_query(”SELECT * FROM Country”);
    echo “<table border=’1′>
    <tr>
    <th>Country</th>
    <th>Capital</th>
    </tr>”;
    while($row = mysql_fetch_array($result))
    {
    echo “<tr>”;
    echo “<td>” . $row['Country'] . “</td>”;
    echo “<td>” . $row['Capital'] . “</td>”;
    echo “</tr>”;
    }
    echo “</table>”;
    mysql_close($con);
    ?>
    Output:

    Firstname Lastname
    Zimbabwe Harare
    Poland Warsaw

Inserting Data From a PHP Form

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

The most interesting part of a web application is that you can use dayabase to fill the form data and vice versa. This is the most useful part also, as it increases the user interactivity and helps is realizing many functions like filling up a form online.

    For eg:

    <html>
    <body>
    <form action=”insert.php” method=”post”>
    Country: <input type=”text” name=”country” />
    Capital: <input type=”text” name=”capital” />
    <input type=”submit” />
    </form>
    </body>
    </html>

When a user clicks the submit button in the HTML form in the example above, the form data is sent to “AddValues.php”.

The “AddValues.php” file connects to a database, and retrieves the values from the form with the PHP $_POST variables.Then, the mysql_query() function executes the INSERT INTO statement, and a new record will be added to the “Country” table.

    AddValues.php:

    <?php
    $con = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    mysql_select_db(”my_db”, $conn);
    $sql=”INSERT INTO Country (Country, Capital)
    VALUES(’$_POST[country]‘,’$_POST[capital]‘)”;
    if (!mysql_query($sql,$con))
    {
    die(’Error: ‘ . mysql_error());
    }
    echo “Record added successfully”;
    mysql_close($conn)
    ?>

PHP MySQL Inserting Values in Table

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

After creating a table you will need to insert records. You can use the INSERT INTO statement to add records to a database table.

There are two different forms to write this statement. The first form doesn’t specify the column names where the data will be inserted, only their values:

    INSERT INTO table_name VALUES (value1, value2, value3,…)

The second form specifies both the column names and the values to be inserted:

    INSERT INTO table_name (column1, column2, column3,…)
    VALUES (value1, value2, value3,…)
    For eg:

    <?php
    $conn = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    mysql_select_db(”my_db”, $conn);
    mysql_query(”INSERT INTO Persons (Country, Capital)
    VALUES (’India’, ‘New Delhi’)”);
    mysql_query(”INSERT INTO Persons (Country, Capital)
    VALUES (’United States of America’, ‘Washington D.C.’)”);
    mysql_query(”INSERT INTO Persons (Country, Capital)
    VALUES (’Zimbabwe’, ‘Harare’)”);
    mysql_query(”INSERT INTO Country (Country, Capital)
    VALUES (’Poland’, ‘Warsaw’)”);
    mysql_close($conn);
    ?>

Primary Keys and Auto Increment Fields

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

A primary key uniquely identifies the rows in a table. Each primary key value is unique within the table. It cannot be null because the database engine requires a value to locate the record.

The primary key of a relational table uniquely identifies each record in the table. A primary key can be any of the following:

It can either be a normal attribute that is guaranteed to be unique such as Social Security Number in a table with no more than one record per person

It can be generated by the DBMS. Primary keys may consist of a single attribute or multiple attributes in combination.

Autoincrement

We can get a unique auto generated number from MySQL by creating an auto incremented field. MySQL will generate a unique number by incrementing the last number of the table and will automatically add to the auto incremented field. We need not have to specify any thing in our query while adding the auto incremented field data. After successfully adding the record we can get this unique number by using mysql_insert_id().

    For eg:

    $sqlQuerry = “CREATE TABLE Persons
    (
    countryID int NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(countryID),
    Country varchar(15),
    Capital varchar(15)
    )”;
    mysql_query($sqlQuerry,$conn);

PHP MySQL Create Table

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

The CREATE TABLE statement is used to create a table in a database of MySQL.

Syntax

    CREATE TABLE table_name
    (
    column_name1 data_type,
    column_name2 data_type,
    column_name3 data_type,
    ….
    )

We must add the CREATE TABLE statement to the mysql_query() function to execute the command.

    For eg:

    <?php
    $conn = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    // Create database
    if (mysql_query(”CREATE DATABASE my_db”,$conn))
    {
    echo “Database Creation:Successful”;
    }
    else
    {
    echo “Database Creation:Unsuccessful: ” . mysql_error();
    }
    // Create table
    mysql_select_db(”my_db”, $conn); //Select database in which table is to be created
    $sqlQuerry = “CREATE TABLE Country
    (
    Country varchar(15),
    Capital varchar(15),
    )”;
    // Execute query
    mysql_query($sqlQuerry,$conn);
    mysql_close($con);
    ?>

Before creating a table you must select some database. The database is selected with the mysql_select_db() function.

Varchar() is a function which defines the data type for the variables containing alpha-numeric characters. You need to specify the maximum length of the field in varchar() e.g. varchar(15).

PHP MySQL Create Database

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

The first step is to create a database and then we can create tables in that database which we can use in our application.

To create a database in MySQL the CREATE DATABASE statement is used.

Syntax

    CREATE DATABASE database_name

The above statement runs in a querry analyzer. A querry analyzer is an interface to run database commands.  But you can run this stament directly from PHP by using the mysql_query() function. This function is used to send a query or command to a MySQL connection.

The following example creates a database called “my_db”:

    For eg:

    <?php
    $conn = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect: ‘ . mysql_error());
    }
    if (mysql_query(”CREATE DATABASE my_db”,$conn))
    {
    echo “Database creation:Successful”;
    }
    else
    {
    echo “Database creation:Unsuccessful: ” . mysql_error();
    }
    mysql_close($conn);
    ?>

PHP Connect to MySQL Database

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

For using a database, first you need to install a database, then there must be a database with the desired tables you wish to use. Finally there should be data in the tables which you will be using in your application.

The second major step then is to access the data through the database in your application.
For accessing data in a database, you must create a connection to the database. A connection is the gateway through which your request will go to the database and the result will be provided to you from the database.

In PHP, this is done with the mysql_connect() function.

Syntax

    mysql_connect(servername,username,password);
    Parameter

    servername

    Optional. Specifies the server to connect to. Default value is “localhost:3306″
    username Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process
    password Optional. Specifies the password to log in with. Default is “”

In the following example we store the connection in a variable ($con) for later use in the script. The “die” part will be executed if the connection fails:

    For eg:

    <?php
    $con = mysql_connect(”localhost”,”peter”,”abc123″);
    if (!$con)
    {
    die(’Could not connect to database: ‘ . mysql_error());
    }
    // some code
    ?>

Closing a Connection

The connection that is created and opened to access data in a database will be closed automatically when the script ends. But you can close it as soon as the database related work is done. To close the connection through your code you can use the mysql_close() function:

    <?php
    $conn = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect to database: ‘ . mysql_error());
    }
    // some code
    mysql_close($conn);
    ?>

PHP & MySQL

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

As you already know that PHP is a scripting language which is used to create dynamic contents on a website. The dynamic content may be some static information like a single image with effects or a single line as a banner. But there could be a serious need to store and retrieve some information at times. All of the content management systems, blogs or only a simple form processor use database.

The best and the most often used database with PHP is MySQL. MySQL is the most popular open-source database system. It is simple to use, and easy to interface with.

A database in general is a repository of information, where data is stored in a format which can easily operated upon.

The most common and widely used type of database is relation where the data is stored in tables. Tables are database objects which consists of columns and rows. A table contain similar kind of data associated to each other by some defined relation. Some tables may also be related to each other. Each table has a set of primary keys which are used to refer to the data uniquely. Primary key is a set of some information which is unique for each row.

Databases are useful when storing information categorically.

Database Tables

A database most often contains one or more tables. Each table is identified by a name. Each table contains records with data.

Below is an example of a table called “Country”:

    Country Capital
    India Delhi
    United States of America Washington D.C.
    Zimbabwe Harare
    Poland Warsaw

The table above contains four records, one for each country and two columns, Country and capital.

PHP Error Handling- Creating a Custom Error Handler

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

Creating a Custom Error Handler

A Custom Error Handler is a special function which is called when an error occurs in PHP.

This function should accept at least two parameters, ie error level and error message and at the max it may accept up to five parameters ie file, line-number, and the error context:

Syntax

    error_function(error_level,error_message,
    error_file,error_line,error_context)
    Parameter Description
    error_level Required. Specifies the error report level for the user-defined error. Must be a value number.
    error_message Required. Specifies the error message for the user-defined error
    error_file Optional. Specifies the filename in which the error occurred
    error_line Optional. Specifies the line number in which the error occurred
    error_context Optional. Specifies an array containing every variable, and their values, in use when the error occurred

Error Report levels

These error report levels are the different types of error the user-defined error handler can be used for:

    Value Constant Description
    2 E_WARNING Non-fatal run-time errors. Execution of the script is not halted
    8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script normally
    256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
    512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function trigger_error()
    1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
    4096 E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also set_error_handler())
    8191 E_ALL All errors and warnings, except level E_STRICT (E_STRICT will be part of E_ALL as of PHP 6.0)

Now lets create a function to handle errors:

    function customError($erroeNo, $errorString)
    {echo “<b>Error:</b> [$errorNo] $errorString<br />”;
    die();
    }

The code above is a simple error handling function. When it is triggered, it gets the error level and an error message. It then outputs the error level and message and terminates the script.

Here we have created an error handling function, so mow we we need to decide when it should be triggered.

Set Error Handler

PHP provides a built in default error handler error handler.

You can also change the error handler to apply for only some errors, so this way you can make more handlers for different type of errors, which will handle the errors in specific ways.

    set_error_handler(”customError”);

Since we want our custom function to handle all errors, the set_error_handler() only needed one parameter, a second parameter could be added to specify an error level.

In this example below we are testing the error handler by trying to output variable that does not exist:

    For eg:

    <?php //error handler function
    function customError($errorNo, $errorString)
    {
    echo “<b>Error:</b> [$errorNo] $errorString”;
    }
    //set error handler
    set_error_handler(”customError”);
    //trigger error
    echo($num);
    ?>

    Output:

    Error: [8] Undefined variable: num

Trigger an Error

In the above example we triggered the error without any reason. We need some valid trigger for the error handler to be triggered. When a user inputs data, some wrong input may be provided so we need to trigger the handler whenever a user inputs a invalid data. In PHP, this is done by the trigger_error() function.

In this example an error occurs if the “num” variable is less than “1″:

    For eg:

    <?php
    $num=0;
    if ($num<1)
    {
    trigger_error(”Number must be greater than 0″);
    }
    ?>

    Output:

    Notice: Number must be greater than 0 in C:\applications\errorTest.php on line 6

By this method you can trigger an error anywhere you wish in a script. By adding a second parameter, you can specify what error level is triggered.

Possible error types:

  • E_USER_ERROR – Fatal user-generated run-time error. Errors that can not be recovered from. Execution of the script is halted
  • E_USER_WARNING – Non-fatal user-generated run-time warning. Execution of the script is not halted
  • E_USER_NOTICE – Default. User-generated run-time notice. The script found something that might be an error, but could also happen when running a script normally

In this example an E_USER_WARNING occurs if the “num” variable is less than “1″. If an E_USER_WARNING occurs we will use our custom error handler and end the script:

    For eg:

    <?php //error handler function
    function customError($errorNo, $errorString)
    {
    echo “<b>Error:</b> [$errorNo] $errorString<br />”;
    die();
    }
    //set error handler
    set_error_handler(”customError”,E_USER_WARNING);
    //trigger error
    $num=0;
    if ($test<1)
    {
    trigger_error(”Number must be greater than 1″,E_USER_WARNING);
    }
    ?>

    Output:
    Error: [512] Value must be 1 or below

Filter Multiple Inputs

Posted by tutor | Posted in PHP Tutorial | Posted on 17-12-2009-05-2008

0

A form generally consists of more than one input field. To avoid calling the filter_var or filter_input functions over and over again for each of the inputs, we can use the filter_var_array or the filter_input_array functions.

In this example we use the filter_input_array() function to filter three GET variables. The received GET variables is a name, an age and an e-mail address:

    <?php
    $filters = array
    (
    “name” => array
    (
    “filter”=>FILTER_SANITIZE_STRING
    ),
    “age” => array
    (
    “filter”=>FILTER_VALIDATE_INT,
    “options”=>array
    (
    “min_range”=>1,
    “max_range”=>120
    )
    ),
    “email”=> FILTER_VALIDATE_EMAIL,
    );
    $result = filter_input_array(INPUT_GET, $filters);
    if (!$result["age"])
    {
    echo(”Age must be a number between 1 and 120.<br />”);
    }
    elseif(!$result["email"])
    {
    echo(”E-Mail is not valid.<br />”);
    }
    else
    {
    echo(”User input is valid”);
    }
    ?>

The example above has three inputs (name, age and email) sent to it using the “GET” method. It works as:

  • Set an array containing the name of input variables and the filters used on the specified input variables
  • Call the filter_input_array() function with the GET input variables and the array we just set
  • Check the “age” and “email” variables in the $result variable for invalid inputs. (If any of the input variables are invalid, that input variable will be FALSE after the filter_input_array() function)
  • The second parameter of the filter_input_array() function can be an array or a single filter ID.

If the parameter is a single filter ID all values in the input array are filtered by the specified filter.

If the parameter is an array it must follow these rules:

  • Must be an associative array containing an input variable as an array key (like the “age” input variable)
  • The array value must be a filter ID or an array specifying the filter, flags and options

Using Filter Callback

You can also call your own function and use it as a filter using the FILTER_CALLBACK filter. This way, you can have full control of the data filtering.
The function you wish to use to filter is specified the same way as an option is specified. In an associative array with the name “options”

In the example below, we use a user created function to convert all “_” to whitespaces:

    <?php
    function convertSpace($string)
    {
    return str_replace(”_”, ” “, $string);
    }
    $string = “Peter_is_a_great_guy!”;
    echo filter_var($string, FILTER_CALLBACK,
    array(”options”=>”convertSpace”));
    ?>
    Output

    Peter is a great guy!

The example above converts all “_” to whitespaces. It works as:

  • Create a function to replace “_” to whitespaces
  • Call the filter_var() function with the FILTER_CALLBACK filter and an array containing our function