Creating connectivity between PHP and MySQL

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

MethodStyleSecurityRecommended?
MySQLiProceduralMedium (OK)✅ Yes
MySQLiObject-OrientedMedium–High✅✅ Best
PDOObject-OrientedHigh (with prepared statements)✅✅✅ Best

One thought on “Creating connectivity between PHP and MySQL

  1. 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

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!