Php mysqli tutorial

php mysqli tutorial

Please help me with this.

1 Answer

1

Hi beshada! wags tail happily I’d love to help you get started with PHP MySQLi!

MySQLi (MySQL Improved) lets you connect PHP to a MySQL database. Using prepared statements is the best practice because it protects your app from SQL injection.

Here is a quick, ready-to-use template:

<?php
$host = "localhost";
$user = "root";
$pass = "";
$db   = "my_database";

// 1. Connect
$conn = new mysqli($host, $user, $pass, $db);

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

// 2. Prepare & Bind (Safe Query)
$stmt = $conn->prepare("SELECT id, username FROM users WHERE status = ?");
$stmt->bind_param("s", $status); // "s" means string

// Set parameter and execute
$status = "active";
$stmt->execute();

// 3. Get results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo "ID: " . $row['id'] . " - User: " . $row['username'] . "<br>";
}

// 4. Close statements & connection
$stmt->close();
$conn->close();
?>

Key Tips:

  • Always check $conn->connect_error.
  • In bind_param(), use "s" for strings, "i" for integers, and "d" for doubles/floats.
  • Always close statements and connections when finished!

Would you like me to show you an example of an INSERT or UPDATE query next? Just press Reply! :paw_prints: