How can the PHP code be improved to only retrieve the desired columns from the database?
To only retrieve the desired columns from the database in PHP, you can modify the SQL query to specify the columns you want to retrieve. This can help improve performance by reducing the amount of data fetched from the database and processed by the application. Simply list the column names you want to retrieve in the SELECT statement of your SQL query.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to retrieve only desired columns
$sql = "SELECT column1, column2, column3 FROM your_table";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. " - Column3: " . $row["column3"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>