MySQL Connect

PHP MySQL Connect

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:

  1. MySQLi (MySQL Improved): Designed specifically for MySQL databases.
  2. PDO (PHP Data Objects): Can work with multiple different database systems (MySQL, PostgreSQL, SQLite, etc.).

In this tutorial, we will focus on MySQLi using the procedural approach, as it is the most straightforward for beginners.


Opening a Connection

To open a connection, use the mysqli_connect() function. You must provide the server name (usually localhost), the username, and the password.

MySQL Connection Example

<?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!"; ?>

Always Check for Errors!

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!


Exercise

?

Which function is used to open a procedural connection to a MySQL server?