PHP introductory tutorial-database operation_PHP tutorial

WBOY
Release: 2016-07-13 17:09:53
Original
989 people have browsed it

php tutorial introductory tutorial-database tutorial operation

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 the records in 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 tutorial 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 a table with the following fields:
Index number - integer
Username - a string with a maximum length of 30
User last name - a string with a maximum length of 50
Free message - string with maximum length 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 | | 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:
The reason why Empty set (0.07 sec) gets this result is because we have not inserted any data into the table. Let's insert some data into the table by typing:
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 take a 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 contents 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 type it in 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 using 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 searches two fields and changes the value of UserName

Combining PHP and MySQL
In this part, we will create a simple PHP-based web site to control the MySQL table created earlier. ​
​We will create 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

  
  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 Name Last Name Domain Name Request Date
$idx $user $last $text
";
  }
  else
  {
  echo "No data.";
  }
  mysql_free_result($result);
  include (’links.x’);
  ?>
  
   
--------------------------------------------------------------------------------
  好,下面给出一些说明:
  我们先用正常的html标签创建thml文档。当我们想从html中出来转入PHP中时,我们用来结束PHP部分。
  mysql_connect() 命令告诉PHP建立一个与MySQL服务器的连接。如果连接建立成功,脚本将继续,如果不成功,则打印出die命令的信息“Problem connecting to Database”(如果要看关于mysql_connect的更多的信息和其它的PHP函数,可以去http://www.php.net下的文档中查找)。
  现在,如果MySQL是按照我们上面所讨论的那样安装的,就足够了。但是如果你使用的是预装的MySQL(象ISP),你应该使用下面的命令:
  mysql_connect (localhost, username, password);
  我们可以将$query设成我们想在MySQL中执行的查询,然后使用mysql_db_query命令来执行它:
  $result = mysql_db_query("example", $query);
  这时,"example"表示数据库的名字并且$query是要进行的查询。
  我们使用MySQL命令select(象上面所描述的)来从表中取得所有的数据:
  $query = "select * from tbl";
  简单地解释一下$result的作用,如果执行成功,函数将返回一个查询结果的一个MySQL结果标识符,如 果出错则返回false。返回的不是结果而是一个标识符,可以在后面将它转换成我们所需的信息。
  现在,我们想检查一下在数据库中是否存在有记录,并且如果有则将结果按照html的表格结构打印出来。为了检查是否存在数据,我们使用if命令和下面的语法:
  if (argument) {
  "do something;"
  } else {
  "do something different;"
  } 
  这时"do something"当argument=true时你所要执行的命令,"do something different"为当argument =false时所要执行的命令。
  注意我们使用echo命令来输出一些html标签来建立html的表格结构。只有从PHP命令输出的文本才会被 看成html内容 - PHP命令本身是不会看成html内容的。我们使用的另一个命令是while指令,使用格式如下:
  while (argument)) {
  "something to do";
  }
  while循环在argument=true时会不停地重复,执行在{}中的指令集。
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
​$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 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.
Using a form to add data Let’s take a look at the following code:
-------------------------------------------------- -------------------------------

Add an entry to the database


Add an entry




 UserName:
​ ​   

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




-------------------------------------------------- -------------------------------
Assuming you are familiar with forms, this is a fairly simple script. We designed a form based on the html page, which calls the add2tbl.php3 script after submission. The form now consists of 4 fields corresponding to the MySQL table: 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 for convenience only and is not required.
We once again use the include command (as explained earlier) to add links.
  让我们看一下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  
  注意,我在脚本中所作的注释。使用一个注释可以用"//",服务器将忽略此行的后面部分。
 

Simple, isn’t it? Edit a record from database: Let us assume that we want to modify a record that exists in the database. Earlier, we saw that there is a SQL command called set that is used to set the value of a field that exists in the database. We will use this command to modify an entire record in the database. Consider the following script:
-------------------------------------------------- -------------------------------
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’);
​?>


-------------------------------------------------- ----------------------------------
As you can see, the code here is somewhat familiar. The first part just prints out the contents of the table in the database. Note that one line is different:
$idx
This line creates a link to editing.php3 and passes some variables to the new script. It is very similar to the form method, except that links are used. We convert information into: variables and values. Note that in order to print out the " symbol, we need to use " otherwise the server will see it as part of the PHP script and use it as the printed message.
We want to convert all the records in the database to , so that we can get the exact data in the table so that we can modify it easier.
-------------------------------------------------- -------------------------------
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:
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 "
idx User Name Last Name Free Text
$idx $user $last $text
";
}
else
​{
echo "No data.";
}
​mysql_free_result($result);
​include (’links.x’);
​?>
-------------------------------------------------- ----------------------------------
Basically the 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

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/629705.htmlTechArticlephp教程入门教程-数据库教程操作 在这个教程中,我们将一步一步地建立一个小的网站,使用了PHP和MySQL的下面特性: 1. 查看数据库; 2. 编...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!