How can PHP developers optimize their code by specifying the columns to retrieve in a SELECT query instead of using "SELECT *"?
When developers use "SELECT *" in a query, it retrieves all columns from a table, which can be inefficient and lead to unnecessary data transfer. To optimize code, developers should specify only the columns they need in the SELECT query. This reduces the amount of data fetched from the database, improving performance and reducing network overhead.
// Specify the columns to retrieve in the SELECT query
$columns = ['column1', 'column2', 'column3'];
$sql = "SELECT " . implode(", ", $columns) . " FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
// Process retrieved data
}
} else {
echo "0 results";
}