What are some common pitfalls to avoid when handling MySQL queries within PHP classes?
One common pitfall to avoid when handling MySQL queries within PHP classes is not properly sanitizing user input, which can lead to SQL injection attacks. To prevent this, always use prepared statements with parameterized queries to securely pass user input to the database.
// Example of using prepared statements with parameterized queries to avoid SQL injection
// Assume $mysqli is a mysqli object connected to the database
class User {
private $mysqli;
public function __construct($mysqli) {
$this->mysqli = $mysqli;
}
public function getUserById($userId) {
$stmt = $this->mysqli->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();
return $user;
}
}
$user = new User($mysqli);
$userData = $user->getUserById($_GET['user_id']);
Keywords
Related Questions
- Are there any security considerations to keep in mind when updating text files in PHP?
- How can PHP scripts be improved to fetch and display user names instead of just IDs from a related table in a database?
- What are the considerations when balancing the visual presentation and functionality of a search feature in PHP when using text files?