What are the recommended methods for handling user inputs and form submissions in PHP to prevent issues like non-object errors when fetching data from a database?

When handling user inputs and form submissions in PHP, it is crucial to validate and sanitize the data before using it in database queries to prevent issues like non-object errors. One way to avoid these errors is by using prepared statements with parameterized queries to securely fetch data from the database without the risk of SQL injection attacks.

// Example of using prepared statements to handle user inputs and prevent non-object errors

// Assuming $db is your database connection

// Validate and sanitize user input
$user_id = isset($_POST['user_id']) ? $_POST['user_id'] : '';

// Prepare a SQL statement with a parameterized query
$stmt = $db->prepare("SELECT * FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();

// Fetch the results
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Check if the user exists
if($user) {
    // User found, do something with the data
    echo "User found: " . $user['username'];
} else {
    // User not found
    echo "User not found";
}