๐Ÿ˜ PHP MySQL Integration โ€“ MySQLi & PDO Explained with Examples


๐Ÿงฒ Introduction โ€“ Why Learn PHP with MySQL?

Combining PHP (server-side scripting) and MySQL (relational database) is one of the most popular ways to build dynamic and database-driven websites. From blogs and eCommerce sites to user management and CMS systems, this duo powers a significant portion of the internet.

๐ŸŽฏ What You’ll Learn:

  • How to connect PHP to MySQL using MySQLi and PDO
  • How to perform CRUD operations (SELECT, INSERT, UPDATE, DELETE)
  • Explanation of each code snippet
  • Secure coding practices to avoid SQL injection
  • Real-world examples of usage

โš™๏ธ Connecting PHP with MySQL

โœ… Method 1: Using MySQLi (MySQL Improved)

<?php
$conn = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($conn->connect_error) {
    die("โŒ Connection failed: " . $conn->connect_error);
}
echo "โœ… Connected successfully";
?>

๐Ÿง  Explanation:

  • new mysqli(...): Initializes a new MySQLi object to open a connection.
  • "localhost": MySQL server location.
  • "username", "password", "database": Your credentials and database name.
  • connect_error: If the connection fails, this property contains the error.
  • die(): Terminates the script with an error message.

โœ… Method 2: Using PDO (PHP Data Objects)

<?php
try {
    $pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "โœ… Connected successfully";
} catch (PDOException $e) {
    echo "โŒ Connection failed: " . $e->getMessage();
}
?>

๐Ÿง  Explanation:

  • new PDO(...): Creates a new PDO connection.
  • setAttribute(...): Configures PDO to throw exceptions on errors.
  • catch (PDOException $e): Catches and displays errors gracefully.

๐Ÿ’พ CRUD Operations in PHP + MySQL

๐Ÿ” SELECT โ€“ Retrieving Data (MySQLi)

<?php
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {
    echo $row['name'] . " - " . $row['email'] . "<br>";
}
?>

๐Ÿง  Explanation:

  • query($sql): Sends the SQL query to the database.
  • fetch_assoc(): Fetches one row at a time as an associative array.
  • echo: Outputs the name and email fields of each user.

โž• INSERT โ€“ Adding New Records (Prepared Statement – MySQLi)

<?php
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);

$name = "Alice";
$email = "alice@example.com";
$stmt->execute();
?>

๐Ÿง  Explanation:

  • prepare(): Prepares an SQL query with placeholders.
  • bind_param("ss", ...): Binds PHP variables to placeholders. "ss" = 2 strings.
  • execute(): Runs the query with bound values.

โœ… Prevents SQL injection because it doesn’t allow SQL code to be injected into variables.


๐Ÿ“ UPDATE โ€“ Modifying Existing Records

<?php
$stmt = $conn->prepare("UPDATE users SET email = ? WHERE id = ?");
$stmt->bind_param("si", $email, $id);

$email = "alice_updated@example.com";
$id = 1;
$stmt->execute();
?>

๐Ÿง  Explanation:

  • "UPDATE ... WHERE id = ?": Updates the row with the given id.
  • "si": First is a string (email), second is an integer (id).
  • Replaces the old email of user with ID 1.

โŒ DELETE โ€“ Removing Records

<?php
$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i", $id);

$id = 1;
$stmt->execute();
?>

๐Ÿง  Explanation:

  • DELETE FROM users WHERE id = ?: Deletes a row matching the id.
  • "i" means integer.
  • Deletes the user with ID = 1.

๐Ÿ›ก๏ธ Best Practices for PHP + MySQL

๐Ÿ“Œ Use Prepared Statements: Always bind values to prevent injection.

๐Ÿ” Secure Credentials:

  • Store DB usernames/passwords in a .env file.
  • Load them with getenv() or a config array.

๐Ÿ“Š Use Specific User Privileges:

  • Create a user with limited privileges (not root).
  • Only allow access to required tables and commands.

๐Ÿ” Close Connections:

$conn->close(); // for MySQLi
unset($pdo);    // for PDO

๐Ÿ“Š Real-World Applications

Use CaseRole of PHP + MySQL
Blog CMSStore posts, comments, user info
E-commerceStore orders, product inventory, customers
Admin DashboardShow charts, filter user data
Feedback FormCapture input and store to database
AuthenticationStore and verify login credentials

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

PHP offers powerful tools to interact with MySQL using MySQLi and PDO. Learning both connection styles, practicing CRUD, and understanding prepared statements sets you up for full-stack development.

๐Ÿ” Key Takeaways

  • Use MySQLi or PDO to connect to MySQL
  • Always use prepared statements for security
  • Understand and implement all CRUD operations
  • Use environment files to secure your credentials

โš™๏ธ Real-World Relevance
PHP and MySQL power a huge number of web systems. Mastery of their integration means you’re ready to build dynamic and secure data-driven applications.


โ“ FAQ โ€“ PHP MySQL Integration

โ“ Should I use MySQLi or PDO?
โœ… PDO is more flexible (supports multiple DBMS). MySQLi is faster for MySQL-specific apps.

โ“ How to prevent SQL injection in PHP?
โœ… Use prepared statements (prepare() and bind_param()/bindValue()).

โ“ Can I use MySQL in PHP without installing anything?
โœ… Yes, if you’re using XAMPP, WAMP, or LAMP, both MySQL and PHP are included.

โ“ Is it safe to store DB credentials in PHP code?
โŒ No. Use .env or separate config files outside web root.

โ“ What tool can help me manage MySQL easily?
โœ… Tools like MySQL Workbench, DBeaver, and phpMyAdmin help visualize and manage DBs.



Share Now :

Leave a Reply

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

Share

๐Ÿ˜ MySQL with PHP

Or Copy Link

CONTENTS
Scroll to Top