PHP program that demonstrates how to connect to a MySQL database using prepared statements

<?php
// Database credentials
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "yourdatabase";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Prepare statement
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");

// Bind parameters
$id = 1;
$stmt->bind_param("i", $id);

// Execute statement
$stmt->execute();

// Get results
$result = $stmt->get_result();

// Loop through results
while ($row = $result->fetch_assoc()) {
    echo "id: " . $row["id"] . ", name: " . $row["name"] . ", email: " . $row["email"] . "<br>";
}

// Close statement and connection
$stmt->close();
$conn->close();
?>


In this example, we first create a new mysqli object to connect to the database using the provided credentials. We then prepare a statement to select all rows from a "users" table where the "id" column matches a parameter. We bind the parameter using the bind_param function and then execute the statement using the execute function.

We then get the results using the get_result function and loop through them using a while loop to output the data. Finally, we close the statement and connection using the close function.

Note that you should always sanitize your input data to prevent SQL injection attacks. In this example, we hard-coded the value of $id, but in a real-world scenario, you would likely receive this value from user input and need to validate it before using it in a query.

Sql:-


CREATE TABLE users (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  email VARCHAR(100) NOT NULL UNIQUE,
  PRIMARY KEY (id)
);

Post a Comment

0 Comments