What are the best practices for retrieving and storing values from a database in PHP?

When retrieving and storing values from a database in PHP, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to sanitize and validate user input before storing it in the database to ensure data integrity. Finally, always close the database connection after performing the necessary operations to free up resources.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Retrieve data from the database using prepared statements
$stmt = $conn->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->bind_param("i", $id);

$id = 1;
$stmt->execute();
$stmt->bind_result($id, $name);

while ($stmt->fetch()) {
    echo "ID: " . $id . " Name: " . $name . "<br>";
}

$stmt->close();

// Store data in the database using prepared statements
$stmt = $conn->prepare("INSERT INTO users (name) VALUES (?)");
$stmt->bind_param("s", $name);

$name = "John Doe";
$stmt->execute();

$stmt->close();

// Close the database connection
$conn->close();