Current location - Quotes Website - Team slogan - How does PHP connect to MySQL?
How does PHP connect to MySQL?
Connecting PHP to mysql database is a skill that PHP novices must master. As long as you master the operations of adding, deleting, modifying and checking the database in PHP, you can write some simple and commonly used programs. Such as message forms, news pages, etc. This paper mainly introduces two common methods of connecting PHP to Mysql database in detail.

The following two methods of connecting PHP to mysql database are introduced in detail through specific code examples.

Mysqli connects to the database, and pdo connects to the database.

The first method: use mysql to connect to MySQL database.

The code example is as follows:

& lt? Server-side programming language (abbreviation of professional hypertext preprocessor)

$ host = ' 127 . 0 . 0 . 1 ';

$ user = ' root

$ password = ' root

$ dbName = ' php

$ link = new MySQL($ host,$user,$password,$ dbName);

if($ link-& gt; Connection error) {

Die ("Connection failed:". $ link-& gt; Connection _ error);

}

$ sql = " select * from admins

$ RES = $ link-& gt; Query ($ SQL);

$ data = $ RES-& gt; fetch _ all();

var _ dump($ data);

After a series of join operations, we create an sql statement to check the data table. In the above code, we need to create some variables, such as database user name, database name password and so on. Then we connected the database named php in an object-oriented way. Then use if conditional statement and connect-error method to judge whether PHP successfully connects to the database.

Here, let's log in to phpmyadmin and see if there is a php database. We can know that there is a php database from the picture below.

Finally, visit through the browser, and the results are as follows:

As can be seen from the figure, we have successfully connected to the php database and can query the data table information.

The second method: use PDO to connect to the database.

The code example is as follows:

& lt? Server-side programming language (abbreviation of professional hypertext preprocessor)

$ host = ' 127 . 0 . 0 . 1 ';

$ user = ' root

$ password = ' root

$ dbName = ' php

$ pdo = new PDO ("MySQL: host = $ host; dbname=$dbName ",$user,$ password);

$ sql = " select * from admins

$ data = $ PDO-& gt; Query ($ SQL)->; fetch();

var _ dump($ data);

The above steps of connecting php to Mysql are detailed descriptions of two common methods of connecting PHP to database to query data. For more related tutorials, please visit the mysql video tutorial of PHP Chinese website. Welcome to learn.