AskHandle

AskHandle Blog

How to Efficiently Connect to a MySQL Database using PHP

September 4, 2025Jessy Chan3 min read

How to Efficiently Connect to a MySQL Database using PHP

Connecting a MySQL database to a PHP application is crucial for web development. This guide outlines best practices for establishing this connection, along with useful tips and code examples.

Understanding the Basics

What are the essential components for connecting to a MySQL database using PHP? The main elements are:

  • Database server (MySQL)
  • PHP script
  • Connection between the script and the database

The database server manages the data needed by your application. PHP scripts execute queries and interact with the database to retrieve or manipulate data. The connection acts as a bridge for communication.

Establishing a Connection

How can you create a connection to a MySQL database in PHP? Use the mysqli extension for a secure interaction. The mysqli_connect() function establishes the connection as shown below:

php
1<?php
2$servername = "localhost";
3$username = "your_username";
4$password = "your_password";
5$database = "your_database";
6
7$conn = mysqli_connect($servername, $username, $password, $database);
8
9if (!$conn) {
10    die("Connection failed: " . mysqli_connect_error());
11}
12
13echo "Connected successfully";
14?>

Replace localhost, your_username, your_password, and your_database with your MySQL configuration. The mysqli_connect_error() function provides an error message if the connection fails.

Handling Connection Errors

Why is it important to manage connection errors? Handling errors ensures application stability. Use mysqli_connect_errno() to check for connection issues. Here’s how to implement error handling:

php
1<?php
2$servername = "localhost";
3$username = "your_username";
4$password = "your_password";
5$database = "your_database";
6
7$conn = mysqli_connect($servername, $username, $password, $database);
8
9if (mysqli_connect_errno()) {
10    die("Connection failed: " . mysqli_connect_error());
11}
12
13echo "Connected successfully";
14?>

Error handling enhances user experience by providing informative messages in unexpected situations.

Executing SQL Queries

How do you execute SQL queries after establishing a MySQL connection? Use the mysqli_query() function for querying the database. Below is an example of a simple SELECT query:

php
1<?php
2$sql = "SELECT * FROM users";
3$result = mysqli_query($conn, $sql);
4
5if (mysqli_num_rows($result) > 0) {
6    while ($row = mysqli_fetch_assoc($result)) {
7        echo "ID: " . $row['id'] . " - Name: " . $row['name'] . "<br>";
8    }
9} else {
10    echo "No records found";
11}
12
13mysqli_free_result($result);
14mysqli_close($conn);
15?>

Here, records from the users table are fetched and displayed. Always remember to free the result set with mysqli_free_result() and close the connection using mysqli_close() to maintain application performance.

Parameterized Queries

What measures can be taken to secure your application against SQL injection? Using parameterized queries is a best practice. These queries separate SQL code from user input. Here’s an example:

php
1<?php
2$sql = "SELECT * FROM users WHERE id = ?";
3$stmt = mysqli_prepare($conn, $sql);
4$id = 1;
5
6mysqli_stmt_bind_param($stmt, "i", $id);
7mysqli_stmt_execute($stmt);
8
9$result = mysqli_stmt_get_result($stmt);
10
11while ($row = mysqli_fetch_assoc($result)) {
12    echo "ID: " . $row['id'] . " - Name: " . $row['name'] . "<br>";
13}
14
15mysqli_free_result($result);
16mysqli_close($conn);
17?>

Parameterized queries ensure that user input is treated as data, reducing the risk of executing malicious code.