Apr 21, 2011

PHP: POST & GET

PHP - POST & GET

Recall from the PHP Forms Lesson where we used an HTML form and sent it to a PHP web page for processing. In that lesson we opted to use the the post method for submitting, but we could have also chosen the get method. This lesson will review both transferring methods.

POST - Review

In our PHP Forms Lesson we used the post method. This is what the pertinent line of HTML code looked like:

HTML Code Excerpt:

This HTML code specifies that the form data will be submitted to the "process.php" web page using the POST method. The way that PHP does this is to store all the "posted" values into an associative array called "$_POST". Be sure to take notice the names of the form data names, as they represent the keys in the "$_POST" associative array.
Now that you know about associative arrays, the PHP code from "process.php" should make a litte more sense.

PHP Code Excerpt:

$quantity = $_POST['quantity'];
$item = $_POST['item'];
The form names are used as the keys in the associative array, so be sure that you never have two input items in your HTML form that have the same name. If you do, then you might see some problems arise.

PHP - GET

As we mentioned before, the alternative to the post method is get. If we were to change our HTML form to the get method, it would look like this:

HTML Code Excerpt:

The get method is different in that it passes the variables along to the "process.php" web page by appending them onto the end of the URL. The URL, after clicking submit, would have this added on to the end of it:
"?item=##&quantity=##"
The question mark "?" tells the browser that the following items are variables. Now that we changed the method of sending information on "order.html", we must change the "process.php" code to use the "$_GET" associative array.

PHP Code Excerpt:

$quantity = $_GET['quantity'];
$item = $_GET['item'];
After changing the array name the script will function properly. Using the get method displays the variable information to your visitor, so be sure you are not sending password information or other sensitive items with the get method. You would not want your visitors seeing something they are not supposed to!

Security Precautions

Whenever you are taking user input and using you need to be sure that the input is safe. If you are going to insert the data into a MySQL database, then you should be sure you have thought about preventing MySQL Injection. If you are going to make a user's input available to the public, then you should think about PHP htmlentities.

Apr 19, 2011

PHP functions - eregi

eregi() -   became deprecated starting PHP 5.3.0

hmmm... I've used this function many times.

Apr 12, 2011

Time and Date - PHP

PHP has the ability to dynamically generate the time and date. Using a simple line of code we are able to include this on our site, however it is important to know how the formatting works.



You can use the date function in conjunction with the time function to display this in the format of date ( format , time ) In our case we want the start time to be now, so we will call the time first. We will demonstrate many different types of formatting


 $b = time (); 
 print date("m/d/y",$b) . "
"; 

 print date("D, F jS",$b) . "
"; 

 print date("l, F jS Y",$b) . "
"; 

 print date("g:i A",$b) . "
"; 

 print date("r",$b) . "
"; 

 print date("g:i:s A D, F jS Y",$b) . "
"; 

 ?> 


There is different formats that can be used in the date feature. Below is a summary of the variable used in date, and what each does. They ARE CaSe sEnsItIVe:


DAYS 
d - day of the month 2 digits (01-31) 
j - day of the month (1-31) 
D - 3 letter day (Mon - Sun) 
l - full name of day (Monday - Sunday) 
N - 1=Monday, 2=Tuesday, etc (1-7) 
S - suffix for date (st, nd, rd) 
w - 0=Sunday, 1=Monday (0-6) 
z - day of the year (1=365)


WEEK 
W - week of the year (1-52)


MONTH 
F - Full name of month (January - December)
m - 2 digit month number (01-12) 
n - month number (1-12) 
M - 3 letter month (Jan - Dec) 
t - Days in the month (28-31)


YEAR
L - leap year (0 no, 1 yes)
o - ISO-8601 year number (Ex. 1979, 2006)
Y - four digit year (Ex. 1979, 2006)
y - two digit year (Ex. 79, 06)


TIME
a - am or pm
A - AM or PM
B - Swatch Internet time (000 - 999)
g - 12 hour (1-12)
G - 24 hour c (0-23)
h - 2 digit 12 hour (01-12)
H - 2 digit 24 hour (00-23)
i - 2 digit minutes (00-59)
s 0 2 digit seconds (00-59)


OTHER e - timezone (Ex: GMT, CST)
I - daylight savings (1=yes, 0=no)
O - offset GMT (Ex: 0200)
Z - offset in seconds (-43200 - 43200)
r - full RFC 2822 formatted date

Basic PHP Syntax video

http://video.about.com/php/Basic-PHP-Syntax.htm

Apr 8, 2011

Mysql Temporary tables

he temporary tables could be very useful in some cases to keep temporary data. The most important thing that should be knows for temporary tables is that they will be deleted when the current client session terminates.
Temporary tables where added in MySQL version 3.23. If you use an older version of MySQL than 3.23 you can't use temporary tables, but you can use heap tables.
As stated earlier temporary tables will only last as long as the session is alive. If you run the code in a PHP script, the temporary table will be destroyed automatically when the script finishes executing. If you are connected to the MySQl database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table.

Example

Here is an example showing you usage of temporary table. Same code can be used in PHP scripts using mysql_query() function.
mysql> CREATE TEMPORARY TABLE SalesSummary (
    -> product_name VARCHAR(50) NOT NULL
    -> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
    -> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
    -> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO SalesSummary
    -> (product_name, total_sales, avg_unit_price, total_units_sold)
    -> VALUES
    -> ('cucumber', 100.25, 90, 2);

mysql> SELECT * FROM SalesSummary;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
| cucumber     |      100.25 |          90.00 |                2 |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
When you issue a SHOW TABLES command then your temporary table would not be listed out in the list. Now if you will log out of the MySQL session and then you will issue a SELECT command then you will find no data available in the database. Even your temporary table would also not exist.

Dropping Temporary Tables:

By default all the temporary tables are deleted by MySQL when your database connection gets terminated. Still you want to delete them in between then you do so by issuing DROP TABLE command.
Following is the example on dropping a temproary table.
mysql> CREATE TEMPORARY TABLE SalesSummary (
    -> product_name VARCHAR(50) NOT NULL
    -> , total_sales DECIMAL(12,2) NOT NULL DEFAULT 0.00
    -> , avg_unit_price DECIMAL(7,2) NOT NULL DEFAULT 0.00
    -> , total_units_sold INT UNSIGNED NOT NULL DEFAULT 0
);
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO SalesSummary
    -> (product_name, total_sales, avg_unit_price, total_units_sold)
    -> VALUES
    -> ('cucumber', 100.25, 90, 2);

mysql> SELECT * FROM SalesSummary;
+--------------+-------------+----------------+------------------+
| product_name | total_sales | avg_unit_price | total_units_sold |
+--------------+-------------+----------------+------------------+
| cucumber     |      100.25 |          90.00 |                2 |
+--------------+-------------+----------------+------------------+
1 row in set (0.00 sec)
mysql> DROP TABLE SalesSummary;
mysql>  SELECT * FROM SalesSummary;
ERROR 1146: Table 'TUTORIALS.SalesSummary' doesn't exist

MYSQL index

A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records.
While creating index it should be considered that what are the columns which will be used to make SQL queries and create one or more indexes on those columns.
Practically, Indexes are also type of tables which keeps primary key or index field and a pointer to each record in to the actual table.
The users cannot see the indexes, they are just used to speed up queries and will be used by Database Search Engine to locate records very fast.
INSERT and UPDATE statements takes more time on tables having indexes where as SELECT statements become fast on those tables. The reason is that while doing insert or update, database need to inert or update index values as well.

Simple and Unique Index:

You can create a unique index on a table. A unique index means that two rows cannot have the same index value. Here is the syntax to create an Index on a table
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...);
You can use one or more columns to create an index. For example we can create an index on tutorials_tbl using tutorial_author
CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author)
You can creates a simple index on a table. Just omit UNIQUE keyword from the query to create simple index. Simple index allows duplicate values in a table.
If you want to index the values in a column in descending order, you can add the reserved word DESC after the column name:
mysql> CREATE UNIQUE INDEX AUTHOR_INDEX
ON tutorials_tbl (tutorial_author DESC)

ALTER command to add and drop INDEX:

There are four types of statements for adding indexes to a table:
  • ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) : This statement adds a PRIMARY KEY, which means that indexed values must be unique and cannot be NULL.
  • ALTER TABLE tbl_name ADD UNIQUE index_name (column_list):This statement creates an index for which values must be unique (with the exception of NULL values, which may appear multiple times).
  • ALTER TABLE tbl_name ADD INDEX index_name (column_list):This adds an ordinary index in which any value may appear more than once.
  • ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list):This creates a special FULLTEXT index that is used for text-searching purposes.
Here is the example to add index in an existing table.
mysql> ALTER TABLE testalter_tbl ADD INDEX (c);
You can drop any INDEX by using DROP clause along with ALTER command. Try out following example to drop above created index.
mysql> ALTER TABLE testalter_tbl DROP INDEX (c);
You can drop any INDEX by using DROP clause along with ALTER command. Try out following example to drop above created inde x.

ALTER Command to add and drop PRIMARY KEY:

You can add primary key as well in the same way. But make sure Primary Key works on columns which are NOT NULL.
Here is the example to add primary key in an existing table. This will make a column NOT NULL first and then add it as a primary key.
mysql> ALTER TABLE testalter_tbl MODIFY i INT NOT NULL;
mysql> ALTER TABLE testalter_tbl ADD PRIMARY KEY (i);
You can use ALTER command to drop a primary key as follows:
mysql> ALTER TABLE testalter_tbl DROP PRIMARY KEY;
To drop an index that is not a PRIMARY KEY, you must specify the index name.

Displaying INDEX Information:

You can use SHOW INDEX command to list out all the indexes associated with a table. Vertical-format output (specified by \G) often is useful with this statement, to avoid long line wraparound:
Try out following example:
mysql> SHOW INDEX FROM table_name\G
........

MYSQL ALTER command

MySQL ALTER command is very useful when you want to change a name of your table, any table field or if you want to add or delete an existing column in a table.
Lets begin with creation of a table called testalter_tbl
root@host# mysql -u root -p password;
Enter password:*******
mysql> use TUTORIALS;
Database changed
mysql> create table testalter_tbl
    -> (
    -> i INT,
    -> c CHAR(1)
    -> );
Query OK, 0 rows affected (0.05 sec)
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| i     | int(11) | YES  |     | NULL    |       |
| c     | char(1) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

Dropping, Adding, or Repositioning a Column:

Suppose you want to drop an existing column i from above MySQL table then you will use DROP clause along with ALTER command as follows
mysql> ALTER TABLE testalter_tbl  DROP i;
DROP will not work if the column is the only one left in the table.
To add a column, use ADD and specify the column definition. The following statement restores the i column to testalter_tbl
mysql> ALTER TABLE testalter_tbl ADD i INT;
After issuing this statement, testalter will contain the same two columns that it had when you first created the table, but will not have quite the same structure. That's because new columns are added to the end of the table by default. So even though i originally was the first column in mytbl, now it is the last one:
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| c     | char(1) | YES  |     | NULL    |       |
| i     | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
To indicate that you want a column at a specific position within the table, either use FIRST to make it the first column, or AFTER col_name to indicate that the new column should be placed after col_name. Try the following ALTER TABLE statements, using SHOW COLUMNS after each one to see what effect each one has:
ALTER TABLE testalter_tbl DROP i;
ALTER TABLE testalter_tbl ADD i INT FIRST;
ALTER TABLE testalter_tbl DROP i;
ALTER TABLE testalter_tbl ADD i INT AFTER c;
The FIRST and AFTER specifiers work only with the ADD clause. This means that if you want to reposition an existing column within a table, you first must DROP it and then ADD it at the new position.

Changing a Column Definition or Name:

To change a column's definition, use MODIFY or CHANGE clause along with ALTER command. For example, to change column c from CHAR(1) to CHAR(10), do this:
mysql> ALTER TABLE testalter_tbl MODIFY c CHAR(10);
With CHANGE, the syntax is a bit different. After the CHANGE keyword, you name the column you want to change, then specify the new definition, which includes the new name. Try out following example:
mysql> ALTER TABLE testalter_tbl CHANGE i j BIGINT;
If you now use CHANGE to convert j from BIGINT back to INT without changing the column name, the statement be as expected:
mysql> ALTER TABLE testalter_tbl CHANGE j j INT;

The Effect of ALTER TABLE on Null and Default Value Attributes:

When you MODIFY or CHANGE a column, you can also specify whether or not the column can contain NULL values, and what its default value is. In fact, if you don't do this, MySQL automatically assigns values for these attributes.
Here is the example where NOT NULL column will have value 100 by default.
mysql> ALTER TABLE testalter_tbl 
    -> MODIFY j BIGINT NOT NULL DEFAULT 100;
If you don't use above command then MySQL will fill up NULL values in all the columns.

Changing a Column's Default Value:

You can change a default value for any column using ALTER command. Try out following example.
mysql> ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| c     | char(1) | YES  |     | NULL    |       |
| i     | int(11) | YES  |     | 1000    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
You can remove default constraint from any column by using DROP clause along with ALTER command.
mysql> ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;
mysql> SHOW COLUMNS FROM testalter_tbl;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| c     | char(1) | YES  |     | NULL    |       |
| i     | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

Changing a Table Type:

You can use a table type by using TYPE clause alongwith ALTER command. Try out following example to change testalter_tbl to MYISAM table type.
To find out the current type of a table, use the SHOW TABLE STATUS statement.
mysql> ALTER TABLE testalter_tbl TYPE = MYISAM;
mysql>  SHOW TABLE STATUS LIKE 'testalter_tbl'\G
*************************** 1. row ****************
           Name: testalter_tbl
           Type: MyISAM
     Row_format: Fixed
           Rows: 0
 Avg_row_length: 0
    Data_length: 0
Max_data_length: 25769803775
   Index_length: 1024
      Data_free: 0
 Auto_increment: NULL
    Create_time: 2007-06-03 08:04:36
    Update_time: 2007-06-03 08:04:36
     Check_time: NULL
 Create_options:
        Comment:
1 row in set (0.00 sec)

Renaming a Table:

To rename a table, use the RENAME option of the ALTER TABLE statement. Try out following example to rename testalter_tbl to alter_tbl
mysql> ALTER TABLE testalter_tbl RENAME TO alter_tbl;
You can use ALTER command to create and drop INDEX on a MySQL file. We will see this feature in next chapter.