Home > Backend Development > PHP Tutorial > How to connect php to database

How to connect php to database

爱喝马黛茶的安东尼
Release: 2023-04-07 08:10:01
Original
22254 people have browsed it

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.

How to connect php to database

Open your own php document, enter the following code to connect to your database.

<?php 
$link = mysql_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;&#39;); 
if (!$link) {  
    die(&#39;Could not connect to MySQL: &#39; . mysql_error()); 
} 
else 
    echo &#39;Connection OK&#39;;
mysql_close($link);
?>
Copy after login

Of course, the password here in the database is empty, everyone must fill in the correct Mysql password.

How to connect php to database

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.

How to connect php to 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.

How to connect php to database

Modify the above d code to:

<?php 
$link = mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;&#39;); 
if (!$link) {  
    die(&#39;Could not connect to MySQL: &#39; . mysqli_error()); 
} 
else 
    echo &#39;Connection OK&#39;;
mysqli_close($link); 
?>
Copy after login

How to connect php to database

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!

How to connect php to database

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template