Before PHP can talk to MySQL, you need to open a connection. The classic way is with mysqli_connect(). You give it the server, username, password, and database name, and if everything works, you get a connection object you can use to run queries.
Connecting with mysqli_connect
Pass four arguments to mysqli_connect(): the host (usually localhost), your username, your password, and the database name. It returns a connection object. If it fails, it returns false, and mysqli_connect_error() tells you what went wrong.
<?php
$conn = mysqli_connect("localhost", "root", "", "mydb");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Try it Yourself โ
PDO vs MySQLi
PHP actually gives you two ways to talk to MySQL: MySQLi (MySQL improved) and PDO (PHP Data Objects). MySQLi is MySQL-specific and has both a procedural and object-oriented interface. PDO supports twelve different database drivers โ not just MySQL. PDO also supports prepared statements natively in a cleaner way. If you're starting a new project, PDO is usually the better choice.
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected using PDO";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
Try it Yourself โ
Closing the Connection
PHP automatically closes database connections when your script finishes, but it's good practice to close them explicitly when you're done. With MySQLi, use mysqli_close($conn). With PDO, set the connection object to null.