About PHP combined with MySQL

Source: Internet
Author: User

I believe many PHP programmers in the PHP development of the database used in the MySQL database, and in the end why PHP development to combine the MySQL database, not also can use other databases, why not, then we will look together, in detail PHP combined with MySQL, Why PHP Development is a combination of MySQL.

Part I: My application tool.

Phpstudy: This package integrates the latest apache+php+mysql+phpmyadmin, one-time installation, without configuration can be used, is very convenient and easy to use PHP debugging environment. You do not need to download and install PHP, MySQL, Appche, simple and convenient.
First recognize the following phpstudy:

Click on "MySQL Manager" and select Mysql-front

The following interface appears:
After opening, enter into the official database interface.

This is just to show you the following MySQL, which will be followed by its specific operation.

In this part, the main problem that I have appeared is that when I open the localhost in Figure 5, there is no connection to MySQL, there is no way to choose to reload the phpstudy.

Part Two: Understanding the relationship between PHP, Apache, and MySQL.

There is a customer in an online shop bought a book, shop owner after receiving the demand will go to the manufacturers to pick up goods, the shopkeeper get goods to the goods to customers.
The flowchart is as follows:


We know that the customer and the shopkeeper do not communicate directly, but through the owner to exchange data, the owner to provide communication services. The relationship between PHP,Apache, and the database is like the relationship between the customer, the shopkeeper and the manufacturer. PHP needs some kind of data, send the request directly to Apache server,Apache then feedback this request to the database, the database takes out the response data to Apache server,Apache the server is sent to PHPagain.
1, why PHP and database can not communicate directly, have to pass Apache it?

For example: PHP and database are like two people of different nationalities, the former from China, the latter from the United States, the language is not Tong Lian communication is a problem, let alone business. There happens to be a person called Apache, that is, understand Chinese and understand English, the needs of PHP translated into English to tell the database, the database to take out the corresponding goods to Apache, Apache again to PHP.
The PHP language and database data do not recognize each other and need to be converted through Apache.
2, why Apache can not be a server, and do database, so less a link is not more convenient?
This design to a problem of the rationality of division of labor.
If the Apache and the database merge, it is the equivalent of Apache both as a shopkeeper and as a manufacturer, will greatly deepen the Apache server workload. When the data is small, Apache can withstand, when the data is large, Apache also has to bear the transportation and management of the Factory warehouse, the final benefits may also be greatly reduced, rather than the warehouse transportation and management of the work to the factory to do.

MySQL Database (db)
There are many databases in the world, MySQL is one of the most popular.
MySQL is a relational database management system developed by the Swedish MySQL AB company, currently owned by Oracle Corporation. MySQL is an associated database management system that keeps data in separate tables rather than putting all of the data in a large warehouse, which increases speed and increases flexibility. (MySQL database is equivalent to classifying goods into different warehouses, each warehouse is a small database, and the factory is a large database.) This makes it easy to access the goods and, if not classified, the storage efficiency is significantly reduced.

The RDBMS is the feature of the relational database management system (relational Management Systems):
1. The data appears in tabular form
2. Various record names for each behavior
3. Data fields corresponding to record names for each column
4. A number of rows and columns form a single sheet
5. A number of forms form database

Part III: Using php to manipulate MySQL database

1. Connect to the database using PHP scripts

PHP provides the mysql_connect () function to connect to the database. This function has 5 parameters, generally we only use the first 3.

Here you may ask, PHP can connect to the database that appache what to do. This explains that Apache is a server that builds a context in which PHP and the database can communicate. PHP and database These two people speak different languages and communicate through Apache, the simultaneous translation system.

. server specifies the servers to connect to. You can include a port number, such as "Hostname:port", or a path to a local socket, such as ":/path/to/socket" for localhost.
If PHP directive mysql.default_host is undefined (by default), the default value is ' localhost:3306 '.
. User username. The default value is the user name of the server process owner.
. Password password. The default value is a blank password.

PHP mysql_close is used to disconnect from the MySQL database. In general, the script will automatically disconnect after running, so this sentence can also not write. However, mysql_close () does not close the persistent connection established by Mysql_pconnect ().
To connect to a database:

<?phpheader ("Content-type:text/html;charset=utf-8"); $servername = "127.0.0.1";//server host address $username = "root";// User name of Access database $password = "root";//Access database password//phpstudy mysql has a default user name (root) and password (root)//create connection $conn = mysql_connect ($ ServerName, $username, $password);//Detect connection if (! $conn) {die    ("Connection failed:". Mysql_connect_error ());//die () outputs a message and disconnects. }echo "Connection succeeded"; Mysql_close ($conn);//close connection.?>

Databases are not accessible to everyone, only people with access to them. Let me show you how to add a user if the Mysql-front tool.


After adding a new user:


To access with a new user:

<?phpheader ("Content-type:text/html;charset=utf-8"); $servername = "127.0.0.1";//server host address $username = "Sunwukong" ;//Access database user name $password = "Jingubang";//Access database password//phpstudy mysql has a default user name (root) and password (root)//create connection $conn = mysql_connect ($ ServerName, $username, $password);//Detect connection if (! $conn) {die    ("Connection failed:". Mysql_connect_error ());//die () outputs a message and disconnects. }echo "Connection succeeded"; Mysql_close ($conn);//close connection.?>

The connection was successful.

2. Create a database

PHP uses mysql_query (sql,connection) to create or delete databases. mysql_query () Sends the statement SQL for the search query through the established connection connection to the database. The database responds to the action after it reads.

<?phpheader ("Content-type:text/html;charset=utf-8"); $servername = "127.0.0.1";//server host address $username = "Sunwukong" ;//Access database user name $password = "Jingubang";//Access database password//phpstudy mysql has a default user name (root) and password (root)//create connection $conn = mysql_connect ($ ServerName, $username, $password);//Detect connection if (! $conn) {die    ("Connection failed:". Mysql_connect_error ());//die () outputs a message and disconnects. }echo "Connection succeeded"; echo "</br>"; $sql = "CREATE Database Zhubajie";//create is the SQL language that creates the statement of the databases, here is a creation named "Zhubajie "The string for the database. $dingpa = mysql_query ($sql, $conn);//sends the $SQL query statement to the database. if (! $dingpa) {die    ("Failed to create database:". mysql_error ());} echo "created successfully"; Mysql_close ($conn);//close connection.?>

After running,

Sometimes you will find that the above PHP file run will show the error shown:


This error occurs because you passed $username = "Sunwukong"; When the user name accesses the database, the user is not granted permission when it is created in MySQL.

3. Delete Database

Deleting a database and creating a database is also done through mysql_query.

4. Create data table data

We will create a table called "Myguests" with 5 columns: "ID", "FirstName", "LastName", "email" and "reg_date":
To create a data table myguests:

CREATE TABLE myguests (ID INT (6) UNSIGNED auto_increment PRIMARY key,firstname varchar () not null,lastname varchar (in) N OT null,email VARCHAR (+), reg_date TIMESTAMP)

The data table shows the following:

Note that the header row in the table displayed by the Object Browser specifies the type of data and other properties.


is the specific data graph.
Let's look at the specific code:

We used the MySQL extension in early PHP versions. However, this extension is not recommended for use in 2012. Instead of mysqli extensions and PDO, the individual is using the mysqli extension. The mysqli extension is an extension of the MySQL extension, and the use of the two is no different, but the former is more powerful than the latter. The following is the MYSQLI process-oriented (it also has an object-oriented encoding method) of the encoding operation of MySQL, you can compare it with the above MySQL extension encoding method of the difference.

Auto INCREMENT-Set the value of the MySQL field to automatically grow by 1 each time a new record is added
PRIMARY KEY-Sets a unique identifier for each record in the data table. The PRIMARY KEY for the usual column is set to the ID value, which is used with auto_increment. Each table should have a primary key (this column is "zhubajie_t"), and the primary key must contain a unique value. (People here may not understand, but to the back)

Not null-each row must contain a value (cannot be null), and a NULL value is not allowed.
Default value-Set defaults
UNSIGNED-Using unsigned numeric types, 0 and positive numbers
The above three properties can be added to the column as well as the data type of the specified column. (Here's a good understanding).

5. Delete table data

In fact, PHP combined with MySQL development has long become a habit, like men and women, of course, there are special circumstances.

Related recommendations:

Summary of the MySQL database optimization

Take MySQL, for example, to get you to understand those databases.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.