AMSSOI-Andhra Mahila Sabha School of Informatics
The array functions allow you to manipulate arrays.<br /> <br /> PHP supports both simple and multi-dimensional arrays. There are also specific functions for populating arrays from database queries.<br /> <br /> These functions allow you to interact with and manipulate arrays in various ways. Arrays are essential for storing, managing, and operating on sets of variables.<br /> <br /> Simple and multi-dimensional arrays are supported, and may be either user created or created by another function. There are specific database handling functions for populating arrays from database queries, and several functions return arrays.<br /> <br /> <strong>For detailed explanation read the attached document.</strong>
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 22: Update data in a database</strong></u><br /> <br /> In previous lessons, you have learned to insert, retrieve and delete data from a database. In this lesson, we will look at how to update a database, i.e., edit the values of existing fields in the table.<br /> <br /> <em><strong>Update data with SQL</strong></em><br /> <br /> The syntax for an SQL statement that updates the fields in a table is:<br /> <br /> <br /> UPDATE TableName SET TableColumn='value' WHERE condition<br /> <br /> <br /> It is also possible to update multiple cells at once using the same SQL statement:<br /> <br /> <br /> UPDATE TableName SET TableColumn1='value1', TableColumn2='value2' WHERE condition<br /> <br /> <br /> With the knowledge you now have from the lessons 19, 20 and 21, it should be quite easy to understand how the above syntax is used in practice. But we will of course look at an example.<br /> <br /> <em><strong>Example: Update cells in the table "people"</strong></em><br /> <br /> The code below updates Donald Duck's first name to D. and changes the phone number to 44444444. The other information (last name and birthdate) are not changed. You can try to change the other people's data by writing your own SQL statements.<br /> <br /> <br /> <html><br /> <head><br /> <title>Update data in database</title><br /> <br /> </head><br /> <body><br /> <br /> <?php<br /> // Connect to database server<br /> mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());<br /> <br /> // Select database<br /> mysql_select_db("mydatabase") or die(mysql_error());<br /> <br /> // The SQL statement is built<br /> $strSQL = "Update people set ";<br /> $strSQL = $strSQL . "FirstName= 'D.', ";<br /> $strSQL = $strSQL . "Phone= '44444444' ";<br /> <br /> $strSQL = $strSQL . "Where id = 22";<br /> <br /> // The SQL statement is executed<br /> mysql_query($strSQL);<br /> <br /> // Close the database connection<br /> mysql_close();<br /> ?><br /> <br /> <h1>The database is updated!</h1><br /> </body><br /> </html><br /> <br /> <br /> This example completes the lessons on databases. You have learned to insert, retrieve, delete and update a database with PHP. Thus, you are actually now able to make very advanced and dynamic web solutions, where the users can maintain and update a database using forms.<br /> <br /> If you want to see a sophisticated example of what can be made with PHP and databases, try to join our community. It's free and takes approximately one minute to sign up. You can, among other things, maintain your own profile using the form fields. Maybe you will get ideas for your own site.<br /> <br /> This also ends the tutorial. PHP gives you many possibilities for adding interactivity to your web site. The only limit is your imagination - have fun!<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 21: Delete data from database</strong></u><br /> <br /> In the two previous lessons, you have learned to insert and retrieve data from a database. In this lesson, we'll look at how to delete records in the database, which is considerably easier than inserting data.<br /> <br /> <em><strong>Delete data using SQL</strong></em><br /> <br /> The syntax for an SQL statement that deletes records is:<br /> <br /> <br /> DELETE FROM TableName WHERE condition<br /> <br /> <br /> <u><strong>Example: Delete a record</strong></u><br /> <br /> When deleting a record, you can use the unique AutoNumber field in the database. In our database, it is the column named id. Using this unique identifier ensures that you only delete one record. In the next example, we delete the record where id has the value 24:<br /> <br /> <br /> <html><br /> <head><br /> <title>Delete data in the database</title><br /> </head><br /> <br /> <body><br /> <br /> <?php<br /> // Connect to database server<br /> mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());<br /> <br /> // Select database<br /> mysql_select_db("mydatabase") or die(mysql_error());<br /> <br /> // The SQL statement that deletes the record<br /> $strSQL = "DELETE FROM people WHERE id = 24";<br /> mysql_query($strSQL);<br /> <br /> // Close the database connection<br /> mysql_close();<br /> ?><br /> <br /> <h1>Record is deleted!</h1><br /> <br /> </body><br /> </html><br /> <br /> <br /> Remember that there is no "Recycle Bin" when working with databases and PHP. Once you have deleted a record, it is gone and cannot be restored.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 20: Get data from database</strong></u><br /> <br /> Now it's time to retrieve data from our database to our PHP pages.<br /> <br /> This is really one of the most important lessons in this tutorial. Once you have read and understood this lesson, you will realize why database-driven web solutions are so powerful, and your views on web development will be expanded dramatically.<br /> <br /> <em><strong>SQL queries</strong></em><br /> <br /> To retrieve data from a database, you use queries. An example of a query could be: "get all data from the table 'people' sorted alphabetically" or "get names from the table 'people'".<br /> <br /> Again, the language Structured Query Language (SQL) is used to communicate with the database. Try looking at this simple example:<br /> <br /> <br /> Get all data from the table 'people'<br /> <br /> <br /> Will be written like this in SQL:<br /> <br /> <br /> SELECT * FROM people<br /> <br /> <br /> The syntax is pretty self-explanatory. Just read on and see how SQL statements are used in the examples below.<br /> <br /> <u><strong>Example 1: Retrieve data from a table</strong></u><br /> <br /> This example uses the database and table from lesson 19 and lesson 18. Therefore, it is important that you read these lessons first.<br /> <br /> The example shows how data in the table "people" is retrieved with an SQL query.<br /> <br /> The SQL query returns a result in the form of a series of records. These records are stored in a so-called recordset. A recordset can be described as a kind of table in the server's memory, containing rows of data (records), and each record is subdivided into individual fields (or columns).<br /> <br /> A recordset can be compared to a table where each record could be compared to a row in the table. In PHP, we can run through a recordset with a loop and the function mysql_fetch_array, which returns each row as an array.<br /> <br /> The code below shows how to use mysql_fetch_array to loop through a recordset:<br /> <br /> <br /> <html><br /> <head><br /> <title>Retrieve data from database </title><br /> </head><br /> <body><br /> <br /> <?php<br /> // Connect to database server<br /> mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());<br /> <br /> // Select database<br /> mysql_select_db("mydatabase") or die(mysql_error());<br /> <br /> // SQL query<br /> $strSQL = "SELECT * FROM people";<br /> <br /> // Execute the query (the recordset $rs contains the result)<br /> $rs = mysql_query($strSQL);<br /> <br /> // Loop the recordset $rs<br /> // Each row will be made into an array ($row) using mysql_fetch_array<br /> while($row = mysql_fetch_array($rs)) {<br /> <br /> // Write the value of the column FirstName (which is now in the array $row)<br /> echo $row['FirstName'] . "<br />";<br /> <br /> }<br /> <br /> // Close the database connection<br /> mysql_close();<br /> ?><br /> </body><br /> </html><br /> <br /> Notice that for every record how we get the content of the column "FirstName" by typing $row['FirstName']. Similarly, we can get the content of the column "Phone" by writing $row['Phone'], for example.<br /> <br /> The order of the recordset is exactly the same as in the table in the database. But in the next example, it will be shown how to sort recordset.<br /> <br /> <u><strong>Example 2: Sort the data alphabetically, chronologically or numerically</strong></u><br /> <br /> Often it can be helpful if a list or table of data is presented alphabetically, chronologically or numerically. Such sorting is very easy to do with SQL, where the syntax Order By ColumnName is used to sort according to the column contents.<br /> <br /> Look at the SQL statement from the example above:<br /> <br /> <br /> strSQL = "SELECT * FROM people"<br /> <br /> <br /> The records can, for example, be sorted alphabetically by the first name of the people this way:<br /> <br /> <br /> strSQL = "SELECT * FROM people ORDER BY FirstName"<br /> <br /> <br /> Or chronologically by date of birth like this:<br /> <br /> <br /> strSQL = "SELECT * FROM people ORDER BY BirthDate"<br /> <br /> <br /> The sorting can be charged from ascending to descending by adding DESC:<br /> <br /> <br /> strSQL = "SELECT * FROM people ORDER BY BirthDate DESC"<br /> <br /> <br /> In the following example, the people are sorted by age:<br /> <br /> <html><br /> <head><br /> <br /> <title>Retrieve data from database </title><br /> <br /> </head><br /> <body><br /> <br /> <?php<br /> // Connect to database server<br /> mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());<br /> <br /> // Select database<br /> mysql_select_db("mydatabase") or die(mysql_error());<br /> <br /> // SQL query<br /> $strSQL = "SELECT * FROM people ORDER BY BirthDate DESC";<br /> <br /> // Execute the query (the recordset $rs contains the result)<br /> $rs = mysql_query($strSQL);<br /> <br /> // Loop the recordset $rs<br /> while($row = mysql_fetch_array($rs)) {<br /> <br /> // Write the value of the column FirstName and BirthDate<br /> echo $row['FirstName'] . " " . $row['BirthDate'] . "<br />";<br /> <br /> }<br /> <br /> // Close the database connection<br /> mysql_close();<br /> ?><br /> <br /> </body><br /> </html><br /> <br /> Try to change the SQL statement yourself and sort the records by first name, last name or phone number.<br /> <br /> <strong><em>Retrieve selected data</em></strong><br /> <br /> Until now, our SQL statement retrieves all rows from the table. But often you need to set criteria in the SQL query for the data to be retrieved, for instance, if we only want the rows for those who have a particular phone number or a certain last name.<br /> <br /> Say, we only want to retrieve people from the database who have the phone number "66554433". That could be done like this:<br /> <br /> <br /> strSQL = "SELECT * FROM people WHERE Phone = '66554433 '"<br /> <br /> <br /> <em>There are six relational operators in SQL:</em><br /> <br /> = Equals<br /> < Less than<br /> > Greater Than<br /> <= Less than or equal to<br /> >= Greater than or equal to<br /> != Not equal to<br /> In addition, there are some logical operators:<br /> <br /> AND<br /> OR<br /> NOT<br /> See lesson 6 for more information on how to set up conditions.<br /> <br /> In the next example, we use conditions to set up an address book.<br /> <br /> <u><strong>Example 3: Address book</strong></u><br /> <br /> In this example, we will try to combine many of the things you have just learned. We will make a list of the names from the database where each name is a link to further details about the person.<br /> <br /> For this, we need two files - list.php and person.php - with the following code:<br /> <br /> The code of list.php<br /> <br /> <br /> <html><br /> <head><br /> <title>Retrieve data from the database</title><br /> </head><br /> <body><br /> <br /> <ul><br /> <br /> <?php<br /> // Connect to database server<br /> mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());<br /> <br /> // Select database<br /> mysql_select_db("mydatabase") or die(mysql_error());<br /> <br /> // SQL query<br /> $strSQL = "SELECT * FROM people ORDER BY FirstName DESC";<br /> <br /> // Execute the query (the recordset $rs contains the result)<br /> $rs = mysql_query($strSQL);<br /> <br /> // Loop the recordset $rs<br /> while($row = mysql_fetch_array($rs)) {<br /> <br /> // Name of the person<br /> $strName = $row['FirstName'] . " " . $row['LastName'];<br /> <br /> // Create a link to person.php with the id-value in the URL<br /> $strLink = "<a href = 'person.php?id = " . $row['id'] . "'>" . $strNavn . "</a>";<br /> <br /> // List link<br /> echo "<li>" . $strLink . "</li>";<br /> <br /> }<br /> <br /> // Close the database connection<br /> mysql_close();<br /> ?><br /> <br /> </ul><br /> </body><br /> </html><br /> <br /> <br /> <br /> The code for person.php<br /> <br /> <html><br /> <head><br /> <title>Retrieve data from database</title><br /> </head><br /> <body><br /> <br /> <dl><br /> <br /> <?php<br /> // Connect to database server<br /> mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());<br /> <br /> // Select database<br /> mysql_select_db("mydatabase") or die(mysql_error());<br /> <br /> // Get data from the database depending on the value of the id in the URL<br /> $strSQL = "SELECT * FROM people WHERE id=" . $_GET["id"];<br /> $rs = mysql_query($strSQL);<br /> <br /> // Loop the recordset $rs<br /> while($row = mysql_fetch_array($rs)) {<br /> <br /> // Write the data of the person<br /> echo "<dt>Name:</dt><dd>" . $row["FirstName"] . " " . $row["LastName"] . "</dd>";<br /> echo "<dt>Phone:</dt><dd>" . $row["Phone"] . "</dd>";<br /> echo "<dt>Birthdate:</dt><dd>" . $row["BirthDate"] . "</dd>";<br /> <br /> }<br /> <br /> // Close the database connection<br /> mysql_close();<br /> ?><br /> <br /> </dl><br /> <p><a href="list.php">Return to the list</a></p><br /> <br /> </body><br /> <br /> </html><br /> <br /> <br /> The address book example is rather simple, but it shows the potential of working with PHP and databases.<br /> <br /> Imagine that the database had contained 10,000 products with detailed descriptions. By making a few changes in the above files, you could easily create a product catalogue with more than 10,000 pages with only one database and two PHP files.<br /> <br /> Welcome to a world with extensive websites that are easy to develop and maintain! Once you've learned to work with databases, your web solutions will never be the same again.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 19: Insert data into a database</strong></u><br /> <br /> In this lesson, we look at how you can insert data into the database directly from your PHP scripts.<br /> <br /> <em><strong>Insert data using SQL</strong></em><br /> <br /> You use SQL to insert data in a database in the same way that you can use SQL to create databases and tables. The syntax of the SQL query is:<br /> <br /> <br /> INSERT INTO TableName(column1, column2, ...) VALUES(value1, value2, ...)<br /> <br /> <br /> As you can see, you can update multiple columns in the SQL statement by specifying them in a comma-separated list. But of course, it is also possible to specify just one column and one value. The columns that are not mentioned in the SQL statement will just be empty.<br /> <br /> <u><strong>Example: Insert a new person in the table</strong></u><br /> <br /> In this example we use the database from lesson 18. Let's say we want to insert a person into the database. It could be the person Gus Goose with the phone number 99887766 and 1964-04-20 as the date of birth.<br /> <br /> The SQL statement would then look like this:<br /> <br /> <br /> $strSQL = "INSERT INTO people(FirstName,LastName,Phone,BirthDate) VALUES('Gus','Goose','99887766 ','1964-04-20')";<br /> <br /> mysql_query($strSQL) or die(mysql_error());<br /> <br /> <br /> As you can see, SQL statements can get quite long, and you can easily lose track. Therefore, it can be an advantage to write the SQL statement in a slightly different way:<br /> <br /> <br /> strSQL = "INSERT INTO people(";<br /> <br /> strSQL = strSQL . "FirstName, ";<br /> strSQL = strSQL . "LastName, "<br /> strSQL = strSQL . "Phone, ";<br /> strSQL = strSQL . "birth) ";<br /> <br /> strSQL = strSQL . "VALUES (";<br /> <br /> strSQL = strSQL . "'Gus', ";<br /> strSQL = strSQL . "'Goose', ";<br /> strSQL = strSQL . "'99887766', ";<br /> <br /> strSQL = strSQL . "'1964-04-20')";<br /> <br /> mysql_query($strSQL) or die(mysql_error());<br /> <br /> <br /> This way, the SQL statement is built up by splitting the sentence into small parts and then putting those parts together in the variable $strSQL.<br /> <br /> In practice, it makes no difference which method you choose, but once you start working with larger tables, it's crucial that you always keep track, so choose the method you find most convenient.<br /> <br /> Try running the following code to insert Gus Goose into the database:<br /> <br /> <br /> <html><br /> <head><br /> <title>Insert data into database</title><br /> </head><br /> <body><br /> <?php<br /> <br /> // Connect to database server<br /> mysql_connect("mysql.myhost.com", "user", "sesame") or die (mysql_error ());<br /> <br /> // Select database<br /> mysql_select_db("mydatabase") or die(mysql_error());<br /> <br /> // The SQL statement is built<br /> <br /> $strSQL = "INSERT INTO people(";<br /> <br /> $strSQL = $strSQL . "FirstName, ";<br /> $strSQL = $strSQL . "LastName, ";<br /> <br /> $strSQL = $strSQL . "Phone, ";<br /> $strSQL = $strSQL . "BirthDate) ";<br /> <br /> $strSQL = $strSQL . "VALUES(";<br /> <br /> $strSQL = $strSQL . "'Gus', ";<br /> <br /> $strSQL = $strSQL . "'Goose', ";<br /> $strSQL = $strSQL . "'99887766', ";<br /> <br /> $strSQL = $strSQL . "'1964-04-20')";<br /> <br /> // The SQL statement is executed<br /> mysql_query($strSQL) or die (mysql_error());<br /> <br /> // Close the database connection<br /> mysql_close();<br /> ?><br /> <br /> <h1>The database is updated!</h1><br /> </body><br /> </html><br /> <br /> <br /> <em><strong>Save user input into a database</strong></em><br /> <br /> Often you want to save user input in a database.<br /> <br /> As you've probably already figured out, this can be done by creating a form as described in lesson 11 - where the values from the form fields can be inserted in the SQL statement. Suppose you have a simple form like this:<br /> <br /> <br /> <form action="insert.php" method="post"><br /> <input type="text" name="FirstName" /><br /> <input type="submit" value="Save" /><br /> <br /> </form><br /> <br /> <br /> The form submits to the file insert.php where you, as shown in lesson 11, can get the user's input by requesting the form content. In this particular example, an SQL statement could look like this:<br /> <br /> <br /> strSQL = "INSERT INTO people(FirstName) values('" . $_POST["FirstName"] . "')"<br /> <br /> <br /> In the same way, it is possible to retrieve data from cookies, sessions, query strings, etc.<br /> <br /> <em><strong>Most common beginner mistakes</strong></em><br /> <br /> In the beginning, you will probably get a lot of error messages when you try to update your databases. There is no room for the slightest inaccuracy when you work databases. A misplaced comma can mean the database is not being updated, and you get an error message instead. Below, we describe the most common beginner mistakes.<br /> <br /> <em><strong>Wrong data types</strong></em><br /> <br /> It is important that there is consistency between the type of data and column. Each column can be set to a data type. The screenshot below shows the data types for the table "people" in our example.<br /> <br /> See Fig 1<br /> <br /> An error occurs if you, for example, attempt to insert text or numbers in a date field. Therefore, try to set the data types as precisely as possible.<br /> <br /> Below is the most common data types listed:<br /> <br /> <strong>CHAR</strong><br /> Text or combinations of text and numbers. Can also be used for numbers that are not used in calculations (e.g., phone numbers). Up to 255 characters - or the length defined in the "Length"<br /> <strong>TEXT</strong><br /> Longer pieces of text, or combinations of text and numbers. Up to 65,535 characters.<br /> <strong>INT</strong><br /> Numerical data for mathematical calculations. 4 bytes.<br /> <strong>DATE</strong><br /> Dates in the format YYYY-MM-DD 3 bytes.<br /> <strong>TIME</strong><br /> Time in the format hh:mm:ss 3 bytes.<br /> <strong>DATETIME</strong><br /> Date and time in the format YYYY-MM-DD hh:mm:ss 8 bytes.<br /> <br /> <em><strong>SQL statements with quotes or backslash</strong></em><br /> <br /> If you try to insert text that contains the characters single quote ('), double quote (") or backslash (\), the record may not be inserted into the database. The solution is to add backslashes before characters that need to be quoted in database queries.<br /> <br /> This can be done with the function addslashes this way:<br /> <br /> <br /> <?php<br /> <br /> $strText = "Is your name O'Reilly?";<br /> $strText = addslashes($strText);<br /> <br /> ?><br /> <br /> <br /> All single quotes ('), double quotes (") and backslashs (\) will then get an extra backslash before the character. This would only be to get the data into the database, the extra \ will not be inserted. Please note that PHP runs addslashes on all $_GET, $_POST, and $_COOKIE data by default. Therefore do not use addslashes on strings that have already been escaped.<br /> <br /> In the next lesson you will learn to retrieve data from your database. But first, try to insert some more people in your database.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 18: Create databases and tables</strong></u><br /> <br /> In the previous lesson we looked at how to create a connection to a database server. Next step is to create databases and tables.<br /> <br /> We'll look at two ways to create databases and tables. First, how it is done in PHP, and then how it's made with the more user-friendly tool PhpMyAdmin, which is standard on most web hosts and in XAMPP.<br /> <br /> If you have a hosted website with PHP and MySQL, a database has probably been created for you already and you can just skip this part of the lesson and start creating tables. Again, you should consult your host's support pages for more information.<br /> <br /> <em><strong>Create a database and tables with PHP</strong></em><br /> <br /> The function mysql_query are used to send a query to a MySQL database. The queries are written in the language Structured Query Language (SQL). SQL is the most widely used language for database queries - not only for MySQL databases - and is very logical and easy to learn. In this lesson and the next, you will learn the most important SQL queries.<br /> <br /> When creating a database, the SQL query CREATE DATABASE is used with the following syntax:<br /> <br /> CREATE DATABASE database name<br /> <br /> Logical and easy, right!? Let's try to put it into a PHP script:<br /> <br /> <br /> mysql_connect("mysql.myhost.com", "user", "sesame") or die(mysql_error());<br /> <br /> mysql_query("CREATE DATABASE mydatabase") or die(mysql_error());<br /> <br /> mysql_close();<br /> <br /> <br /> First, we connect to the MySQL server. Next, we create a database named "mydatabase". And finally, we close the connection to the MySQL server again.<br /> <br /> So far so good... but things become a little bit more complicated when we want create tables in PHP. When creating tables, we use the SQL query CREATE TABLE with the following syntax:<br /> <br /> <br /> CREATE TABLE table name<br /> (<br /> column1_name DATA_TYPE,<br /> column2_name DATA_TYPE,<br /> column3_name DATA_TYPE,<br /> ...<br /> )<br /> <br /> <br /> table_name and column_name are of course the name of the table and the columns, respectively. DATA_TYPE are used to specify the data type to be inserted into the column. The most commonly used data types are:<br /> <br /> <strong>INT</strong><br /> For numbers without decimals<br /> <strong>DECIMAL</strong><br /> For numbers with decimals<br /> <strong>CHAR</strong><br /> Short text up to 255 characters<br /> <strong>TEXT</strong><br /> For plain text up to 65,535 characters<br /> <strong>LONGTEXT</strong><br /> For long passages of text up to 4,294,967,295 characters<br /> <strong>Date</strong><br /> For dates in the format YYYY-MM-DD<br /> <strong>Time</strong><br /> For time in the format HH:MM:SS<br /> <strong>DATETIME</strong><br /> For date and time in the format YYYY-MM-DD HH:MM:SS<br /> <br /> All in all, logical and relatively easy. Let's try to put it into an example:<br /> <br /> mysql_connect("mysql.myhost.com", "user", "sesame") or die(mysql_error());<br /> mysql_select_db("people") or die(mysql_error());<br /> <br /> mysql_query("CREATE TABLE MyTable (<br /> id INT AUTO_INCREMENT,<br /> FirstName CHAR,<br /> LastName CHAR,<br /> Phone INT,<br /> BirthDate DATE<br /> PRIMARY KEY(id)<br /> )") Or die(mysql_error());<br /> mysql_close ();<br /> <br /> <br /> In the example, we start by connecting to the MySQL server. Next we use the function mysql_select_db to select the database "people". Then we create the table "persons" with 5 columns.<br /> <br /> Note that at the "id" column, we first use INT to specify that the column contains numbers and then add AUTO_INCREMENT to automatically increase the number and ensure a unique ID for each row.<br /> <br /> At the end, we use PRIMARY KEY to set the "id" column as the primary key. The primary key uniquely identifies each record (/row) in the table, which becomes very useful later when we update the database.<br /> <br /> <em><strong>Create database and tables with phpMyAdmin</strong></em><br /> <br /> It can be useful to be able to create databases and tables directly in PHP. But often, it will be easier to use phpMyAdmin (or any other MySQL administration tool), which is standard on most web hosts and XAMPP. The screendumps below shows how to create a database and tables in phpMyAdmin.<br /> <br /> Start by logging onto phpMyAdmin. Often, the address will be the same as your MySQL server (eg. "http://mysql.myhost.com") and with the same username and password. In XAMPP, the address is http://localhost/phpmyadmin/.<br /> <br /> When you are logged on, simply type a name for the database and press the button "Create":<br /> <br /> See fig 1<br /> <br /> At some hosts, it's possible the have already created a database, and you may not have the rights to create more. If that is the case, you obviously just use the assigned database.<br /> <br /> To create a table, click on the tab "Databases" and choose a database by clicking on it:<br /> <br /> See fig 2<br /> <br /> Then there will be a box titled "Create new table in database", where you type the name of the table and the number of columns and press the button "Go":<br /> <br /> See fig 3<br /> <br /> Then you can name the columns and set the data type, etc., as in the SQL example above.<br /> <br /> See fig 4<br /> <br /> Notice, that here we also set "id" as PRIMARY KEY and uses AUTO_INCREMENT (A_I).<br /> <br /> Now you have created your own database and table. In the next lessons, we look at how to insert, retrieve and delete data in a database<br /> <br /> <br /> <br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 17: Databases</strong></u><br /> <br /> A database is a collection of information / data that is organized so that it can easily be retrieved, administrated and updated. Databases thereby enable the opportunity to create dynamic websites with large amounts of information. For example, all data on members of HTML.net and all posts in the forums are stored in databases.<br /> <br /> A database usually consists of one or more tables. If you are used to working with spreadsheets, or maybe have used databases before, tables will look familiar to you with columns and rows:<br /> <br /> See Figure 1<br /> <br /> There are many different databases: MySQL, MS Access, MS SQL Server, Oracle SQL Server and many others. In this tutorial, we will use the MySQL database. MySQL is the natural place to start when you want to use databases in PHP.<br /> <br /> You need to have access to MySQL in order to go through this lesson and the next lessons:<br /> <br /> If you have a hosted website with PHP, MySQL is probably already installed on the server. Read more at your web host's support pages.<br /> If you have installed PHP on your computer yourself and have the courage to install MySQL as well, it can be downloaded in a free version (MySQL Community Edition) at the MySQL's website.<br /> If you use XAMPP (see lesson 2), MySQL is already installed and ready to use on your computer. Just make sure MySQL is running in the Control Panel:<br /> <br /> See Figure 2<br /> <br /> In the rest of this lesson, we will look more closely at how you connect to your database server, before we learn to create databases and retrieve and update data in the following sessions.<br /> <br /> <em><strong>Connection to database server</strong></em><br /> <br /> First, you need to have access to the server where your MySQL database is located. This is done with the function mysql_connect with the following syntax:<br /> <br /> mysql_connect(server, username, password)<br /> <br /> Pretty straightforward: First, you write the location of the database (server), and then type in the username and password.<br /> <br /> If you have your own website, you should read about location of your MySQL server on your host's support pages. Username and password will often be the same as those you use for FTP access. Otherwise contact your provider.<br /> <br /> Example of a MySQL connection on a hosted website:<br /> <br /> mysql_connect("mysql.myhost.com", "user001", "sesame") or die(mysql_error());<br /> <br /> Example of a MySQL connection with XAMPP (default settings):<br /> <br /> mysql_connect("localhost", "root", "") or die (mysql_error());<br /> <br /> In the examples are added or die(mysql_error()) which, in brief, interrupts the script and writes the error if the connection fails.<br /> <br /> Now we have made a connection to a MySQL server, and can now start creating databases and retrieve and insert data. This is exactly what we will look at in the next lessons.<br /> <br /> By the way, keep in mind that it is good practice to close the database connection again when you're finished retrieving or updating data. This is done with the function mysql_close.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 16: Writing to a text file</strong></u><br /> <br /> In the previous lesson, we learned to read from a text file. In this lesson, we will learn to write to a text file.<br /> <br /> The two methods are very similar, but there is one very important difference: You must have write permissions to the file. This means that the file will have to be located in a folder where you have the necessary permissions.<br /> <br /> If you work locally on your own computer, you can set the permissions yourself: right-click on the folder and choose "Properties". With most web hosts, you will normally have one folder with write permissions. It's often called something like "cgi-bin", "log", "databases" or something similar. If your web host permits it, you might also be able to set permissions yourself. Usually you can simply right-click on a folder in your FTP client and choose "properties" or "permissions" or something similar. The screendumps below shows how it's done in FileZilla.<br /> <br /> See Figure 1<br /> <br /> Note that it is the text file that needs to be in the folder with write permissions - not the PHP file.<br /> <br /> <em><strong>Open the text file for writing</strong></em><br /> <br /> In the same way as when reading from a text file, the fopen function is used for writing, but this time we set the mode to "w" (writing) or "a" (appending).<br /> <br /> The difference between writing and appending is where the 'cursor' is located - either at the beginning or at the end of the text file.<br /> <br /> The examples in this lesson use an empty text file called textfile.txt. But you can also create your own text file if you like.<br /> <br /> First, let us try to open the text file for writing:<br /> <br /> <br /> <?php<br /> <br /> // Open the text file<br /> $f = fopen("textfile.txt", "w");<br /> <br /> // Close the text file<br /> fclose($f);<br /> <br /> ?><br /> <br /> <br /> <em><strong>Example 1: Write a line to the text file</strong></em><br /> <br /> To write a line, we must use the function fwrite, like this:<br /> <br /> <br /> <html><br /> <br /> <head><br /> <title>Writing to a text file</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> // Open the text file<br /> $f = fopen("textfile.txt", "w");<br /> <br /> // Write text line<br /> fwrite($f, "PHP is fun!");<br /> <br /> // Close the text file<br /> fclose($f);<br /> <br /> // Open file for reading, and read the line<br /> $f = fopen("textfile.txt", "r");<br /> echo fgets($f);<br /> <br /> fclose($f);<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> Since we opened the file for writing, the line is added at the top, and thus overwrites the existing line. If we instead open the file appending, the line is added at the bottom of the text file, which then will increase by one line each time it's written to.<br /> <br /> <em><strong>Example 2: Adding a text block to a text file</strong></em><br /> <br /> Of course, it is also possible to add an entire text block, instead of just a single line, like this:<br /> <br /> <br /> <html><br /> <head><br /> <title>Write to a text file</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> // Open the text file<br /> $f = fopen("textfile.txt", "w");<br /> <br /> // Write text<br /> fwrite($f, $_POST["textblock"]);<br /> <br /> // Close the text file<br /> fclose($f);<br /> <br /> // Open file for reading, and read the line<br /> $f = fopen("textfile.txt", "r");<br /> <br /> // Read text<br /> echo fgets($f);<br /> fclose($f);<br /> <br /> ?><br /> <br /> </body><br /> <br /> </html><br /> <br /> In the next lessons, we look at another way of storing data: databases.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 15: Reading from a text file</strong></u><br /> <br /> In the previous lesson, we learned how to use PHP to access the server's filesystem. In this lesson, we will use that information to read from an ordinary text file.<br /> <br /> Text files can be extremely useful for storing various kinds of data. They are not quite as flexible as real databases, but text files typically don't require as much memory. Moreover, text files are a plain and simple format that works on most systems.<br /> <br /> <em><strong>Open the text file</strong></em><br /> <br /> We use the fopen function to open a text file. The syntax is as follows:<br /> <br /> <br /> fopen(filename, mode)<br /> <br /> <br /> <strong>filename</strong><br /> Name of the file to be opened.<br /> <strong>mode</strong><br /> Mode can be set to "r" (reading), "w" (writing) or "a" (appending). In this lesson, we will only read from a file and, therefore, use "r". In the next lesson, we will learn to write and append text to a file.<br /> The examples in this lesson use the text file unitednations.txt. This is a simple list of the Programmes and Funds of the United Nations and their domains. You can either download the file, or you can create your own file and test the examples with it.<br /> <br /> First, let's try to open unitednations.txt:<br /> <br /> <br /> <?php<br /> <br /> // Open the text file<br /> $f = fopen("unitednations.txt", "r");<br /> <br /> // Close the text file<br /> fclose($f);<br /> <br /> ?><br /> <br /> <br /> <br /> <em><u><strong>Example 1: Read a line from the text file</strong></u></em><br /> <br /> With the function fgets, we can read a line from the text file. This method reads until the first line break (but not including the line break).<br /> <br /> <br /> <html><br /> <br /> <head><br /> <title>Reading from text files</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> $f = fopen("unitednations.txt", "r");<br /> <br /> // Read line from the text file and write the contents to the client<br /> echo fgets($f);<br /> <br /> fclose($f);<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> <em><u><strong>Example 2: Read all lines from the text file</strong></u></em><br /> <br /> <br /> <html><br /> <br /> <head><br /> <title>Reading from text files</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> $f = fopen("unitednations.txt", "r");<br /> <br /> // Read line by line until end of file<br /> while(!feof($f)) {<br /> echo fgets($f) . "<br />";<br /> }<br /> <br /> fclose($f);<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> In the example, we loop through all the lines and use the function feof (for end-of-file) to check if you are at the end of the file. If this is not the case ("!" - see lesson 6), the line is written.<br /> <br /> Instead of looping through all the lines, we could have achieved the same result with the function fread. If you work with very large text files with thousands of lines, be aware that the fread function uses more resources than the fgets function. For smaller files, it makes very little difference.<br /> <br /> <em><u><strong>Example 3: A simple link directory</strong></u></em><br /> <br /> As mentioned at the beginning of this lesson, text files can be excellent for data storage. This is illustrated in the next example where we create a simple link directory from the contents of the text file unitednations.txt.<br /> <br /> The file is systematically written with the name of the program, then a comma, and then the domain. As you can probably imagine, more information could easily be stored in this comma-separated data file.<br /> <br /> To get the information in each line, we use an array. See Lesson 8 for more information on arrays.<br /> <br /> <br /> <html><br /> <head><br /> <title>Reading from text files</title><br /> <br /> </head><br /> <body><br /> <br /> <?php<br /> $f = fopen("unitednations.txt", "r");<br /> <br /> // Read line by line until end of file<br /> while (!feof($f)) {<br /> <br /> // Make an array using comma as delimiter<br /> $arrM = explode(",",fgets($f));<br /> <br /> // Write links (get the data in the array)<br /> echo "<li><a href='http://" . $arrM[1] . "'>" . $arrM[0]. "</a></li>";<br /> <br /> }<br /> <br /> fclose($f);<br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> Quite handy, right? In principle, you could now just expand the text file with hundreds of links or perhaps expand your directory to also include address information.<br /> <br /> In the next lesson, we will look at how to write to a text file.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 14: Filesystem</strong></u><br /> <br /> With PHP, you can access the server's filesystem. This allows you to manipulate folders and text files in PHP scripts.<br /> <br /> For example, you can use PHP to read or write a text file. Or you can list all files in a specified folder. There are many possibilities and PHP can save you lots of tedious work.<br /> <br /> Here, we'll look at how you can use PHP to work with folders and files. The goal is to give you a quick overview. In the next lessons, we will look more closely at the different possibilities. We will not go through all the different possibilities. Again, see the documentation for a complete listing.<br /> <br /> <strong>filemtime</strong><br /> Returns the time for which the contents of a file was last edited<br /> <strong>fileatime</strong><br /> Returns the time when a file was last accessed / opened<br /> <strong>filesize</strong><br /> Returns the size of a file in bytes.<br /> <br /> <br /> <html><br /> <br /> <head><br /> <title>Filesystem</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> // Find and write properties<br /> echo "<h1>file: lesson14.php</h1>";<br /> echo "<p>Was last edited: " . date("r", filemtime("lesson14.php"));<br /> echo "<p>Was last opened: " . date("r", fileatime("lesson14.php"));<br /> echo "<p>Size: " . filesize("lesson14.php") . " bytes";<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> <strong>Folders</strong><br /> <br /> PHP also allows you to work with folders on the server. We will not go through all the different possibilities - only show an example. Again, see the documentation for more information.<br /> <br /> <strong>opendir</strong><br /> Opens a specified folder.<br /> <strong>readdir</strong><br /> Returns the filename of the next file in the open folder<br /> <strong>closedir</strong><br /> Closes a specified folder.<br /> <br /> The example below lists the contents of the folder "tutorials/php/".<br /> <br /> <br /> <html><br /> <head><br /> <title>FileSystemObject</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> // Opens the folder<br /> $folder = opendir("../../tutorials/php/");<br /> <br /> // Loop trough all files in the folder<br /> while (readdir($folder) != "") {<br /> echo readdir($folder) . "<br />";<br /> }<br /> <br /> // Close folder<br /> $folder = closedir($folder);<br /> <br /> ?><br /> <br /> </body><br /> <br /> </html><br /> <br /> <br /> In the example the directory "../../tutorials/php/" is first opened. Then a loop is used to write the name of the next file in the folder as long as there are more files. At the end, the folder is closed.<br /> <br /> In the next lessons, we will look at how to read from and write to a text file.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 13: Cookies</strong></u><br /> <br /> How and what kind of information websites are collecting from their users, and especially how they use it, is a hot topic. Cookies are often mentioned as an example of how information is collected and pose a threat to your privacy. But are there reasons to be worried? Judge for yourself. Once you have gone through this lesson, you will know what can be done with cookies.<br /> <br /> <em><strong>What is a cookie?</strong></em><br /> <br /> A cookie is a small text file in which a website can store different information. Cookies are saved on the user's hard drive and not on the server.<br /> <br /> Most cookies expire (delete themselves) after a predetermined time period, which can range from one minute to several years. But the user can also identify and delete any cookies on his/her computer.<br /> <br /> Most browsers, such as Microsoft Internet Explorer, Mozilla Firefox and Google Chrome, can be configured to let the user choose whether or not he/she will accept a cookie. But then, why not just say no to all cookies? It is possible. But many websites would not work as intended without cookies, since cookies in many contexts are used to improve the usability and functionality of the website.<br /> <br /> <em><strong>How is information stored in a cookie?</strong></em><br /> <br /> It's easy to set or modify a cookie in PHP with setcookie. In the first example, we will create a cookie and set the value.<br /> <br /> First, you need a name for the cookie. In this example we will use the name "HTMLTest". Next, you set the value of the cookie like this:<br /> <br /> <br /> <?php<br /> <br /> // Setting the cookie<br /> setcookie("HTMLTest", "This is a test cookie"); <br /> <br /> ?><br /> <br /> <br /> By default, a cookie is kept untill the browser is closed, but it can easily be modified by adding another parameter setting the expiry time:<br /> <br /> <br /> <?php<br /> <br /> // Setting the cookie<br /> setcookie("Name", "C. Wing, time()+3600); <br /> setcookie("Interests", "plane spotting", time()+3600);<br /> <br /> ?><br /> <br /> <br /> "Time()+3600" specified that the cookie should expire in 3600 seconds (60 minutes) from now.<br /> <br /> In the example above, we stored information about a user's name and interests. This information can, for example, be useful to target the website specifically for the individual visitor.<br /> <br /> <em><strong>How do you retrieve the value of a cookie?</strong></em><br /> <br /> To get the value of the cookie, $_COOKIE is used. For example, if we need the information from the example above, we do it like this:<br /> <br /> <br /> <?php<br /> <br /> // Retrieve values from the cookie<br /> $strName = $_COOKIE["Name"]; <br /> $strInterest = $_COOKIE["Interest"];<br /> <br /> // Write to the client<br /> echo "<p>" . strName . "</p>" <br /> echo "<p>Your interest is . " strInterest . "</p>"<br /> <br /> ?><br /> <br /> <br /> <em><strong>Who can read the cookie?</strong></em><br /> <br /> By default, a cookie can be read at the same second-level domain (e.g. html.net) as it was created. But by using the parameters domain and path, you can put further restrictions on the cookie using the following syntax:<br /> <br /> <br /> setcookie(name, value, expiration time, path, domain);<br /> <br /> <br /> Let us look at an example:<br /> <br /> <br /> <?php<br /> <br /> // Setting the cookie: name, value, expiration time, path, domain<br /> setcookie("Name", "C. Wing", time()+60*60*24*365, "/tutorials/php/", "www.html.net"); <br /> ?><br /> <br /> <br /> In the example above, we set a cookie called "Name" with the value "C. Wing." The cookie expires after one year (60 seconds * 60 minutes * 24 hours * 365 days) and can be read only by sites located in the directory "/tutorials/php/" on the (sub-)domain "www.html.net".<br /> <br /> Example of a cookie<br /> <br /> We can try to save a sample cookie on your computer and then see how it looks.<br /> <br /> The following code sets the cookie:<br /> <br /> <br /> <?php<br /> <br /> // Setting the cookie<br /> setcookie("HTMLTest", "This text is in a cookie!", time()+60*60*24, "/tutorials/php/", "www.html.net"); <br /> <br /> // Write the information to the client<br /> echo $_COOKIE ["HTMLTest"]; <br /> <br /> ?><br /> <br /> <br /> The cookie is being placed on your hard drive. Depending on what operating system you use, your cookies may be saved in different places. Once you find them, they will probably look like this:<br /> <br /> See Figure 1<br /> <br /> As you can see, a cookie is a normal text file that can be open with Notepad, for example. The contents of the cookie we have just created will probably look something like this:<br /> <br /> <br /> HTMLTest TEXT=This+text+is+in+a+cookie% 21 www.html.net/tutorials/php 0 80973619229399148 4216577264 29399141 *<br /> <br /> <br /> We will not go into detail with the different codes, but simply note that the user has full control over cookies on his/her computer.<br /> <br /> In this lesson, we have looked at what cookies can do but not what they can be used for. It's a common concern that some sites use cookies for inappropriate activities. But in most cases, cookies are used to make sites more user-friendly or relevant for the individual users.<br /> <br /> If you choose to use cookies on your site, it might be a good idea to tell your users that your site uses cookies. This can, for example, be communicated in a privacy policy or registration process.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 12: Sessions</strong></u><br /> <br /> When you visit a website, you do a number of different things. You click from one page to another. Perhaps you also fill out a form or purchase a product.<br /> <br /> As a web developer, such information is of great importance to developing successful web solutions.<br /> <br /> Suppose, for example, that you want to make a site where some pages are protected with login and password. To make this protection effective, the password-protected pages should have access to information on whether the user has logged in at an earlier time. You must, in other words, be able to "remember" what the user did earlier.<br /> <br /> This is exactly what this lesson is about - how you can use sessions in PHP to store and retrieve information during a user's visit to your site.<br /> <br /> <em><u><strong>Session</strong></u></em><br /> <br /> PHP session allows you to manage information about a user's session. You can write smart applications that can identify and gather information about users.<br /> <br /> A session can begin in different ways. We will not go into technical details here but focus on the case where a session starts by a value being stored. A session ends/dies if the user hasn't requested any pages within in a certain timeframe (by the standard 20 minutes). Of course, you can also always end/kill a session in your script.<br /> <br /> Let us say that 50 people are clicking around on the same site, e.g. a web shop, at the same time. Information on what each of them have in their shopping cart would best be stored in a session. In order to identify the individual users, the server uses a unique user ID that is stored in a cookie. A cookie is a small text file stored on the user's computer (more about cookies in lesson 13). Therefore, sessions often require support of cookies in the user's browser.<br /> <br /> <em><strong>An example of using sessions</strong></em><br /> <br /> When you requested this page, I stored the current time in a session. I did this so that I can now show you an example of how a session works.<br /> <br /> I named the item "StartTime" and stored it by adding the following line in my PHP script:<br /> <br /> <br /> <?php<br /> <br /> session_start();<br /> $_SESSION["StartTime"] = date("r");<br /> <br /> ?><br /> <br /> <br /> Thereby, a session was started. As described above, each session is given an ID by the server.<br /> <br /> Your session has the following ID: 031550a83a99497774cd7e3deb4cb52b<br /> <br /> At any time, I can call the "StartTime" from the session by writing:<br /> <br /> <br /> <?php<br /> <br /> session_start();<br /> echo $_SESSION["StartTime"];<br /> <br /> ?><br /> <br /> <br /> Which would reveal that the page was requested at Wed, 01 Feb 2012 07:02:57 +0100 (according to the clock on this web server).<br /> <br /> But what is interesting is that the information remains in the session, even after you have left this page. The information will follow you until your session ends.<br /> <br /> By default, a session lasts till the user closes the browser, then it dies automatically. But if you want to stop a session, it can always be killed in this way:<br /> <br /> <br /> <?php<br /> <br /> session_destroy();<br /> <br /> ?><br /> <br /> <br /> Let us try to look at another example where sessions are used: a password solution.<br /> <br /> <em><strong>Login system with sessions</strong></em><br /> <br /> In the following example, we will make a very simple login system. We will use many of the things we have learned in previous lessons.<br /> <br /> The first thing we need is a form where people can enter their username and password. It could look like this:<br /> <br /> <br /> <html><br /> <head><br /> <title>Login</title><br /> <br /> </head><br /> <body><br /> <form method="post" action="login.php"><br /> <br /> <p>Username: <input type="text" name="username" /></p><br /> <p>Password: <input type="text" name="password" /></p><br /> <br /> <p><input type="submit" value="Let me in" /></p><br /> <br /> </form><br /> </body><br /> </html><br /> <br /> <br /> <br /> Then we create the file: login.php.<br /> <br /> In this file, we check whether it is the correct username and password that has been entered. If that is the case, we set a session that says that this user is logged in with the correct username and password.<br /> <br /> <html><br /> <br /> <head><br /> <title>Login</title><br /> <br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> // Check if username and password are correct<br /> if ($_POST["username"] == "php" && $_POST["password"] == "php") {<br /> <br /> // If correct, we set the session to YES<br /> session_start();<br /> $_SESSION["Login"] = "YES";<br /> echo "<h1>You are now logged correctly in</h1>";<br /> echo "<p><a href='document.php'>Link to protected file</a><p/>";<br /> <br /> }<br /> else {<br /> <br /> // If not correct, we set the session to NO<br /> session_start();<br /> $_SESSION ["Login"] = "NO";<br /> echo "<h1>You are NOT logged correctly in </ h1>";<br /> echo "<p><a href='document.php'>Link to protected file</a></p>";<br /> <br /> }<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> <br /> In the protected files, we want to check whether the user is logged in properly. If this is not the case, the user is sent back to the login form. This is how the protection is made:<br /> <br /> <br /> <?php<br /> <br /> // Start up your PHP Session<br /> session_start();<br /> <br /> // If the user is not logged in send him/her to the login form<br /> if ($_SESSION["Login"] != "YES") {<br /> header("Location: form.php");<br /> }<br /> <br /> ?><br /> <br /> <html><br /> <head><br /> <title>Login</title><br /> </head><br /> <br /> <body><br /> <h1>This document is protected</h1><br /> <br /> <p>You can only see it if you are logged in.</p><br /> </body><br /> </html><br /> <br /> <br /> <a href="http://www.html.net/tutorials/php/lesson12_ex1.php">Click here to test the login system</a><br /> <br /> Now you've been introduced to the Session object. In the next lesson, we are still working in the same area but will take a closer look at cookies.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 11: Passing variables with forms</strong></u><br /> <br /> Interactive websites require input from users. One of the most common ways to get input is with forms.<br /> <br /> In this lesson, we will look at how to build forms and process inputs on the server.<br /> <br /> <strong><form></strong><br /> <br /> When you code a form, there are two particular important attributes: action and method.<br /> <br /> <strong>action</strong><br /> Is used to enter the URL where the form is submitted. It would be the PHP file that you want to handle the input.<br /> <strong>method</strong><br /> Can either have the value "post" or "get", which are two different methods to pass data. At this point, you don't need to know much about the difference, but with "get", the data is sent through the URL, and with "post", the data is sent as a block of data through standard input service (STDIN). In the last lesson, we looked at how data is retrieved through the URL using $_GET. In this lesson, we look at how data submitted through a form using the method "post" is retrieved.<br /> <br /> <em><strong>An HTML page with a form</strong></em><br /> <br /> The page that contains the form doesn't need to be a PHP file (but it can be). It need not even be on the same site as the file that will receive the data.<br /> <br /> In our first example, we will look at a very simple form with one text field:<br /> <br /> <br /> <html><br /> <head><br /> <title>Form</title><br /> </head><br /> <body><br /> <br /> <h1>Enter your name</h1><br /> <br /> <form method="post" action="handler.php"><br /> <input type="text" name="username"><br /> <input type="submit"><br /> </form><br /> <br /> </body><br /> </html><br /> <br /> <br /> <br /> The result in the browser is a form:<br /> <br /> See Figure 1<br /> <br /> Now we come to the fun part: receiving and handling the data with PHP.<br /> <br /> Requesting form data with PHP<br /> <br /> When you need to request data submitted through a form (post method), you use $_POST:<br /> <br /> <br /> $_POST["fieldname"];<br /> <br /> <br /> Which returns the value of a field in the form. Let us try to use it in an example.<br /> <br /> First create a page with a form as above. Then make a PHP page named "handler.php" (notice that this is the name of the page we wrote in the action attribute in our <form>).<br /> <br /> The file "handler.php" shall have the following content:<br /> <br /> <br /> <html><br /> <head><br /> <title>Form</title><br /> </head><br /> <br /> <body><br /> <br /> <?php<br /> <br /> echo "<h1>Hello " . $_POST["username"] . "</h1>";<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> <em><strong>User input and conditions</strong></em><br /> <br /> In the next example, we will try to use user input to create conditions. First, we need a form:<br /> <br /> <br /> <html><br /> <head><br /> <title>Form</title><br /> </head><br /> <body><br /> <br /> <form method="post" action="handler.php"><br /> <br /> <p>What is your name:</p><br /> <input type="text" name="username"></p><br /> <br /> <p>What is your favorite color:<br /> <input type="radio" name="favoritecolor" value="r" /> Red<br /> <input type="radio" name="favoritecolor" value="g" /> Green<br /> <input type="radio" name="favoritecolor" value="b" /> Blue </p><br /> <br /> <input type="submit" value="Submit" /><br /> <br /> </form><br /> <br /> </body><br /> </html><br /> <br /> <br /> Which will look like this in the browser:<br /> <br /> See Figure 2<br /> <br /> Now we will use these inputs to create a page that automatically changes background color according to what the user's favorite color is. We can do this by creating a condition (see lesson 6) that uses the data the user has filled out in the form.<br /> <br /> <?php<br /> <br /> $strHeading = "<h1>Hello " . $_POST["username"] . "</h1>";<br /> <br /> switch ($_POST["favoritecolor"]) {<br /> case "r":<br /> $strBackgroundColor = "rgb(255,0,0)";<br /> break;<br /> case "g";<br /> $strBackgroundColor = "rgb(0,255,0)";<br /> break;<br /> case "b":<br /> $strBackgroundColor = "rgb(0,0,255)";<br /> break;<br /> default:<br /> $strBackgroundColor = "rgb(255,255,255)";<br /> break;<br /> }<br /> <br /> ?><br /> <br /> <html><br /> <head><br /> <title>Form</title><br /> <br /> </head><br /> <body style="background: <? echo $strBackgroundColor; ?>;"><br /> <br /> <? echo $strHeading; ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> The background color will be white if the user has not chosen any favorite color in the form. This is done by using default to specify what should happen if none of the above conditions are met.<br /> <br /> But what if the user does not fill out his name? Then it only says "Hello" in the title. We will use an extra condition to change that.<br /> <br /> <br /> <?php<br /> <br /> $strUsername = $_POST["username"];<br /> <br /> if ($strUsername != "") {<br /> $strHeading = "<h1>Hello " . $_POST["username"] . "</h1>";<br /> }<br /> else {<br /> $strHeading = "<h1>Hello stranger!</h1> ";<br /> }<br /> <br /> switch ($_POST["favoritecolor"]) {<br /> case "r":<br /> $strBackgroundColor = "rgb(255,0,0)";<br /> break;<br /> case "g";<br /> $strBackgroundColor = "rgb(0,255,0)";<br /> break;<br /> case "b":<br /> $strBackgroundColor = "rgb(0,0,255)";<br /> break;<br /> default:<br /> $strBackgroundColor = "rgb(255,255,255)";<br /> break;<br /> }<br /> <br /> ?><br /> <br /> <html><br /> <br /> <head><br /> <br /> <title>Form</title><br /> </head><br /> <body style="background: <? echo $strBackgroundColor; ?>;"><br /> <br /> <? echo $strHeading; ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> In the example above, we use a condition to validate the information from the user. In this case, it might not be so important if the user did not write his name. But as you code more and more advanced stuff, it's vital that you take into account that the user may not always fill out forms the way you had imagined.<br /> <br /> <u><strong>Example: contact form</strong></u><br /> <br /> With your new knowledge of PHP and forms, you are able to create a contact form using the function mail, which has the following syntax:<br /> <br /> <br /> mail(to, subject, message);<br /> <br /> <br /> First, we need a simple HTML form:<br /> <br /> <br /> <html><br /> <head><br /> <title>Contact form</title><br /> </head><br /> <body><br /> <br /> <h1>Contact form</h1><br /> <br /> <form method="post" action="handler.php"><br /> <p>Subject:<br /><input type="text" name="subject" /></p><br /> <p>Message:<br /><textarea name="message"></textarea></p><br /> <input type="submit"><br /> </form><br /> <br /> </body><br /> </html><br /> <br /> <br /> Next we need a PHP script to send the users input:<br /> <br /> <br /> <html><br /> <head><br /> <title>Functions</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> // Recipient (change to your e-mail address)<br /> $strEmail = "[email protected]";<br /> <br /> // Get user inputs<br /> $strSubject = $_POST["subject"];<br /> $strMessage = $_POST["message"];<br /> <br /> mail($strEmail,$strSubject,$strMessage);<br /> echo "Mail Sent.";<br /> <br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> Please note that the example will only work if you have access to a mail server. By default, this is not the case in XAMPP and most free hosts. Also, some hosts may require that you include a from header, which is done with an extra parameter:<br /> <br /> <br /> mail("[email protected]", "Test", "This is a test mail", "From: [email protected]");<br /> <br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 10: Passing variables in a URL</strong></u><br /> <br /> When you work with PHP, you often need to pass variables from one page to another. This lesson is about passing variables in a URL.<br /> <br /> <em><strong>How does it work?</strong></em><br /> <br /> Maybe you have wondered why some URLs look something like this:<br /> <br /> <br /> <a href="http://html.net/page.php?id=1254"><strong>http://html.net/page.php?id=1254</strong></a><br /> <br /> <br /> <em><strong>Why is there a question mark after the page name?</strong></em><br /> <br /> The answer is that the characters after the question mark are an HTTP query string. An HTTP query string can contain both variables and their values. In the example above, the HTTP query string contains a variable named "id", with the value "1254".<br /> <br /> <u><em><strong>Here is another example:</strong></em></u><br /> <br /> <br /> <a href="http://html.net/page.php?name=Joe"><strong>http://html.net/page.php?name=Joe</strong></a><br /> <br /> <br /> Again, you have a variable ("name") with a value ("Joe").<br /> <br /> <em><strong>How to get the variable with PHP?</strong></em><br /> <br /> Let's say you have a PHP page named people.php. Now you can call this page using the following URL:<br /> <br /> <br /> people.php?name=Joe<br /> <br /> <br /> With PHP, you will be able to get the value of the variable 'name' like this:<br /> <br /> <br /> $_GET["name"]<br /> <br /> <br /> So, you use $_GET to find the value of a named variable. Let's try it in an example:<br /> <br /> <br /> <html><br /> <head><br /> <title>Query string</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> // The value of the variable name is found<br /> echo "<h1>Hello " . $ _GET["name"] . "</h1>";<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> When you look at the example above, try to replace the name "Joe" with your own name in the URL and then call the document again! Quite nice, eh?<br /> <br /> <em><strong>Several variables in the same URL</strong></em><br /> <br /> You are not limited to pass only one variable in a URL. By separating the variables with &, multiple variables can be passed:<br /> <br /> <br /> people.php?name=Joe&age=24<br /> <br /> <br /> This URL contains two variables: name and age. In the same way as above, you can get the variables like this:<br /> <br /> <br /> $_GET["name"]<br /> $_GET["age"]<br /> <br /> <br /> Let's add the extra variable to the example:<br /> <br /> <br /> <html><br /> <head><br /> <title>Query string </title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> // The value of the variable name is found<br /> echo "<h1>Hello " . $_GET["name"] . "</h1>";<br /> <br /> // The value of the variable age is found<br /> echo "<h1>You are " . $_GET["age"] . " years old </h1>";<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> Now you have learned one way to pass values between pages by using the URL. In the next lesson, we'll look at another method: forms.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 9: Functions</strong></u><br /> <br /> In previous lessons you have learned to use functions like date() and array(). In this lesson, you will learn to create your own functions using function.<br /> <br /> <em><strong>What is a function?</strong></em><br /> <br /> A function process inputs and returns an output. It can be useful if, for example, you have a wide range of data you have processed or if you have calculations or routines that must be performed many times.<br /> <br /> A function has the following syntax:<br /> <br /> <br /> Function Name(list of parameters) {<br /> Statement<br /> }<br /> <br /> <br /> This way, we can make a very simple function that can add the value 1 to a number. It could look like this:<br /> <br /> function AddOne($x) {<br /> $x = $x + 1;<br /> echo $x;<br /> }<br /> <br /> <br /> <br /> Our function is named AddOne and must be called with a number - e.g. 34....<br /> <br /> echo AddOne(34);<br /> <br /> <br /> ... which (surprise!) will return 35.<br /> <br /> The example above processes a number, but functions can work with text, dates or anything else. You can also create functions that are called by many different parameters. In this lesson you will see different examples of functions.<br /> <br /> <u><em><strong>Example 1: Function with more parameters</strong></em></u><br /> <br /> As mentioned above, you can easily create a function that can be called with more parameters. In the next example, we'll create a function that is called with three numbers and then returns the value of the three numbers added together:<br /> <br /> <br /> <html><br /> <head><br /> <title>Functions</title><br /> <br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> function AddAll($number1,$number2,$number3) {<br /> $plus = $number1 + $number2 + $number3;<br /> return $plus;<br /> }<br /> <br /> echo "123 + 654 + 9 equals " . AddAll(123,654,9);<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> Ok. Now that was almost too simple! But the point was just to show you that a function can be called with more parameters.<br /> <br /> <u><em><strong>Example 2: English date and time</strong></em></u><br /> <br /> Let us try to make a slightly more complex function. A function that's called with a date and time returns it in the format: Wednesday, 15 February, 2012, 10:00:00 AM<br /> <br /> <br /> <html><br /> <head><br /> <title>Functions</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> function EnglishDateTime($date) {<br /> <br /> // Array with the English names of the days of the week<br /> $arrDay = array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");<br /> <br /> // Array with the English names of the months<br /> $arrMonth = array("","January","February","March","April","May","June","July","August","September","October","November","December");<br /> <br /> // The date is constructed<br /> $EnglishDateTime = $arrDay[(date("w",$date))] . ", " . date("d",$date);<br /> $EnglishDateTime = $EnglishDateTime . " " . $arrMonth[date("m",$date)] . " " . date("Y",$date);<br /> $EnglishDateTime = $EnglishDateTime . ", " . date("H",$date) . ":" . date("i",$date);<br /> <br /> return $EnglishDateTime;<br /> <br /> }<br /> <br /> // Test function<br /> echo EnglishDateTime(time());<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> Please note how '$arrMonth' and '$EnglishDateTime' are constructed over several lines. This is done so that users with a low screen resolution can better see the example. The method has no effect on the code itself.<br /> <br /> The function above works on all web servers regardless of language. This means that you can use such a function if your website, for example, is hosted on a French server, but you want English dates.<br /> <br /> At this stage, we will not go into more depth with functions, but now you know a little about how functions work.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u><strong>Lesson 8: Arrays</strong></u><br /> <br /> In this lesson, we will look at what an array is, how it is used, and what it can do.<br /> <br /> Understanding arrays can be a little difficult in the beginning. But give it a try anyway... we've tried to make it as easy as possible.<br /> <br /> <em><strong>What is an array?</strong></em><br /> <br /> An array is a set of indexed elements where each has its own, unique identification number.<br /> <br /> Sound confusing? It's actually not that complicated.<br /> <br /> Imagine a list of words separated by commas. It is called a comma-separated list, and it could, for example, look like this:<br /> <br /> <br /> apples, pears, bananas, oranges, lemons<br /> <br /> <br /> Then try to imagine dividing the list at each comma. Next, give each section a unique identification number like this:<br /> <br /> <br /> What you see is an array. We can, for example, name the array "fruits". The idea is that we can access the array with a number and get a value back, like this:<br /> <br /> fruits(0) = apples<br /> fruits(1) = pears<br /> fruits(2) = bananas<br /> fruits(3) = oranges<br /> fruits(4) = lemons<br /> <br /> This is the idea behind arrays. Let us try to use it in practice.<br /> <br /> <em><strong>How do you use an array?</strong></em><br /> <br /> We will continue with the fruit example. Step by step, we will make it work as a real array. First, we set a variable equal to the list of fruits:<br /> <br /> <br /> <?php<br /> <br /> $fruitlist = "apples, pears, bananas, oranges, lemons";<br /> <br /> ?><br /> <br /> <br /> Next, we use the function explode to split the list at each comma:<br /> <br /> <br /> <?php<br /> <br /> $fruitlist = "apples, pears, bananas, oranges, lemons";<br /> <br /> $arrFruits = explode(",", $fruitlist);<br /> <br /> ?><br /> <br /> <br /> Voila! "$arrFruits" is now an array!<br /> <br /> Notice that we called the function explode with two arguments:<br /> <br /> the list that should be split<br /> and the delimiter - i.e., the character used to split (in this case a comma) - in quotation marks: ",".<br /> Here we use a comma as a delimiter, but you can use any character or word as a delimiter.<br /> <br /> Let us try to comment the script and put it into a PHP page:<br /> <br /> <br /> <html><br /> <head><br /> <title>Array</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> // Comma separated list<br /> $fruitlist = "apples, pears, bananas, oranges, lemons";<br /> <br /> // Create an array by splitting the list (with comma as delimiter)<br /> $arrFruits = explode(",", $fruitlist);<br /> <br /> // Write the values from our array<br /> echo "<p>The list of fruits:</p>";<br /> <br /> echo "<ul>";<br /> echo "<li>" . $arrFruits[0] . "</li>";<br /> echo "<li>" . $arrFruits[1] . "</li>";<br /> echo "<li>" . $arrFruits[2] . "</li>";<br /> echo "<li>" . $arrFruits[3] . "</li>";<br /> echo "<li>" . $arrFruits[4] . "</li>";<br /> echo "</ul>";<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> This example is very simple, and it might be a bit difficult to see the advantage of using an array for this particular task. But just wait... arrays can be used for many very useful things.<br /> <br /> <em><strong>Loop through an array</strong></em><br /> <br /> Back in lesson 5 you learned about loops. Now we will look at how you can loop through an array.<br /> <br /> When you know how many elements an array contains, it is not a problem defining the loop. You simply start with 0 and let the loop continue to the number of items available. In the example with the fruits, you would loop through the array like this:<br /> <br /> <br /> <html><br /> <head><br /> <title>Array</title><br /> <br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> // Comma separated list<br /> $fruitlist = "apples, pears, bananas, oranges, lemons";<br /> <br /> // Create an array by splitting the list (with a comma as delimiter)<br /> $arrFruits = explode (",", $fruitlist);<br /> <br /> echo "<p>The list of fruits:</p>";<br /> echo "<ul>";<br /> <br /> // Loop through the array $arrFruits<br /> for ($x=0; $x<=4; $x++) {<br /> echo "<li>" . $arrFruits[$x] . "</li>";<br /> }<br /> <br /> echo "</ul>";<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> As you can see, the variable $x (which increases from 0 to 4 in the loop) was used to call the array.<br /> <br /> <em><strong>How to find the size of an array</strong></em><br /> <br /> But what if we add another fruit to the list? Then our array will contain one element more - which will get the identification number 5. Do you see the problem? Then we need to change the loop, so it runs from 0 to 5, or else not all of the elements will be included.<br /> <br /> Wouldn't it be nice if we automatically could find out how many elements an array contains?<br /> <br /> That's exactly what we can do with the function foreach. Now we can make a loop that works regardless of the number of elements:<br /> <br /> <br /> <?php<br /> foreach ($arrFruits as $x) {<br /> echo $x;<br /> }<br /> ?><br /> <br /> <br /> This loop will work regardless of how many or few elements the array contains.<br /> <br /> <em><strong>Another example</strong></em><br /> <br /> Below is another example of how you can use an array to write the name of the month:<br /> <br /> <br /> <html><br /> <head><br /> <title>Array<title><br /> <br /> </head><br /> <body><br /> <br /> // Creates array with each month.<br /> // Creates array with the months. Note the comma before January - because there is no month with the number 0<br /> $arrMonths = array("","January","February","March","April","May","June","July","August","September","October","November","December");<br /> <br /> // Call the array with the number of the month - write to the client<br /> echo $arrMonths[date("m")];<br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> Notice that we use the function array instead of the function explode to create an array.<br /> <br /> Ok. Enough about arrays! In the next lesson, you'll learn how to write your own functions.<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u>PHP was originally created by Rasmus Lerdorf in 1995. The main implementation of PHP is now produced by The PHP Group and serves as the formal reference to the PHP language. PHP is free software released under the PHP License, which is incompatible with the GNU General Public License (GPL) due to restrictions on the usage of the term PHP</u><br /> <br /> <u><strong>Lesson 7: Comment your scripts</strong></u><br /> <br /> As you may have noticed, PHP scripts can easily look confusing. In this lesson, we cover why comments are important and how to insert them into your scripts.<br /> <br /> <em><strong>Why is it important to comment your scripts?</strong></em><br /> <br /> When you are coding, you are writing commands to a server/computer and need to use a highly formal language that may not clearly reflect your thoughts when making the script.<br /> <br /> Therefore, it can be difficult for others (or yourself) to understand how the script is structured, and thus hard to identify and correct errors in the script.<br /> <br /> Comments can be used to write short explanatory text in the script. The server completely ignores the comments, and the comments do not affect the actual functionality of the script.<br /> <br /> In the business world, it is often a requirement that scripts and programming are commented, otherwise it would be too risky for a company to take over a system in which it would be too difficult to find and correct errors.<br /> <br /> <em><strong>How do you insert comments?</strong></em><br /> <br /> It is quite easy to insert a comment. You simply start the comment with a double slash: "//".<br /> <br /> Take a look at this example from lesson 5, now with comments:<br /> <br /> <br /> <html><br /> <head><br /> <title>Loops</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> // Here we write color codes using three loops<br /> <br /> // Red can be between 0 and 255<br /> for ($intRed=0; $intRed<=255; $intRed=$intRed+30) {<br /> <br /> // Green can be between 0 and 255<br /> for ($intGreen=0; $ intGreen<=255; $intGreen=$intGreen+30) {<br /> <br /> // Blue can be between 0 and 255<br /> for ($ intBlue=0; $intBlue<=255; $intBlue=$intBlue+30) {<br /> <br /> // The color code is made on the form rgb(red,green,blue)<br /> $strColor = "rgb(" . $intRed . "," . $intGreen . "," . $intBlue . ")"<br /> <br /> // Now we write the color code to the client<br /> echo "<span style='color:" . $strColor . "'> " . $strColor . " </span>";<br /> <br /> // Closes the loops<br /> }<br /> }<br /> }<br /> <br /> ?><br /> <br /> <br /> For the sake of the example, we have included many extra comments, so it should be clear that you are far better off debugging a script with comments than without.<br /> <br /> Therefore, remember to comment your scripts!<br />
AMSSOI-Andhra Mahila Sabha School of Informatics
<u>PHP is a general-purpose server-side scripting language originally designed for Web development to produce dynamic Web pages. It is one of the first developed server-side scripting languages to be embedded into an HTML source document, rather than calling an external file to process data.</u><br /> <br /> <br /> <u><strong>Lesson 6: Conditions</strong></u><br /> <br /> Conditions are used to execute part of a script only if some predefined requirements (conditions) are fulfilled. For example, a condition could be that a date must be after January 1, 2012 or that a variable is greater than 7.<br /> <br /> <em><strong>If...</strong></em><br /> <br /> The first type of condition we will look at is if, which has the following syntax:<br /> <br /> <br /> if (condition) {<br /> statement<br /> }<br /> <br /> <br /> Again, the syntax is very close to ordinary English: If a condition is met, then execute something. Let's look at a simple example:<br /> <br /> <br /> <html><br /> <br /> <head><br /> <title>Loops </title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> $x = 2;<br /> <br /> if ($x > 1) {<br /> echo "<p>variable $x is greater than 1 </p>";<br /> }<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> <em><strong>if ... else ...</strong></em><br /> <br /> The next type of condition will want to look at is else , which may be presented in the following form:<br /> <br /> <br /> if (condition) {<br /> statement<br /> }<br /> else {<br /> statement<br /> }<br /> <br /> <br /> Again, the syntax is very close to ordinary English: if a condition is met execute something or else execute something else.<br /> <br /> In lesson 4, you learned how to find the number of a month. In the following example, we will use the month number in an if else condition to find out what season it is:<br /> <br /> <br /> <html><br /> <head><br /> <title>Conditions</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> if (date ("m") == 3) {<br /> echo "<p>Now it's spring!</p> ";<br /> }<br /> else {<br /> echo "<p>I do not know what season it is!</p> ";<br /> }<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> As you can see, this condition is not a particularly smart condition - it only works when it's March!<br /> <br /> However, there are plenty of ways to improve the condition and make it more precise. Below are listed comparison operators that can be used in the condition:<br /> <br /> == Equals<br /> < Less than<br /> > Greater than<br /> <= Less than or equal to<br /> >= Greater than or equal to<br /> != Not equal to<br /> <br /> In addition, there are some logical operators:<br /> <br /> && And<br /> || Or<br /> ! Not<br /> <br /> The operators can be used to develop more precise conditions, so now we can expand the above example to include all the spring months:<br /> <br /> <br /> <html><br /> <head><br /> <title>Conditions</title><br /> <br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> if (date("m") >= 3 && date("m") <= 5) {<br /> echo "<p> Now it's spring!</p> ";<br /> }<br /> else {<br /> echo "<p> Now it's either winter, summer or autumn!</p> ";<br /> }<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> <br /> Let's take a closer look at the extended condition:<br /> <br /> date("m") >= 3 && date("m") <= 5<br /> <br /> The condition can be translated into:<br /> <br /> <br /> If the month is greater than or equal to 3,<br /> and the month is less than or equal to 5<br /> <br /> <br /> Smart, eh? Operators play a significant role in many different parts of PHP.<br /> <br /> But it still only works with March, April and May. All other months are not yet covered by the condition. So let's try to develop the condition a little more.<br /> <br /> <em><strong>if ... elseif ... else...</strong></em><br /> <br /> Using elseif, we can expand the condition and make it work for all months:<br /> <br /> <br /> <html><br /> <head><br /> <title>Conditions</title><br /> <br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> if (date("m") >= 3 && date("m") <= 5) {<br /> echo "<p>Now it's spring!</p>";<br /> }<br /> <br /> elseif (date("m") >= 6 && date("m") <= 8) {<br /> echo "<p>Now it's summer!</p>";<br /> }<br /> <br /> elseif (date("m") >= 9 && date("m") <= 11) {<br /> echo "<p>Now it's autumn!</p>";<br /> }<br /> <br /> else {<br /> echo "<p>Now is winter!</p>";<br /> }<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> <br /> To write conditions is all about thinking logically and being methodical. The example above is pretty straightforward, but conditions can get very complex.<br /> <br /> <em><strong>switch ... case</strong></em><br /> <br /> Another way of writing conditions is to use the switch method:<br /> <br /> <br /> switch (expression) {<br /> <br /> case 1:<br /> statement<br /> break;<br /> case 2:<br /> statement<br /> break;<br /> default:<br /> statement<br /> break;<br /> }<br /> <br /> <br /> This method is based on an expression and then lists different "answers" or "values" with related statements. The easiest way to explain the method is to show an example.<br /> <br /> As you may remember from lesson 4, the function date("w") returns the current weekday. This can be used in an example where we write the name of the day (instead of a number):<br /> <br /> <br /> <html><br /> <head><br /> <title>Conditions</title><br /> </head><br /> <body><br /> <br /> <?php<br /> <br /> switch(date("w")) {<br /> <br /> case 1:<br /> echo "Now it's Monday";<br /> break;<br /> case 2:<br /> echo "Now it's Tuesday";<br /> break;<br /> case 3:<br /> echo "Now it's Wednesday";<br /> break;<br /> case 4:<br /> echo "Now it's Thursday";<br /> break;<br /> case 5:<br /> echo "Now it's Friday";<br /> break;<br /> case 6:<br /> echo "Now it's Saturday";<br /> break;<br /> default:<br /> echo "Now it's Sunday";<br /> break;<br /> <br /> }<br /> <br /> ?><br /> <br /> </body><br /> </html><br /> <br /> <br /> Often switch can be a good alternative to if else conditions. What you should use in a given situation depends on which method you find easiest and most logical. Making your scripts logical and clear can be a great challenge.<br /> <br /> In the next lesson, we will look at how you can add comments to your scripts to explain how they work. Good comments can be crucial if you or somebody else has to make changes in your codes at a later stage.<br /> <br />
Colleges are sharing lecture notes, study material, file, assignment etc.
Ask any study related doubt and get answered by college students and faculty.
College student sharing a great video to help peers study.
Access previous year papers for various courses.
Info. update by students of the respective college only.