What are common pitfalls when trying to store database query results in a PHP function?
One common pitfall when trying to store database query results in a PHP function is not properly handling the connection to the database within the function. To solve this, you should establish the database connection within the function itself and close it after fetching the results. Another pitfall is not properly handling errors that may occur during the query execution.
function getQueryResults() {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM table";
$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"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
}
// Call the function to get query results
getQueryResults();
Related Questions
- Is ODBC a suitable solution for connecting PHP to DB2 databases, or are there other alternatives?
- What are the advantages of using predefined arrays or formats for storing holiday dates in PHP scripts, and how can this approach simplify holiday calculations?
- Is it recommended to use PDO and prepared statements for interacting with MS-SQL Server in PHP to prevent SQL injection?