php-mysqlHow to connect to a MySQL database using PHP?
To connect to a MySQL database using PHP, you need to use the mysqli_connect()
function. This function takes four parameters: the hostname, username, password, and database name.
$hostname = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = mysqli_connect($hostname, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
Output example
Connected successfully
The mysqli_connect()
function:
$hostname
: The hostname of the MySQL server. This is usuallylocalhost
if the MySQL server is running on the same machine as the PHP script.$username
: The username of the MySQL user.$password
: The password of the MySQL user.$dbname
: The name of the database to connect to.
The function returns a connection resource if the connection is successful, or FALSE
if the connection fails.
Helpful links
More of Php Mysql
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to join tables with PHP and MySQL?
- How to get the version of MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to count the number of resulting rows in a MySQL database using PHP?
- How to use a MySQL union in PHP?
- How to set a timeout for MySQL query in PHP?
- How to create an SSL connection to MySQL using PHP?
- How to get the last insert ID in PHP MySQL?
- How to fetch data from MySQL in PHP?
See more codes...