In what scenarios would it be more advantageous to manually write SQL queries instead of using a query-building function in PHP?
There are scenarios where manually writing SQL queries in PHP can be more advantageous than using a query-building function. This includes situations where complex queries with multiple joins, subqueries, or specific optimizations are needed. Manually writing SQL queries provides more control over the query structure and can sometimes result in better performance.
<?php
// Manually writing a SQL query in PHP
$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);
}
// Manually write SQL query
$sql = "SELECT * FROM users WHERE age > 18";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"]. " - Age: " . $row["age"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>