Home  >  Article  >  Backend Development  >  A simple web example combining PHP and database Code Analysis (PHP Beginner)_PHP Tutorial

A simple web example combining PHP and database Code Analysis (PHP Beginner)_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:25:30787browse

However, apart from the installation part, which has more or less Windows-specific instructions, the rest are the same for all platforms. By the way, for the installation part, please see 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 the records of the database;
 3. Modify the database records;
 4. Delete the records of the database.
We will learn MySQL and PHP at the same time and feel them together. This article can be learned directly from here. If you don’t know how to install and configure Apache+PHP+Mysql, please check out the related articles on the web teaching network!
First run the web server (PHP extension has been added); run MySQL.
Create and manipulate a MySQL database:
First we need to create the database and tables to be used. The database is named "example", the table is named "tbl", and has the following fields: identification number, first name, last name and information. To complete the database creation and table definition work through the mysql terminal, just double-click or run c:mysqlbinmysql.exe.
If you want to see which tables have been defined in MySQL, you can use (note that mysql> is the 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; < ; Enter>
You will see a response, such as:
Query OK, 1 row affected (0.17 sec) That’s right, 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 create 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
Type the following command at the MySQL prompt to create the 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)
Okay, let’s take a look at the table from the MySQL prompt. What does it look like? 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 contents of the table "tbl" we 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 data in table "tbl". The output might be:
Empty set (0.07 sec) The reason why we get this result is 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 you can see above, the values ​​we insert into the table are in the order in which we defined the table earlier, because the default order is used. We can set the order of 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 content of each cell.
Now we want to delete the data. To achieve this we should type:
 MySQL> delete from tbl where idx=1 limit 1; Query OK, 1 row affected (0.00 sec)
 Okay, give some explanation.We are telling MySQL to delete records from the "tbl" table, delete those records with an idx field value of 1, and limit deletion to only one record. If we don't limit the number of deleted records to 1, then all records with idx 1 will be deleted (in this example we only have one record, but nonetheless, I just wanted to make this more clear).
Unfortunately, we get an empty table again, so let's enter 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 to modify the content 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 Will search for all records with UserName "Rafi" and change it to "Berber". Note that the set part and where part do not have to be the same. We can search one field but change another field. Moreover, we can perform searches with two or more criteria.
 MySQL>update tbl set UserName='Rafi' where UserName='Berber' and LastName='Ton';
 Query OK, 1 row affected (0.04 sec)
 This query Searched two fields and changed the value of UserName


Combining PHP and MySQL
In this part, we will build a single PHP-based web site to control the previous Create a 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 on 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 the records in the table
First, we want to check the database and take a look at the following script:
 ----- -------------------------------------------------- -----------------------
 Index.php

 
 < title>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 "
/td>
 
 
 ";
 }
 echo "< /table>";
 }
else
 {
echo "No data.";
 }
mysql_free_result($result);
include ('links.x' );
 ?>
 
 
------------------------ -------------------------------------------------- -------
Okay, here are some instructions:
We first create a thml document using normal html tags. When we want to transfer from html to PHP, we use to end the PHP part.
The mysql_connect() command tells PHP to establish a connection to the MySQL server. If the connection is established successfully, the script will continue. If not, the die command information "Problem connecting to Database" will be printed out (if you want to see more information about mysql_connect and other PHP functions, you can go to http://www Find it in the documentation under .php.net).
Now, if MySQL is installed as we discussed above, that is enough.But if you are using the pre-installed MySQL (like an ISP), you should use the following command:
mysql_connect (localhost, username, password);
We can set $query to what we want to execute in MySQL query, and then use the mysql_db_query command to execute it:
$result = mysql_db_query("example", $query);
At this time, "example" represents the name of the database and $query is the query to be performed.
We use the MySQL command select (as described above) to get all the data from the table:
$query = "select * from tbl";
Briefly explain the role of $result, if If executed successfully, the function will return a MySQL result identifier of the query result, or false if an error occurs. What is returned is not a result but an identifier, which can be converted later into the information we need.
Now, we want to check whether there is a record in the database, and if so, print the result according to the html table structure. To check if the data exists, we use the if command with the following syntax:
if (argument) {
"do something;"
} else {
"do something different;"
}
At this time, "do something" is the command you want to execute when argument=true, and "do something different" is the command you want to execute when argument=false.
Note that we use the echo command to output some html tags to establish the html table structure. Only text output from PHP commands will be treated as HTML content - PHP commands themselves will not be treated as HTML content. Another command we use is the while instruction, with the following format:
while (argument)) {
"something to do";
}
The while loop will continue when argument=true Repeat, executing the set of instructions in {}.
Here we combine the while loop and the PHP function $r=mysql_fetch_array($result). This function retrieves a record based on the corresponding result identifier and places the result in an associative array $r, using the field name as the array key. 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 results 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 quoted content:
echo "

 
 
;";
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 scripts. Let us assume that you have some reusable code (such as links to other pages), we can use the include function, which can save some code and time. Moreover, if we want to change this code, we only need to change the content of the included file, and it will take effect in all files that include it.
Here we create a text file called Links.x, which will store all the link menus we want to use on each page.
 


 
 The syntax of include is:
 Include (' included_text_file');
Now we can use ?> to close the PHP part, and use to end the html page.
  使用表单增加数据让我们看一下下面的代码:
  --------------------------------------------------------------------------------
  
  Add an entry to the database
  
  
  

Add an entry


  
  
User Name Last Name Domain Name Request Date
$last $text
$idx< ;/td>
 
$user $last $text

  
        
  
  
Index:
UserName:  maxlength=100>
LastName:  maxlength=100>
FreeText:

  
  
  
 --------------------------------------------------------------------------------
  假设你对表单很熟悉,这是一个相当简单的脚本。我们根据html页面设计了一个表单,它在提交后调用 add2tbl.php3脚本。现在,表单与MySQL表相对应由4个字段组成:index number,FirstName,LastName和 FreeText。注意在这个表单中字段名字与MySQL表中字段名一样,但这只是为了方便起见而不是必须。
  我们再一次使用了include命令(象在前面所解释的)来增加链接。
  让我们看一下add2tbl.php3脚本:
  --------------------------------------------------------------------------------
  
  
    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
  注意,我在脚本中所作的注释。使用一个注释可以用"//",服务器将忽略此行的后面部分。


简单,不是吗?从数据库中编辑一条记录:让我们假设一下,我们想修改数据库中存在的记录。在前面,我们看到有一个叫set的SQL命令用来设置 数据库中存在字段的值。我们将使用这个命令来修改数据库中的整条记录。考虑下面的脚本:
  --------------------------------------------------------------------------------
  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 "
idx User Name Last Name Free Text

  
  
  
  
  ";
  while ($r = mysql_fetch_array($result))
  {
  $idx = $r["idx"];
  $user = $r["UserName"];
  $last = $r["LastName"];
  $text = $r["FreeText"];
  echo "
  
  
  
  
  ";
  }
  echo "
idx User Name Last Name Free Text

  $idx
$user $last $text
";
  }
  else
  {
  echo "No data.";
  }
  mysql_free_result($result);
  include ('links.x');
  ?>
  
  

--------------------------------------------------------------------------------
  如你所见,这里的代码有些熟悉。第一部分只是打印出数据库中表的内容。注意,有一行不太一样:
  $idx
  这一行建立了一个到editing.php3的一个链接,并且给新的脚本传递了一些变量。同表单方式很象,只 是使用的是链接。我们将信息转换成:变量和值。注意,为了打印出 " 符号,我们需要使用 "否则服务器 将把它看成PHP脚本的一部分并且作为被打印的信息。
  我们想将数据库中的记录全部转换到过,这样我们就可以得到表中的确切的数据,以便我们修改它容易 一些。
--------------------------------------------------------------------------------
 Editing.php
复制代码 代码如下:

  
  Editing an entry
  
  
  

Editing an entry


  

  
  
  
  
  
  
idx:
UserName:  value="">
LastName:  value="">
Free Text:  value="">

  ">
  

  
  
  

-------------------------------------------------- ----------------------------------
OK, this script is very simple. What we need to care about is that when the form prints out, it records the currently recorded data through the value attribute in the command. This data is passed from the 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 a field, the value of the field will change to the new value. We can then pass the new value to another script, which will change the value in the MySQL table.
 ------------------------------------------------ ----------------------------------
Editdb.php:
Copy code The 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 "< tr>
 
 
 
 
 ";
 while ($r = mysql_fetch_array ($result))
 {
$idx = $r["idx"];
$user = $r["UserName"];
$last = $r["LastName"] ;
$text = $r["FreeText"];
echo "

 
 
 ";
 }
Echo "
idx User Name Last Name Free Text
$last $text
";
 }
else
 {
echo "No data.";
 }
mysql_free_result($result);
include ('links.x');
 ?>

------------------------------------------------ -----------------------------------------------
Basically One thing of concern 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 as we explained in the MySQL section earlier. Another thing, note that this script changes the record with idx=$idx. If there are multiple records in the table with idx equal to $idx, these records will all 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 will check all fields, not just check idx.
Delete a record from the database:
Okay, deletion is easy. We still need two scripts: one to select the records to delete (basically the same as selecting the records to edit above), and one to actually delete and print the new table.
 ------------------------------------------------ ----------------------------------
 del.php

Copy code The code is as follows:

  
  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 "
idx User Name Last Name Free Text

  $idx
$user $last $dtext
";
  }
  else
  {
  echo "No data.";
  }
  mysql_free_result($result);
  include ('links.x');
  ?>
  
  

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/324096.htmlTechArticle然而,除了安装部分,有或多或少的针对于Windows的说明外,其它部分对所有的平台都是一样的。顺便说一下,关于安装部分,请看本站的安...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP image upload, store source code and preview_PHP tutorialNext article:PHP image upload, store source code and preview_PHP tutorial

Related articles

See more