PHP and MySQL dynamic website development tutorial for beginners

Source: Internet
Author: User
Tags web database
This is a basic tutorial. No weird code, just some basics. Now there are a lot of tutorials based on UNIX machines. This tutorial will focus on the basics. this is a basic tutorial. No weird code, just some basics. Now there are a lot of tutorials based on UNIX machines, which will be focused on Windows platforms. However, apart from the installation part, there are more or less instructions for Windows, and the other part is the same for all platforms. By the way, for the installation part, please refer to the installation guide on this site. In this tutorial, we will build a small website step by step, using the following features of PHP and MySQL:

1. view the database;
2. edit database records;
3. modify database records;
4. delete database records.
  
We will learn about MySQL and PHP at the same time and feel them together. This article will be learned from here. if you do not install and configure Apache + PHP + Mysql, please refer to the relevant articles on web tutorial network!

Run the web server (PHP extension added) first and MySQL.
  
Create and manipulate a MySQL database:
  
First, we need to create the database and table to be used. The database name is "example" and the table name is "tbl". It has the following fields: identification number, name, last name, and information. To create a database and define a table on the mysql terminal, double-click or run c: \ mysql \ bin \ mysql.exe.
If you want to see which tables have been defined in MySQL, you can use (note mysql> terminal prompt ):
Mysql> show databases; <回车>
This command may display the following information:
+ ---------- +
| Database |
+ ---------- +
| Mysql |
| Test |
+ ---------- +
2 rows in set (0.01 sec)
To define a new database (example), type:
Mysql> create database example; <回车>
You will see an answer, for example:
Query OK, 1 row affected (0.17 sec) is very popular. now we have a new database. Now we can create a new table in the database, but first we need to select the new database:
Mysql> use example; <回车>
  
The answer should be:
Database changed
Now we can create a table with the following fields:
  
Index number-integer
Username-string with a maximum length of 30
User surname-string with a maximum length of 50
Free Info-string with a maximum length of 100
At the MySQL prompt, type the following command to create a table:
MySQL> create table tbl (idx integer (3), UserName varchar (30), LastName varchar (50), FreeText varchar (100 )); <回车>
  
The answer should be:
Query OK, 0 rows affected (0.01 sec)
Well, let's take a look at what the table looks like from the MySQL prompt. type the command:
MySQL> show columns from tbl; <回车>
We will get the following results:


Reference content is as follows:
+ ---------- + -------------- + ------ + ----- + --------- + ------- +
| Field | Type | Null | Key | Default | Extra |
+ ---------- + -------------- + ------ + ----- + --------- + ------- +
| Idx | int (3) | YES | NULL |
| UserName | varchar (30) | YES | NULL |
| LastName | varchar (50) | YES | NULL |
| FreeText | varchar (100) | YES | NULL |
+ ---------- + -------------- + ------ + ----- + --------- + ------- +


4 rows in set (0.00 sec)
Here, we can see the content of the newly created table "tbl.
  
Now let's take a look at what is in the table. Type the following command:
MySQL> select * from tbl; <回车>
  
This command is used to display all data in the table "tbl. The output may be:
Empty set (0.07 sec) returns this result because we have not inserted any data into the table. Let's insert some data into the table and type:
MySQL> insert into tbl values (1, 'Rafi ', 'ton', 'just a test '); <回车>
  
Query OK, 1 row affected (0.04 sec)
As shown in the preceding figure, the values inserted into the table follow the sequence defined in the previous table, because the default sequence is used. We can set the data sequence. The syntax is as follows:
MySQL> insert into tbl (idx, UserName, LastName, FreeText) values (1, 'Rafi ', 'ton', 'just a test '); <回车>
  
Okay. now let's take a look at the table content:
  
MySQL> select * from tbl; <回车>
The result is:
+ ------ + ---------- + ------------- +
| Idx | UserName | LastName | FreeText |
+ ------ + ---------- + ------------- +
| 1 | Rafi | Ton | Just a test |
+ ------ + ---------- + ------------- +
1 row in set (0.00 sec)
Now we can see the structure of the table and the content of each cell.
  
Now we want to delete the data. To achieve this, enter:
  
MySQL> delete from tbl where idx = 1 limit 1; <回车> Query OK, 1 row affected (0.00 sec)
  
Okay. give some explanations. We are telling MySQL to delete records from the "tbl" table, delete those records whose idx field value is 1, and delete only one record. If we do not limit the number of deleted records to 1, all records with idx as 1 will be deleted (in this example, we only have one record, but even so, I just want to make it clearer ).
  
Unfortunately, we once again got an empty table, so let's try again:
  

Reference content is as follows:
MySQL> insert into tbl values (1, 'Rafi ', 'ton', 'just a test '); <回车>
Query OK, 1 row affected (0.04 sec)

Another thing that can be done is to modify the content of the specified field and use the "update" command:



Reference content is as follows:
MySQL> update tbl set UserName = 'berberber' where UserName = 'Rafi '; <回车>
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0


This command will search all records whose UserName is "Rafi" and change it to "Berber ". Note that the set part and the where part are not necessarily the same. We can search for a field but change the other field. In addition, we can perform two or more search conditions.
  

Reference content is as follows:
MySQL> update tbl set UserName = 'raf' where UserName = 'berberber' and LastName = 'ton '; <回车>
Query OK, 1 row affected (0.04 sec)


This query searches for two fields, changing the UserName value combination PHP and MySQL

In this section, we will create a single PHP-based web site to control the previously created MySQL table.
  
We will build the following site structure (assuming you already know some basic HTML knowledge ):
1. index. php3 is used to view the table at the front end. 2. add. php3 is used to insert data into the table.
3. Modify. php3 is used to Modify the records in the table. 4. del. php3 is used to delete records in the table.
First, let's look at the database and see the scripts below the workshop:
--------------------------------------------------------------------------------
Index. php


Reference content is as follows:
  
  Web Database Sample Index
  
  
Data from tbl
   Mysql_connect () or die ("Problem connecting to DataBase ");
$ Query = "select * from tbl ";
$ Result = mysql_db_query ("example", $ query );
If ($ result ){
Echo "Found these entries in the database:

";
Echo"


















               ";While ($ r = mysql_fetch_array ($ result )){$ Idx = $ r ["idx"];$ User = $ r ["UserName"];$ Last = $ r ["LastName"];$ Text = $ r ["FreeText"];Echo"                ";}Echo"
User NameLast NameDomain NameRequest Date
$ Idx$ User$ Last$ Text
";
}
Else
{
Echo "No data .";
}
Mysql_free_result ($ result );
Include ('links. X ');
?>
  
  


--------------------------------------------------------------------------------
Okay. Here are some instructions:
  
We first create thml documents with normal html tags. When we want to transfer from html to PHP, we use To end the PHP section.
  
The mysql_connect () command tells PHP to establish a connection with the MySQL server. If the connection is established successfully, the script continues. if the connection fails, then print out the die command information "Problem connecting to Database" (if you want to see more information about mysql_connect and other PHP functions, you can go to the document under the http://www.php.net to find ).
  
Now, if MySQL is installed as discussed above, it is enough. However, if you are using pre-installed MySQL (like ISP), you should use the following command:
  
Mysql_connect (localhost, username, password );
We can set $ query to the query we want to execute in MySQL, and then run it using the mysql_db_query command:
$ Result = mysql_db_query ("example", $ query );

In this case, "example" indicates the database name and $ query is the query to be performed.

We use the MySQL command select (as described above) to retrieve all data from the table:

$ Query = "select * from tbl ";

Briefly explain the functions of $ result. if the execution is successful, the function returns a MySQL result identifier of the query result. If an error occurs, false is returned. The returned result is not a result identifier, which can be converted to the information we need later.
  
Now, we want to check whether there are records in the database, and if so, print the results according to the html table structure. To check whether data exists, we use the if command and the following syntax:


Reference content is as follows:
If (argument ){
"Do something ;"
} Else {
"Do something different ;"
}


In this case, "do something" indicates the command to be executed when argument is set to true. "do something different" indicates the command to be executed when argument is set to false.
  
Note that we use the echo command to output some html tags to create an html table structure. Only the text output from the PHP command is considered html content-the PHP command itself is not considered html content. Another command we use is the while Command. the format is as follows:
While (argument )){
"Something to do ";
}
The while loop repeats repeatedly when argument = true and runs the instruction set in.
  
Here we combine the while loop and PHP functions $ r = mysql_fetch_array ($ result ). This function retrieves a record based on the corresponding result identifier and places the result in an associated array $ r. it uses the field name as the key value of the array. In our script, we will get an array: $ r ['idx'], $ r ['username'], $ r ['lastname'] and
$ R ['freetext '].
  
We can also use the mysql_fetch_row function to place the results in an ordered array. we can use $ r [0], $ r [1], $ r [2] and $ r [3] to obtain the corresponding values.
  
For more in-depth information about these functions, visit the http://www.php.net.
Now that we have all the information, we can print it out in an html table:







               ";
Reference content is as follows:
Echo"
$ Idx$ User$ Last$ Text


Now we can release MySQL connections and release some resources by using the mysql_free_result ($ result) function.
  
Another useful feature of PHP is to include text files in scripts. Let's assume that you have some reusable code (such as links to other pages). we can use the include function to save some code and time. Moreover, if you want to change the code, you only need to change the content of the contained file, which will take effect in all the files that contain it.
  
Here we create a text file named Links. x, which stores all the link menus we want to use on every page.


Reference content is as follows:
  


  

      
  • Home
      
  • Add a new entry to the DataBase
      
  • Edit an entry
      
  • Delete an entry from the DataBase
      

The include syntax is:
Include ('encoded _ text_file ');
Can we use it now?> To close the PHP part and useTo end the html page.
Using the form to add data allows us to see the following code:
--------------------------------------------------------------------------------



Reference content is as follows:
  
  Add an entry to the database
  
  
Add an entry
  
  

  
  
  


--------------------------------------------------------------------------------
If you are familiar with forms, this is a simple script. We designed a form based on the html page. after the form is submitted, the add2tbl. php3 script is called. At present, the form and MySQL table should be composed of four fields: index number, FirstName, LastName, and FreeText. Note that the field names in this form are the same as those in the MySQL table, but this is only for convenience, not necessary.
  
The include command is used again. (As explained above) to add links.
Let's take a look at the add2tbl. php3 script:
--------------------------------------------------------------------------------


Reference content is as follows:
  
  
   If ($ UserName)
{
Mysql_connect () or die ("Problem connecting to DataBase ");
$ Query = "insert into tbl values ('$ idx',' $ username', '$ LastName', '$ FreeText ')";
$ Result = mysql_db_query ("example", $ query );
Echo "Data inserted. new table:

";
$ Query = "SELECT * FROM tbl ";
$ Result = mysql_db_query ("example", $ query );
If ($ result)
{
Echo"








               ";While ($ r = mysql_fetch_array ($ result )){$ Idx = $ r ["idx"];$ User
IdxUser NameLast NameFree Text


Note: the comments I made in the script. You can use "//" to use a comment. The server will ignore the later part of this line.

 

Simple, isn't it? Edit a record from the database: Let's assume that we want to modify the existing record in the database. We can see that there is an SQL command called set to set the values of fields in the database. We will use this command to modify the entire record in the database. Consider the following script:
--------------------------------------------------------------------------------


Reference content is as follows:
Edit. php:
  
  Editing an entry from the database
  
  
Edit an entry Mysql_connect () or die ("Problem connecting to DataBase ");
$ Query = "select * from tbl ";
$ Result = mysql_db_query ("example", $ query );
If ($ result)
{
Echo "Found these entries in the database:
";
Echo"


















               ";While ($ r = mysql_fetch_array ($ result )){$ Idx = $ r ["idx"];$ User = $ r ["UserName"];$ Last = $ r ["LastName"];$ Text = $ r ["FreeText"];Echo"                ";}Echo"
IdxUser NameLast NameFree Text

$ Idx
$ User$ Last$ Text
";
}
Else
{
Echo "No data .";
}
Mysql_free_result ($ result );
Include ('links. X ');
?>
  
  


--------------------------------------------------------------------------------
As you can see, the code here is somewhat familiar. The first part only prints the table content in the database. Note that one line is not the same:
$ Idx
This line creates a link to editing. php3 and passes some variables to the new script. Similar to the form, only links are used. We convert the information to: variable and value. Note: to print out the "symbol, we need to use \". Otherwise, the server will regard it as part of the PHP script and use it as printed information.
We want to convert all the records in the database, so that we can get the exact data in the table so that it is easier to modify it.
--------------------------------------------------------------------------------


Reference content is as follows:
Editing. php
  
  Editing an entry
  
  
Editing an entry
  
  
  
  


--------------------------------------------------------------------------------
  
Okay. this script is simple. When a form is printed, it records the data of the current record.Command. The data is transmitted from the previous page.
Now, if we do not change the record information, it will return the current value, that is, the default value. If we change the field value, the field value will become a new value. Next we can pass the new value to another script, which will change the value in the MySQL table.
--------------------------------------------------------------------------------
Editdb. php:


Reference content is as follows:
   Mysql_connect () or die ("Problem connecting to DataBase ");
$ Query = "update tbl set
Idx = '$ idx', UserName =' $ username', LastName = '$ Lastname', FreeText =' $ FreeText 'where
Idx = '$ idx '";
$ Result = mysql_db_query ("example", $ query );
$ Query = "SELECT * FROM tbl ";
$ Result = mysql_db_query ("example", $ query );
If ($ result)
{
Echo "Found these entries in the database:

";
Echo"


















               ";While ($ r = mysql_fetch_array ($ result )){$ Idx = $ r ["idx"];$ User = $ r ["UserName"];$ Last = $ r ["LastName"];$ Text = $ r ["FreeText"];Echo"                ";}Echo"
IdxUser NameLast NameFree Text
$ Idx$ User$ Last$ Text
";
}
Else
{
Echo "No data .";
}
Mysql_free_result ($ result );
  
Include ('links. X ');
?>

--------------------------------------------------------------------------------
Basically, one thing to care about is the following line:
$ Query = "update tbl set idx = '$ idx', UserName =' $ username', LastName = '$ Lastname ', freeText = '$ FreeText' where idx = '$ idx '";
Note that it is the same as the syntax we explained in the previous MySQL section. Another thing is that this script changes the idx = $ idx record. if there are multiple records with idx equal to $ idx in the table, these records will be changed. If we want to be stricter, we can change the where clause as follows:
$ Query = "update tbl set idx = '$ idx', UserName =' $ username', LastName = '$ Lastname ', freeText = '$ FreeText' where idx = '$ idx' and UserName =' $ username' and LastName = '$ Lastname' and FreeText =' $ FreeText '";
This syntax checks all fields, not just idx.
Delete a record from the database:
Yes, it is easy to delete. We still need two scripts: one for selecting the record to be deleted (basically the same as the record selected for editing) and the other for deleting and printing new tables.
--------------------------------------------------------------------------------



Reference content is as follows:
Del. php
  
  Deleting an entry from the database
  
  
Del an entry
   Mysql_connect () or die ("Problem connecting to DataBase ");
$ Query = "select * from tbl ";
$ Result = mysql_db_query ("example", $ query );
If ($ result)
{
Echo "Found these entries in the database:

";
Echo"


















               ";While ($ r = mysql_fetch_array ($ result )){$ Idx = $ r ["idx"];$ User = $ r ["UserName"];$ Last = $ r ["LastName"];$ Text = $ r ["FreeText"];Echo"                ";}Echo"
IdxUser NameLast NameFree Text

Idx = $ idx & UserName = $ user & LastName = $ last & FreeText = $ text \ "> $ idx
$ User$ Last$ Dtext
";
}
Else
{
Echo "No data .";
}
Mysql_free_result ($ result );
Include ('links. X ');
?>
  
  


--------------------------------------------------------------------------------
This script is very similar to the edited script we have used, so let's take a look at the instructions.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.