What are the best practices for writing SQL queries in PHP to prevent SQL injection attacks, and why is using SELECT * discouraged in certain scenarios?

To prevent SQL injection attacks in PHP, it is recommended to use prepared statements with parameterized queries. This helps sanitize user input and prevents malicious SQL code from being injected into the query. Additionally, avoiding the use of "SELECT *" in queries is discouraged in certain scenarios because it can retrieve unnecessary columns, leading to potential performance issues and security risks if sensitive data is inadvertently exposed.

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

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT column1, column2 FROM mytable WHERE id = :id');

// Bind the parameter value
$stmt->bindParam(':id', $id);

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

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