Home > Article > Backend Development > How to connect to database using php
How to use php to connect to the database
First, create a new PHP document in our web directory. Name it testMysql.php, you can name your document whatever you want.
Open your own php document, enter the following code to connect to your database.
<?php $link = mysql_connect('localhost','root',''); if (!$link) { die('Could not connect to MySQL: ' . mysql_error()); } else echo 'Connection OK';mysql_close($link); ?>
Of course, the password here in the database is empty, everyone must fill in the correct Mysql password.
Enter the browser, enter the local loop address to connect, and Connection ok will appear! At this point, we have completed the connection to the database.
It is possible that you may find the following error. This is because your PHP version is relatively new. You are required to use the Mysqli function to connect or PDO to connect. This is to ensure that everyone is connected. Database security.
Modify the above d code to
Enter the browser, enter the local loop address to connect, and Connection ok will appear! The above error is gone and the database connection is successful!
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of How to connect to database using php. For more information, please follow other related articles on the PHP Chinese website!