How can the syntax for passing variables in PHP be optimized to avoid issues with retrieving values from a table?

When passing variables in PHP to retrieve values from a table, it is important to sanitize and validate the input to prevent SQL injection attacks and ensure the data is safe to use. One way to optimize the syntax is to use prepared statements with placeholders instead of directly concatenating variables into the SQL query. This helps to separate the query logic from the data, making it easier to read and maintain.

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

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

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

// Prepare a statement with a placeholder
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set the variable value
$username = "john_doe";

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

// Fetch the result
$result = $stmt->get_result();

// Process the result
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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