Home  >  Article  >  Backend Development  >  A simple web example code analysis combining php and database (php beginners)

A simple web example code analysis combining php and database (php beginners)

WBOY
WBOYOriginal
2016-08-08 09:29:09949browse

This is a basic tutorial. No weird code, just some basics. There are currently a large number of tutorials based on UNIX machines, this tutorial will focus on Windows-based platforms.

However, except for the installation part, which has more or less Windows-specific instructions, the other parts 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 database records;
 3. Modify the database records;
 4. Delete the database records.
 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;
 You will see an answer such as:
 Query OK, 1 row affected ( 0.17 sec) Great, 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 the 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 see what it looks like to view the table 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 | | |
  +----------+---------------+------+-----+------- --+-------+
  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 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'); Okay, now we can look at the contents of the table again:
 MySQL> select * from tbl;
 The result this time 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 me some explanations. 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 whose UserName is "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 searches two fields and changes the value of UserName
Combining PHP and MySQL
 In this section, we will build a custom PHP-based web site, using To control the MySQL table created earlier.
 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 Used to modify records in the table 4. del.php3 is used to delete records in the table
First, we want to check the database and take a look at the following script:
---------------- -------------------------------------------------- ---------------
  Index.php
 
 Web Database Sample Index
  
    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 = $r["UserName"];
 $last = $r["LastName"];
 $text = $r["FreeText"];
 echo "
& lt; td & gt; $ IDX & LT;/TD & GT;
& LT; TD & GT; $ User & LT;/TD & GT;
& LT; TD & GT; $ last & lt;
& lt; td & gt; $ Text & LT;/TD & GT;
& LT;/TR & GT; " ;
 }
  echo "
User Name Last Name Domain Name< ;/td>
 
Request Date
";
 }
else
 {
  echo "No data.";
 }
  mysql_free_result($result);
  include ('links.x');
  ?>
  
  
---------------------------------------- ------------------------------------------
 Okay, here are some Description:
 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, it 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 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 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 the execution is successful, the function will return A MySQL result identifier for a 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" when argument= The command you want to execute when true, "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. The format is as follows:
 while (argument)) {
 "something to do";
 }
 The while loop will repeat continuously when argument=true, executing the instruction set 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 "
 $idx
 
  $last
  $text
 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 containing 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 in each page.
 


 php3">Add a new entry to the DataBase
 
  • Edit an entry
     
  • Delete an entry from the DataBase
     
     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


      

      
      
            
      
      
    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="">

      ">
      

      
      
      


    ------------------------------------------------- ----------------------------------
     Okay, 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)
     {
     echo "Found these entries in the database:

    ";
     echo "< tr>
     
     
     Name
     r["idx"];
     $user = $r["UserName"];
     $last = $r["LastName"];
     $text = $r["FreeText"];
     echo "
      
      
      
       
     /tr>

     ?> ;


    ------------------------------------------------- ----------------------------------
     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 syntax as we explained in the previous MySQL section. 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 the 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 "
    idx User Name
    $idx $user $last $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 $dtext
    ";
      }
      else
      {
      echo "No data.";
      }
      mysql_free_result($result);
      include ('links.x');
      ?>
      
       

    http://www.jb51.net/article/27814.htm

    以上就介绍了php和数据库结合的一个简单的web实例 代码分析 (php初学者),包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

  • 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