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

Leave a Reply

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

error: Content is protected !!