PHP and database combined with a simple Web instance Code analysis (PHP beginner) _php Tutorial

Source: Internet
Author: User
Tags echo command php and mysql web database
However, in addition to the installation section, there are more or less instructions for Windows, and the rest is the same for all platforms. By the way, for the installation section, please see the Installation Guide of this site. In this tutorial, we will build a small web site step after day, using the following features of PHP and MySQL:
1. View the database;
2. Edit the records of the database;
3. Modify the records of the database;
4. Delete the records for the database.
We will learn MySQL and PHP at the same time, to feel them together. This article directly from here to learn, if you do not install the configuration apache+php+mysql please check the Web teaching network related articles!
Run the Web server first (the PHP extension has been added), and run MySQL.
Create and manipulate a MySQL database:
First we need to create the database and table to use. The database is named "Example" with the table named "TBL" with the following fields: Identification number, first name, last name, and information. To work with the MySQL terminal to build the library and define the table, simply 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 that mysql> is a terminal prompt):
mysql> show databases; <回车>
This command may display the following information:
+----------+
| Database |
+----------+
| MySQL |
| Test |
+----------+
2 rows in Set (0.01 sec)
In order to define a new database (example), type:
mysql> CREATE DATABASE example; <回车>
You will see an answer such as:
Query OK, 1 row affected (0.17 sec) Very fat, we now have a new database. Now we can create a new table in the library, but first we need to select the new database:
Mysql> use example; <回车>
The answer should be:
Database changed
Now we can build a table with the following fields:
Index number-integer
User name-a string with a maximum length of 30
User last name-a string with a maximum length of 50
Free information-a string with a maximum length of 100
At the MySQL prompt, type the following command to create the table:
Mysql> CREATE TABLE tbl (idx integer (3), UserName varchar (+), LastName varchar (+), FreeText varchar (100)); <回车>
The answer should be:
Query OK, 0 rows affected (0.01 sec)
OK, let's see what the table looks like from the MySQL prompt, type the command:
Mysql> show columns from TBL; <回车>
We will get the following result:
+----------+--------------+------+-----+---------+-------+
| 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 contents of the table "TBL" just created.
Now let's take a look at what's in the table. Type the following command:
Mysql> select * from TBL; <回车>
This command is used to display all the data in the table "TBL". The output may be:
The Empty set (0.07 sec) gets this result because we haven't inserted any data into the table yet. 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 I see above, the values we insert into the table are in the order of the tables we defined earlier, because the default order is used. We can set the order of the data, the syntax is as follows:
mysql> INSERT INTO TBL (Idx,username,lastname,freetext) VALUES (1, ' Rafi ', ' Ton ', ' Just a test '); <回车>
OK, now we can look at the contents of the table again:
Mysql> select * from TBL; <回车>
This time 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 contents of each cell.
Now we want to delete the data. In order to implement we should type:
Mysql> Delete from tbl where idx=1 limit 1; <回车> Query OK, 1 row Affected (0.00 sec)
Well, give some explanations. We're telling MySQL to delete records from the TBL table, delete records with a value of 1 for the IDX field, and restrict the deletion of only one record. If we do not limit the number of deleted records to 1, then all records with IDX 1 will be deleted (in this case we only have one record, but even so, I just want to make this clearer).
Unfortunately, once again we got an empty table, so let's lose it again:
mysql> INSERT into TBL values (1, ' Rafi ', ' Ton ', ' Just a test '); <回车>
Query OK, 1 row affected (0.04 sec)
Another thing you can do is modify the contents of the specified field and use the "Update" command:
Mysql>update tbl Set username= ' Berber ' where username= ' Rafi '; <回车>
Query OK, 1 row affected (0.01 sec)
Rows matched:1 changed:1 warnings:0
This command searches all records that username as "Rafi" and changes it to "Berber". Note that the set section and the where section do not have to be the same. We can search for a field but change another field. Furthermore, we can perform searches for two or more conditions.
Mysql>update tbl Set username= ' Rafi ' where username= ' Berber ' and lastname= ' Ton '; <回车>
Query OK, 1 row affected (0.04 sec)
This query searches for two fields and changes the value of the username


Combining PHP with MySQL
In this section, we will build a PHP-based Web site that controls the MySQL tables that were built.
We will build the following site structure (assuming you already know some basic HTML knowledge):
1. Index.php3 for Front end view table 2. ADD.PHP3 for inserting data into a table
3. MODIFY.PHP3 is used to modify record 4 in the table. Del.php3 used to delete records in a table
First, we want to look at the database and see the following script:
--------------------------------------------------------------------------------
index.php

  
   <title>Web Database Sample Index</title>
  
  
  

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 ');
?>
  
  
--------------------------------------------------------------------------------
OK, here are some instructions:
We'll start by creating a THML document with normal HTML tags. When we want to get out of the HTML into PHP, we use To end the PHP section.
The mysql_connect () command tells PHP to establish a connection to the MySQL server. If the connection is established successfully, the script will continue and if unsuccessful, print out the information "problem connecting to Database" of the Die Command (if you want to see more information about mysql_connect and other PHP functions, you can go to HTTP.// Found in the document under Www.php.net).
Now, if MySQL is installed as we discussed above, it will suffice. But if you are using pre-installed MySQL (like an ISP), you should use the following command:
mysql_connect (localhost, username, password);
We can set $query as the query we want to execute in MySQL, and then use the Mysql_db_query command to execute it:
$result = Mysql_db_query ("Example", $query);
At this point, "example" represents the name of the database and $query is the query to be made.
We use the MySQL command select (as described above) to get all the data from the table:
$query = "SELECT * from TBL";
Simply explain the role of $result, if successful, the function returns a MySQL result identifier for the result of the query, and returns False if an error occurs. The return is not the result but an identifier, which can be converted to the information we need later.
Now, we want to check if there is a record in the database, and if so, print the result in the HTML table structure. To check if there is data, we use the IF command and the following syntax:
if (argument) {
"Do something;"
} else {
"Do something different;"
}
At this time "do something" when argument=true the command you want to execute, "do something Different" is the command to be executed when argument =false.
Note that we use the echo command to output some HTML tags to create the HTML table structure. Only text that is output from a PHP command is considered HTML content-the PHP command itself is not considered HTML content. Another command we use is the while instruction, which uses the following format:
while (argument)) {
"Something to Do";
}
The while loop repeats repeatedly at Argument=true, executing the instruction set in {}.
Here we combine the while loop and PHP function $r=mysql_fetch_array ($result). This function retrieves a record based on the corresponding result identifier, and puts the result in a related array (associative array) $r, which uses the name of the field 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, which will put the result in an ordered array, we can use $r[0], $r [1], $r [2] and $r[3] to get the corresponding value:
Now that we have all the information, we can print it out in an HTML table:
The following is the referenced content:
echo "
   $idx
   $user
   $last
   $text
   ";
Now we can release the MySQL connection and release some resources by using the Mysql_free_result ($result) function.
Another useful feature of PHP is the ability to include text files in the script. Let's say that you have some reusable code (such as a link to another page), and we can use the Include function to save some code and time. And, if you want to change the code, we just need to change the contents of the included file, which will take effect in all the files that include it.
Here we create a text file called Links.x, which will store all the link menus that we want to use on each page.
 


  

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

The syntax for include is:
Include (' Included_text_file ');
Now we can use?> to close the PHP section and useTo end the HTML page.
Using forms to add data let's look at the following code:
--------------------------------------------------------------------------------
  
   <title>Add an entry to the database</title>
  
  
  

Add an entry


  
  
  
  
  
--------------------------------------------------------------------------------
Let's say you're familiar with the form, which is a fairly simple script. We designed a form based on an HTML page that invokes the Add2tbl.php3 script after committing. Now, the form and the MySQL table should consist of 4 fields: Index Number,firstname,lastname and FreeText. Note that the field names in this form are the same as the field names in the MySQL table, but this is only for convenience and not necessary.
Once again we used the include command (as explained above) to increase the link.
Let's take a look at the add2tbl.php3 script:
--------------------------------------------------------------------------------
  
  
   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 "















Copy Code

<title>Editing an entry from the database</title>


Edit an entry








               ";   while ($r = Mysql_fetch_array ($result)) {$idx = $r ["idx"]; $user Note the comments that I made in the script. With a comment you can use "//" and the server ignores the later part of this line. Simple, isn't it? To edit a record from the database: Let's assume that we want to modify the records that exist in the database. In front, we see a SQL command called set to set the value of the field that exists in the database. We will use this command to modify the entire record in the database.                  Consider the following script:--------------------------------------------------------------------------------edit.php: The code is as follows:    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 "
IdxUser NameLast NameFree Text



















               ";   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 simply prints out the contents of the table in the database. Note that there is a different line:
$idx
This line establishes a link to editing.php3 and passes some variables to the new script. It's like a form, but it's just a link. We convert the information into: variables and values. Note that in order to print out "symbols we need to use \" Otherwise the server will treat it as part of the PHP script and as the printed information.
We want to convert all the records in the database to the past so that we can get the exact data in the table so that it is easier for us to modify it.
--------------------------------------------------------------------------------
editing.php
Copy CodeThe code is as follows:
  
   <title>Editing an entry</title>
  
  
  

Editing an entry


  
  
  
  

--------------------------------------------------------------------------------
OK, this script is simple. Our concern is that when the form is printed out, it records the data of the current record by The Value property in the command. This data was passed from a previous page.
Now, if we don't change the recorded information, it will return the current value, which is the default value. If we change the value of the field, the value of the field becomes the new value. Then we can pass the new value to another script, which will change the values in the MySQL table.
--------------------------------------------------------------------------------
editdb.php:
Copy CodeThe code 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 ');
?>

--------------------------------------------------------------------------------
One thing that basically concerns you 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 syntax that we explained in the previous MySQL section. Another thing, note that this script changes the records of idx= $idx, and if there are more than one IDX equal to $IDX records in the table, these records will be changed. If we want to be more strict, 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 examines all fields, not just the IDX.
To delete a record from the database:
OK, delete is easy. We still need two scripts: one to select the records to delete (basically the same as the record you chose to edit), one to really delete and print the new table.
--------------------------------------------------------------------------------
del.php
Copy CodeThe code is as follows:
  
   <title>Deleting an entry from the database</title>
  
  
  

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 ');
?>
  
  

http://www.bkjia.com/PHPjc/324096.html www.bkjia.com true http://www.bkjia.com/PHPjc/324096.html techarticle However, in addition to the installation section, there are more or less instructions for Windows, and the rest is the same for all platforms. By the way, about the installation section, please see this site of Ann ...

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