Home>Article>Backend Development> How to connect php to mysql database

How to connect php to mysql database

silencement
silencement Original
2019-09-24 15:06:32 2786browse

How to connect php to mysql database

Before connecting to the MySQL database, you must specify the following information:

MySQL data source name or DSN: Specify the address of the MySQL database server. You can use an IP address or server name, for example, 127.0.0.1 or localhost

MySQL database name: Indicates the name of the database to connect to.

Username and Password: Specify the username and password of the MySQL user used to connect to the MySQL database server. This account must have sufficient permissions to access the database specified above.

We will use:

Local MySQL database server, so that the DSN is localhost.

In classicmodels as a sample database.

Root account with blank password, just for demonstration.

Connecting to MySQL Steps

First, for convenience, we will create a new PHP file for database configuration, dbconfig.php. This file contains all configured parameters:


      

Second, we create a new PHP file called phpmysqlconnect.php:

getMessage()); }

How the script works

dbconfig.php uses the require_once function to include the file in the script.

In the try block, we create a new PDO object with three parameters: connection string, username and password. The connection string consists of the variables $host and $dbname in the file dbconfig.php.

If the connection to the MySQL database is successfully established, we will display a success message. If there are any errors or exceptions, PHP will issue a PDOException

containing a detailed error message. We call the object's getMesage() method PDOException to get the detailed message to be displayed.

The above is the detailed content of How to connect php to mysql database. For more information, please follow other related articles on the PHP Chinese website!

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
Previous article:How php and nginx interact Next article:How php and nginx interact