๐Ÿงช PHP Advanced Topics
Estimated reading: 4 minutes 27 views

๐Ÿ—„๏ธ PHP MySQL โ€“ Connect, Query, and Manage Databases with PHP

Learn how to interact with MySQL databases using PHP to build dynamic, data-driven applications efficiently and securely.


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

PHP and MySQL are a classic duo in web development. MySQL is an open-source relational database management system (RDBMS), and PHP offers native support for connecting and executing SQL queries. Together, they power thousands of websites, applications, and content management systems like WordPress, Joomla, and Drupal.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • How to connect PHP to a MySQL database
  • How to run SQL queries using mysqli
  • How to handle data securely
  • Common operations like SELECT, INSERT, UPDATE, DELETE

๐Ÿ—„๏ธ PHP MySQL

You can connect to MySQL using:

ExtensionDescription
mysqliObject-oriented and procedural; modern and secure
PDOMore abstract and flexible (supports multiple DBs)

This article focuses on mysqli for native MySQL interaction.


๐Ÿ”— Connect to MySQL using mysqli

$host = "localhost";
$user = "root";
$pass = "";
$db   = "test_db";

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

โœ… Use $conn->connect_error to catch connection issues
โœ… Replace credentials with secure values in production


๐Ÿ” SELECT Data from MySQL

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

while ($row = $result->fetch_assoc()) {
    echo "ID: {$row['id']} - Name: {$row['name']}<br>";
}

๐Ÿ“Œ Always check if $result->num_rows > 0 before looping


๐Ÿ“ INSERT Data into MySQL

$name = "Alice";
$sql = "INSERT INTO users (name) VALUES ('$name')";

if ($conn->query($sql) === TRUE) {
    echo "โœ… New record created successfully";
} else {
    echo "โŒ Error: " . $conn->error;
}

โš ๏ธ Donโ€™t use plain strings with user input โ€” use prepared statements for security


๐Ÿ›ก๏ธ Prevent SQL Injection with Prepared Statements

$stmt = $conn->prepare("INSERT INTO users (name) VALUES (?)");
$stmt->bind_param("s", $name);
$stmt->execute();

โœ… Use bind_param() to bind variables safely
โœ… "s" means string; use "i" for integer, etc.


โœ๏ธ UPDATE and DELETE Examples

โœ… UPDATE

$stmt = $conn->prepare("UPDATE users SET name = ? WHERE id = ?");
$stmt->bind_param("si", $new_name, $id);
$stmt->execute();

โœ… DELETE

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

๐Ÿ“Œ Always confirm deletion actions on the frontend to prevent accidental data loss


๐Ÿ“Š Common mysqli Functions

FunctionPurpose
mysqli_connect()Establish connection (procedural)
$conn->query()Run SQL queries
$conn->prepare()Prepare SQL statements securely
$stmt->bind_param()Bind parameters to a prepared statement
$stmt->execute()Execute the statement
$stmt->fetch()Fetch results (with bind_result)
$conn->close()Close connection

๐Ÿง  Best Practices for PHP + MySQL

  • โœ… Use prepared statements for all user input
  • โœ… Use utf8mb4 charset for full Unicode support (emojis, special characters)
  • โœ… Keep DB credentials in separate configuration files
  • โœ… Avoid displaying raw errors in production (log them instead)
  • โœ… Use PDO for portability if you plan to support other DBs in the future

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

PHP and MySQL are tightly integrated, allowing developers to quickly build powerful, data-driven applications. With mysqli, you can securely query and manage your database directly from PHP scripts.

๐Ÿ” Key Takeaways:

  • Use mysqli or PDO for database interaction
  • Always protect input using prepared statements
  • Perform common SQL operations (SELECT, INSERT, UPDATE, DELETE) safely
  • Secure credentials and database access in production

โš™๏ธ Real-World Use Cases:
Login systems, content management, blog platforms, e-commerce sites, data dashboards


โ“ Frequently Asked Questions (FAQs)

โ“ What is the difference between mysqli and PDO?
โœ… mysqli is MySQL-specific. PDO supports multiple databases and provides a uniform interface.

โ“ Should I use procedural or OOP with mysqli?
โœ… OOP is cleaner and more scalable for modern applications.

โ“ Is mysqli_real_escape_string() safe enough?
โš ๏ธ It helps, but prepared statements are the recommended method for securing input.

โ“ Can I fetch results as arrays?
โœ… Yes, use $result->fetch_assoc() or $result->fetch_array().

โ“ How do I close a MySQL connection in PHP?
โœ… Use $conn->close(); when you’re done querying the database.


Share Now :

Leave a Reply

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

Share

๐Ÿ—„๏ธ PHP MySQL

Or Copy Link

CONTENTS
Scroll to Top