In what scenarios would using SQL be a better option than handling file operations in PHP?

Using SQL would be a better option than handling file operations in PHP when dealing with structured data that needs to be queried, updated, and managed efficiently. SQL databases provide features like indexing, transactions, and relational capabilities that make handling data operations more streamlined and optimized compared to manually reading and writing files in PHP.

// Example of using SQL to query data from a database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();