How to Connect Database with PHP
Learn how to establish a connection between PHP and a MySQL database using the mysqli extension
Understand the Problem
Problem Statement
This tutorial demonstrates how to connect a PHP script to a MySQL database. You'll learn to configure database credentials, establish a connection using the mysqli extension, handle connection errors, and properly close the connection. This is a fundamental skill for any PHP developer working with database-driven applications.
Constraints
- MySQL server must be running and accessible
- Database credentials (host, username, password, database name) must be valid
- PHP must have MySQL extension enabled
- Connection should be established before performing database operations
- Connection should be closed when no longer needed
Examples
$host = 'localhost';
$username = 'root';
$password = 'mypassword';
$database = 'test_db';Connected to the database successfullyWith valid MySQL credentials and a running MySQL server, the mysqli constructor successfully establishes a connection and outputs the success message.
$host = 'localhost';
$username = 'invalid_user';
$password = 'wrong_password';
$database = 'nonexistent_db';Connection failed: Access denied for user 'invalid_user'@'localhost' (using password: YES)When using invalid credentials or attempting to access a non-existent database, the connection attempt fails and an appropriate error message is displayed.
Solution
/*
* Note: This is a conceptual C equivalent using MySQL C API
* PHP's database connectivity is typically not replicated in pure C
* for web development purposes, but here's how you might approach it
*/
#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
MYSQL *conn;
// Initialize MySQL connection
conn = mysql_init(NULL);
if (conn == NULL) {
fprintf(stderr, "MySQL initialization failed\n");
return 1;
}
// Database configuration
const char *host = "localhost";
const char *user = "your_username";
const char *password = "your_password";
const char *database = "your_database";
// Establish connection
if (mysql_real_connect(conn, host, user, password, database, 0, NULL, 0) == NULL) {
fprintf(stderr, "Connection failed: %s\n", mysql_error(conn));
mysql_close(conn);
return 1;
}
printf("Connected to the database successfully\n");
// Perform database operations here
// Close connection
mysql_close(conn);
return 0;
}This C code demonstrates the MySQL C API equivalent of the PHP database connection. It initializes a MySQL connection object, configures the database parameters, attempts to connect using mysql_real_connect(), handles connection errors with appropriate error messages, and closes the connection when finished. The mysql.h header provides the necessary MySQL client library functions.