Home >Backend Development >PHP Tutorial >How to connect php to database
First, create a new PHP document in our web directory. I named 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.
Related recommendations: "php tutorial"
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:
<?php $link = mysqli_connect('localhost','root',''); if (!$link) { die('Could not connect to MySQL: ' . mysqli_error()); } else echo 'Connection OK'; mysqli_close($link); ?>
Enter the browser and enter the local loop address Connect, Connection ok will appear! The above error is gone and the database connection is successful!
The above is the detailed content of How to connect php to database. For more information, please follow other related articles on the PHP Chinese website!