What is the best practice for retrieving a single value from a MySQL database using PHP?

When retrieving a single value from a MySQL database using PHP, it is best practice to use prepared statements to prevent SQL injection attacks. Prepared statements also help improve performance by reducing the need for repeated query parsing. To retrieve a single value, you can execute a SELECT query with a LIMIT of 1 and fetch the result using a fetch method.

<?php
// Establish a connection 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);
}

// Prepare and execute a SELECT query to retrieve a single value
$stmt = $conn->prepare("SELECT column_name FROM table_name WHERE condition = ?");
$stmt->bind_param("s", $condition);
$condition = "value";
$stmt->execute();

// Bind the result
$stmt->bind_result($result);

// Fetch the result
$stmt->fetch();

// Output the result
echo $result;

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