What best practices should be followed when handling database queries and results in PHP functions?
When handling database queries and results in PHP functions, it is important to properly sanitize input data to prevent SQL injection attacks. Additionally, always use prepared statements to securely execute queries and avoid direct concatenation of user input into SQL queries.
// Example of a function that handles a database query using prepared statements
function getUserInfo($userId, $conn) {
$stmt = $conn->prepare("SELECT username, email FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
return $row;
} else {
return false;
}
}
Related Questions
- Are there specific considerations or limitations when using DBA/DBM functions for database operations in PHP?
- What are the potential drawbacks of using JavaScript to display message boxes in PHP?
- How can the use of Modulo in PHP be beneficial when dealing with repetitive tasks or calculations, as suggested in the forum thread?