What are some best practices for extracting specific columns from a table in PHP?

When extracting specific columns from a table in PHP, one common approach is to use a SQL query to select only the desired columns. This can be done by specifying the column names in the SELECT statement. Another approach is to fetch all columns from the table and then extract the specific columns needed in PHP code.

// 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 select specific columns from a table
$sql = "SELECT column1, column2 FROM table_name";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Column 1: " . $row["column1"]. " - Column 2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();