What is the correct way to send a query to the database in PHP?

When sending a query to a database in PHP, it is important to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL code from user input, making it safe to execute queries. To send a query to the database in PHP using prepared statements, you can use the PDO (PHP Data Objects) extension.

// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind parameters to the prepared statement
$stmt->bindParam(':username', $username);

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

// Fetch the results of the query
$results = $stmt->fetchAll();