What best practices should be followed when structuring and organizing SQL queries within PHP code for optimal performance?

When structuring and organizing SQL queries within PHP code for optimal performance, it is important to use prepared statements to prevent SQL injection attacks and improve query execution efficiency. Additionally, it is recommended to avoid dynamically generating SQL queries based on user input and instead use parameterized queries for better security and performance.

// Example of using prepared statements in PHP to execute SQL queries
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL query using a placeholder for the parameter
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

// Bind the parameter value to the placeholder
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);

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

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

// Loop through the results
foreach ($results as $row) {
    // Process the data
}