Before you can access or modify data in a MySQL database, you must first open a connection to the database server.
In PHP, there are two primary ways to connect to a MySQL database:
In this tutorial, we will focus on MySQLi using the procedural approach, as it is the most straightforward for beginners.
To open a connection, use the mysqli_connect() function. You must provide the server name (usually localhost), the username, and the password.
<?php $servername = "localhost"; $username = "root"; $password = "your_password";// Create connection $conn = mysqli_connect($servername, $username, $password);
// Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully!"; ?>
Notice the if (!$conn) check. If the connection fails (e.g., incorrect password), the die() function immediately stops the script from running and prints the exact error message. This saves you from hours of debugging!
Which function is used to open a procedural connection to a MySQL server?