Establishing a connection between PHP and MySQL is a fundamental aspect of web development. PHP provides three primary methods for connecting to a MySQL database:
Procedural Style
<?php
$host = “localhost”;
$user = “root”;
$password = “”;
$dbname = “testdb”;
$conn = mysqli_connect($host, $user, $password, $dbname);
if (!$conn) {
die(“Connection failed: ” . mysqli_connect_error());
}
echo “Connected successfully!”;
?>
Object-Oriented Style
<?php
$host = “localhost”;
$user = “root”;
$password = “”;
$dbname = “testdb”;
$conn = new mysqli($host, $user, $password, $dbname);
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
echo “Connected successfully!”;
?>
Using PDO (PHP Data Objects)
<?php
$host = “localhost”;
$dbname = “testdb”;
$user = “root”;
$password = “”;
try {
$conn = new PDO(“mysql:host=$host;dbname=$dbname”, $user, $password);
// Set Error Handling Mode
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo “Connected successfully!”;
} catch (PDOException $e) {
echo “Connection failed: ” . $e->getMessage();
}
?>
Summary
Method | Style | Security | Recommended? |
MySQLi | Procedural | Medium (OK) | ✅ Yes |
MySQLi | Object-Oriented | Medium–High | ✅✅ Best |
PDO | Object-Oriented | High (with prepared statements) | ✅✅✅ Best |
Hi,
Many local businesses lose out on customers due to poor local SEO.
When I checked your site, I found:
• Missing Google Business Profile details
• Lack of location-based keywords
• No local citations or reviews
If you’re looking to bring in more local traffic, I’d love to help.
We can help optimize your website for better conversions. Interested?
Thank you,
Manshi Sharma
SEO Expart