Php and database combined with a simple web instance code analysis (php beginners) _ PHP Tutorial

Source: Internet
Author: User
Tags echo command web database
Php and database combined with a simple web instance code analysis (php beginners ). 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, please refer to the installation section on this site. However, apart from the installation section, there are more or less instructions for Windows, and the other sections are 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:
+ ---------- + -------------- + ------ + ----- + --------- + ------- +
| 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:
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:
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.
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 and changes the UserName value.

Combination of 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

  Web Database Sample Index
Data from tbl
   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 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:
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. .
Now that we have all the information, we can print it out in an html table:
Reference content is as follows:
  $ 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.


  • 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:
  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:

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:

The code is as follows:


Related Article

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: 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.