What are the key differences in syntax between writing to a text file and executing SQL queries in PHP?
When writing to a text file in PHP, you would typically use functions like fopen, fwrite, and fclose to open the file, write data to it, and then close it. On the other hand, when executing SQL queries in PHP, you would use functions like mysqli_query or PDO to connect to a database, send queries to it, and retrieve results. The key difference lies in the syntax and the purpose of each operation - writing to a text file involves file handling functions, while executing SQL queries involves database interaction functions.
// Writing to a text file
$file = fopen("example.txt", "w");
fwrite($file, "Hello, World!");
fclose($file);
// Executing SQL query
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Email: " . $row["email"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();