What best practices should be followed when handling MySQL queries within PHP functions to avoid unnecessary strain on the database?
To avoid unnecessary strain on the database when handling MySQL queries within PHP functions, it is important to properly sanitize input data to prevent SQL injection attacks, use prepared statements to improve query performance and security, limit the number of queries being executed, and properly close database connections after use.
// Example of using prepared statements to handle MySQL queries within PHP functions
// Establish database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Prepare a statement
$stmt = $mysqli->prepare("SELECT id, name FROM users WHERE id = ?");
// Bind parameters
$stmt->bind_param("i", $user_id);
// Set parameters and execute
$user_id = 1;
$stmt->execute();
// Bind result variables
$stmt->bind_result($id, $name);
// Fetch results
while ($stmt->fetch()) {
echo "User ID: $id, Name: $name <br>";
}
// Close statement
$stmt->close();
// Close connection
$mysqli->close();