WWW PHP Tutorials Info
WWW PHP Tutorials Info
2. Introduction
For many people, the main reason for learning a scripting language like PHP is for the interaction with databases that it can offer. We will look at how to use PHP and MySQL database to store information on the web and include it into your website.
converted by Web2PDFConvert.com
Open the file in our browser and scroll down through all this information. If you find a section about MySQL then you will know that MySQL is installed.
3.2.1. Fields
MySQL supports a number of column types, which may be grouped into three categories: numeric types, date and time types, and string (character) types. This section first gives an overview of the types available: MySQL field types
Use for A very small integer A small integer A medium-size integer A normal-size integer
Size The signed range is 128 to 127. The unsigned range is 0 to 255 The signed range is 32768 to 32767. The unsigned range is 0 to 65535 The signed range is 8388608 to 8388607. The unsigned range is 0 to 16777215 The signed range is 2147483648 to 2147483647. The unsigned range is 0 to 4294967295
A large integer
The signed range is 9223372036854775808 to 9223372036854775807. The unsigned range is 0 to 18446744073709551615 Ranges are 3.402823466E+38 to 1.175494351E-38, 0 and 1.175494351E-38 to 3.402823466E+38. If the number of Decimals is not set or <= 24 it is a single-precision floating point number
FLOAT
A small (singleprecision) floatingpoint number. Cannot be unsigned A normal-size (double-precision) floating-point number. Cannot be unsigned An unpacked floatingpoint number. Cannot be unsigned
Ranges are -1.7976931348623157E+308 to -2.2250738585072014E-308, 0 and 2.2250738585072014E-308 to 1.7976931348623157E+308. If the number of Decimals is not set or 25 <= Decimals <= 53 stands for a doubleprecision floating point number
Behaves like a CHAR column: "unpacked" means the number is stored as a string, using one character for each digit of the value. The decimal point, and, for negative numbers, the '-' sign is not counted in Length. If Decimals is 0, values will have no decimal point or fractional part. The maximum range of DECIMAL values is the same as for DOUBLE , but the actual range for a given DECIMAL column may be constrained by the choice of Length and Decimals. If Decimals is left out it's set to 0. If Length is left out it's set to 10. Note that in MySQL 3.22 the Length includes the sign and the decimal point The supported range is 1000-01-01 to 9999-12-31. MySQL displays DATE values in YYYY-MM-DD format The supported range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59. MySQL displays DATETIME values in YYYYMM-DD HH:MM:SS format The range is 1970-01-01 00:00:00 to sometime in the year 2037. MySQL displays TIMESTAMP values in YYYYMMDDHHMMSS , YYMMDDHHMMSS , YYYYMMDD or YYMMDD format, depending on whether M is 14 (or missing), 12, 8 or 6, but allows you to assign values to TIMESTAMP columns using either strings or numbers. A TIMESTAMP column is useful for recording the date and time of an INSERT or UPDATE operation because it is automatically set to the date and time of the most recent operation if you don't give it a value yourself
DATE DATETIME
TIMESTAMP
converted by Web2PDFConvert.com
TIME
A time
The range is -838:59:59 to 838:59:59. MySQL displays TIME values in HH:MM:SS format, but allows you to assign values to TIME columns using either strings or numbers The allowable values are 1901 to 2155, and 0000 in the 4 year format and 1970-2069 if you use the 2 digit format (70-69). MySQL displays YEAR values in YYYY format, but allows you to assign values to YEAR columns using either strings or numbers. (The YEAR type is new in MySQL 3.22) The range of Length is 1 to 255 characters. Trailing spaces are removed when the value is retrieved. CHAR values are sorted and compared in case-insensitive fashion according to the default character set unless the BINARY keyword is given
YEAR
A year in 2 or 4 digit formats (default is 4digit) A fixed-length string that is always rightpadded with spaces to the specified length when stored A variable-length string. Note: Trailing spaces are removed when the value is stored (this differs from the ANSI SQL specification)
CHAR
VARCHAR
The range of Length is 1 to 255 characters. VARCHAR values are sorted and compared in case-insensitive fashion unless the BINARY keyword is given
A BLOB or TEXT column with a maximum length of 65535 (2^16 - 1) characters A BLOB or TEXT column with a maximum length of 16777215 (2^24 - 1) characters
A string object that can have only one value, chosen from the list of values 'value1', 'value2', ..., or NULL . An ENUM can have a maximum of 65535 distinct values. A string object that can have zero or more values, each of which must be chosen from the list of values 'value1', 'value2', ... A SET can have a maximum of 64 members
SET
A set
Length 6 15 15 20 20 20 30 30
Description A unique identifier for each record The person's first name The person's last name The person's phone number The person's mobile number The person's fax number The person's e-mail address The person's web address
There is one thing you should be aware of in this database. The id field will also be set as PRIMARY , INDEX , UNIQUE and will be set to auto_increment (found under "extra" in phpMyAdmin). The reason for this is that this will be the field identifier (primary and index) and so must be unique. The auto_increment setting means that whenever you add a record, as long as you don't specify an id , it will be given the next number available.
converted by Web2PDFConvert.com
The following code can be used to create our contacts table with PHP:
<?php $user = "username"; $passw ord = "passw ord"; $database = "database_name"; mysql_connect("localhost", $user, $passw ord); @mysql_select_db($database) or die("Unable to select database!"); $query = "CREATE TABLE contacts ( id int(6) NOT NULL auto_increment, first varchar(15) NOT NULL, last varchar(15) NOT NULL, phone varchar(20) NOT NULL, mobile varchar(20) NOT NULL, fax varchar(20) NOT NULL, email varchar(30) NOT NULL, w eb varchar(30) NOT NULL, PRIMARY KEY (id), UNIQUE id (id), KEY id_2 (id) )"; mysql_query($query); mysql_close(); ?>
At this point you may be wondering if it is a security risk, keeping your password in the file. Don't worry, PHP source code is processed by the server before being sent to the browser so it is impossible for the user to see the script's source. The next command starts a database server connection:
mysql_connect("localhost", $user, $passw ord);
This line tells PHP to connect to the MySQL database server at "localhost" ( localhost means the database server runs on the same server the web site is running). Unless your web host tells you otherwise you should always use localhost . When done, close the connection:
mysql_close();
This is a very important command as it closes the connection to the database server. The server will keep the connection open if you do not include this command. Too many open MySQL connections can cause problems for a web host. It is good practice to always include this line once you have issued all your commands to the database.
This command tells PHP to select the database stored in the variable $database (which you set earlier). If it cannot connect it will stop executing the script and will output the error Unable to select database!.
mysql_query($query);
This may look a little confusing at first so lets look at it in more detail.
INSERT INTO contacts (id, first, last, phone, mobile, fax, email, w eb) VALUES ('', 'John', 'Smith', '(351) 239100100', '(351) 239100101', '(351) 239100102', '[email protected]', 'http://w w w .samaxes.com')
This SQL statement is quite easy to understand. It tells to insert the data:
('', 'John', 'Smith', '(351) 239100100', '(351) 239100101', '(351) 239100102', '[email protected]', 'http://w w w .samaxes.com')
of the table contacts . You may have noticed that you are not inserting any value into the first field ( id ) in the database. This field is going to act as an index. No two records in the database will have the same identifier.
The following script will get the information from the request parameters, connect to the database server and insert the data into the contacts table:
<?php $user = "username"; $passw ord = "passw ord"; $database = "database_name"; $first = $_POST["first"]; $last = $_POST["last"]; $phone = $_POST["phone"]; $mobile = $_POST["mobile"]; $fax = $_POST["fax"]; $email = $_POST["email"]; $w eb = $_POST["w eb"]; mysql_connect("localhost", $user, $passw ord); @mysql_select_db($database) or die("Unable to select database!"); $query = "INSERT INTO contacts (id, first, last, phone, mobile, fax, email, w eb) VALUES ('', '$first', '$last', '$phone', '$mobile', '$fax', '$email', '$w eb')"; mysql_query($query); mysql_close(); ?>
converted by Web2PDFConvert.com
This script should then be saved as insert.php so that it can be called by the HTML form.
This is a basic MySQL command which will tell the script to select all the records in the contacts table. Because there will be output from this command it must be executed with the results being assigned to a variable:
$query = "SELECT * FROM contacts"; $result = mysql_query($query);
In this case the whole content of the contacts table is now contained in a special array with the name $result .
This will set the value of $num to the number of rows stored in $result (the output you got from the database). This can then be used in a loop to get all the data and output it on the screen.
We will not need to get the id field (although we can) because we have no use for it in the current output page.
converted by Web2PDFConvert.com
$w eb = mysql_result($result, $i, "w eb"); echo "<p>$first $last</p><p>Phone: $phone</p><p>Mobile: $mobile</p><p>Fax: $fax</p> <p>E-mail: $email</p><p>Web: $w eb</p><hr/>"; $i++; } ?>
You can also use the PHP loop to repeat the appropriate code and include it as part of a larger table. For example, using part of the code from the previous section which looped to output the database you can format it to be displayed in one large table:
<table> <thead> <tr> <th>Name</th> <th>Phone</th> <th>Mobile</th> <th>Fax</th> <th>E-mail</th> <th>Website</th> </tr> </thead> <tbody> <?php $i=0; w hile ($i < $num) { $first = mysql_result($result, $i, "first"); $last = mysql_result($result, $i, "last"); $phone = mysql_result($result, $i, "phone"); $mobile = mysql_result($result, $i, "mobile"); $fax = mysql_result($result, $i, "fax"); $email = mysql_result($result, $i, "email"); $w eb = mysql_result($result, $i, "w eb"); ?> <tr> <td><?php echo $first . " " . $last; ?></td> <td><?php echo $phone; ?></td> <td><?php echo $mobile; ?></td> <td><?php echo $fax; ?></td> <td><a href="mailto:<?php echo $email; ?>"><?php echo $email; ?></a></td> <td><a href="<?php echo $w eb; ?>"><?php echo $w eb; ?></a></td> </tr> <?php $i++; } ?> </tbody> </table>;
This code will print the table headers and add an extra table row for each record in the database.
converted by Web2PDFConvert.com
// loop... }
You can expand on this more by making it more user friendly (for example by providing a link to the "Add data" page if no contacts exist).
Where $id is a variable holding a number of a record. This may seem to be a little worthless as it is, but you can use this very effectively in a number of different ways. For example, if you want to have a dynamically generated site run through a database and a single PHP script, you could write the script to include the database data into the design. Then, using the id field, you could select each individual page and put it into the output. You can even use the page's URL to specify the record you want: http://www.example.com/news/items.php?item=7393. And then have the PHP script look up the record with the id corresponding to the item parameter which in this case would be 7393 .
As with other MySQL queries, it is almost like plain english. In the same way, you can select records based on any field in the database. You can also use variables to give the database criteria. For example, if you had a search form you could get the last name people want to search for and store it in a variable called $searchlast . Then you could execute the following piece of code:
$query = "SELECT * FROM contacts W HERE last = '$searchlast'"; $result = mysql_query($query);
You could also replace ASC by DESC to order the data in descending order.
converted by Web2PDFConvert.com
$first = mysql_result($result, $i, "first"); $last = mysql_result($result, $i, "last"); $phone = mysql_result($result, $i, "phone"); $mobile = mysql_result($result, $i, "mobile"); $fax = mysql_result($result, $i, "fax"); $email = mysql_result($result, $i, "email"); $w eb = mysql_result($result, $i, "w eb"); // Space for code ++$i; } ?>
Where "Space for code" comment will be replaced by the code for the update form. This is, in fact, just plain HTML formatting the output:
<form action="update.php" method="post"> <p><input type="hidden" name="id" value="<?php echo $id; ?>"/></p> <p>First Name: <input type="text" name="first" value="<?php echo $first; ?>"/></p> <p>Last Name: <input type="text" name="last" value="<?php echo $last; ?>"/></p> <p>Phone Number: <input type="text" name="phone" value="<?php echo $phone; ?>"/></p> <p>Mobile Number: <input type="text" name="mobile" value="<?php echo $mobile; ?>"/></p> <p>Fax Number: <input type="text" name="fax" value="<?php echo $fax; ?>"/></p> <p>E-mail Address: <input type="text" name="email" value="<?php echo $email; ?>"/></p> <p>Web Address: <input type="text" name="w eb" value="<?php echo $w eb; ?>"/></p> <p><input type="Submit" value="Update"/></p> </form>
As you can see, this code will output a standard form, but instead of having blank text boxes like on the form for inserting a new record, this one already has the current information from the database inserted into it. This makes it much more effective for an update script.
This query tells the database to update the contacts table where the id is the same as the value stored in $id . This query could then be integrated into a simple script:
$id = $_POST["id"]; $first = $_POST["first"]; $last = $_POST["last"]; $phone = $_POST["phone"]; $mobile = $_POST["mobile"]; $fax = $_POST["fax"]; $email = $_POST["email"]; $w eb = $_POST["w eb"]; $user = "username"; $passw ord = "passw ord"; $database = "database_name"; mysql_connect("localhost", $user, $passw ord); @mysql_select_db($database) or die("Unable to select database!"); $query = "UPDATE contacts SET first = '$first', last = '$last', phone = '$phone', mobile = '$mobile', fax = '$fax', email = '$email', w eb = '$w eb' W HERE id = " . $id; mysql_query($query); echo "Record updated!"; mysql_close();
This code would update the database and give the user a confirmation message.
converted by Web2PDFConvert.com
This query can be used with the connection and confirmation message of the code above.
6. Final tips
Save time and optimize your search.
Replacing the appropriate sections. Then in your .php files use the following code at the beginning:
include("dbinfo.inc.php"); // or include("/full/path/to/file/dbinfo.inc.php");
Then, you can use the variables $username , $passw ord and $database throughout your scripts without having to define them every time. Also, if you ever change this information, for example if you move to another web host, there is only one file to change.
6.2. Searching
A limited form of searching can also be performed on your database using a built in MySQL function. The LIKE keyword:
SELECT * FROM tablename W HERE fieldname LIKE '%$value%'
To explain further, LIKE tells the database to perform its "searching" feature. The % signs mean that any other data could appear in their place and $value would hold your search string. For instance, LIKE '%piano%' would output any rows with the word piano in the specified field. Similarly, you can leave out one of the % signs so that you can specify the position of the string:
SELECT * FROM tablename W HERE fieldname LIKE 'piano%'
will only output rows where the specified field begins with the piano word. So a record with the string "The piano is next to the table" will not show up.
7. Security
At this point it should be noted that you must be very careful in using the technique given above. Without correct security measures, it would be very easy for someone to access data on your server, or even make changes to the database. This can occur if the user sets the variable to a value which edits the SQL string being generated in such a way that it can be used for their own purposes. I won't go into full details here, but there are many websites which give full details (search for "sql injection attack"). This security hole is easy to plug with a bit of work. Always check input data for invalid characters and use PHP's built in functions to remove control characters, HTML code, etc. Again, there are many websites which go into this in depth.
converted by Web2PDFConvert.com