To create a smooth connection between PHP and a MySQL database for effective data storage, retrieval, and management, we can use PHP’s mysqli or PDO (PHP Data Objects) extension. The aim is to build a secure, scalable, and functional backend system. This involves setting up database credentials, managing any connection errors, and running SQL queries for CRUD operations.
It’s important to use prepared statements to guard against SQL injection, ensuring the application stays secure. This goal is centered on enhancing the interaction between PHP and MySQL to support strong, dynamic, and data-driven web applications.
By following the below steps, you can connect PHP and MySQL Database in different ways.
1. Use mysqli to Connect
<?php
// Database connection details
$host = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database_name";
// Create a connection
$conn = mysqli_connect($host, $username, $password, $database);
// Check the connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully!";
?>
2. Use PDO (PHP Data Objects)
PDO provides a more secure and flexible way to connect to a database and is recommended for larger projects.
<?php
try {
// Data Source Name (DSN)
$dsn = "mysql:host=localhost;dbname=your_database_name";
$username = "your_username";
$password = "your_password";
// Create a PDO instance
$pdo = new PDO($dsn, $username, $password);
// Set the error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully!";
} catch (PDOException $e) {
// Handle connection error
echo "Connection failed: " . $e->getMessage();
}
?>
3. Execute Queries
<?php
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// Output each row
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "
";
}
} else {
echo "No records found.";
}
// Close the connection
mysqli_close($conn);
?>
We hope this might be helpful for you.