search
HomeBackend DevelopmentPHP TutorialA 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

Jul 21, 2016 pm 03:25 PM
phpwebcodeanalyzebeginnerandInstallExampledatabasehaveHoweverofSimplecombinepart

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

 
 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 "";
 }
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 open the PHP part. This tells the web server to treat the following text as PHP syntax instead of ordinary html. 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
User Name Last Name Domain Name Request Date
$last $text
$idx< ;/td>
 
$user $last $text

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.