How can specific columns be selected in PHP queries instead of using SELECT *?
When writing SQL queries in PHP, instead of using "SELECT *", you can specify the exact columns you want to retrieve from the database table. This can improve query performance and reduce unnecessary data retrieval. To do this, simply list the column names separated by commas after the SELECT keyword in your SQL query.
<?php
// Connect to 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);
}
// Select specific columns from a table
$sql = "SELECT column1, column2, column3 FROM table_name";
$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";
}
// Close connection
$conn->close();
?>