Are there best practices for handling system commands and escaping characters when executing SQL queries in PHP on a live server environment?

When executing SQL queries in PHP on a live server environment, it is crucial to handle system commands and escape characters properly to prevent SQL injection attacks. To do this, you should always use prepared statements with parameterized queries instead of directly inserting user input into SQL statements. This helps to sanitize the input and avoid any malicious code execution.

// Establish a database connection
$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 a SQL statement using a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set the username variable from user input
$username = $_POST['username'];

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

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

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

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