search
HomeBackend DevelopmentPHP TutorialPHP introductory tutorial-database operation_PHP tutorial

PHP introductory tutorial-database operation_PHP tutorial

Jul 13, 2016 pm 05:09 PM
phpstepGetting Started TutorialexistlandEstablishoperateTutorialdatabasethis

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
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools