What steps can be taken to test and troubleshoot a query in PHP to avoid errors like the one mentioned in the thread?

Issue: To avoid errors in PHP queries, it is important to properly sanitize user input to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries. Example PHP code snippet with prepared statements:

// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

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

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

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

// Set the parameter value and execute the query
$username = "john_doe";
$stmt->execute();

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

// Fetch and print the results
while ($row = $result->fetch_assoc()) {
    echo "Username: " . $row["username"] . "<br>";
}

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