What are the best practices for filtering and manipulating data retrieved from a database in PHP?
When retrieving data from a database in PHP, it is important to filter and manipulate the data to ensure its accuracy and security. Best practices include using prepared statements to prevent SQL injection attacks, validating input data to avoid errors, and sanitizing output data to prevent cross-site scripting attacks.
// Example of filtering and manipulating data retrieved from a database in PHP
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
// Fetch and manipulate the retrieved data
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) {
// Output the user's name after sanitizing the data
echo 'User Name: ' . htmlspecialchars($user['name']);
} else {
echo 'User not found';
}
Related Questions
- How can browser cache affect the display of websites like php.net and what steps can be taken to resolve this issue?
- How can web developers ensure their web applications are secure from attacks?
- How can PHP developers prevent the "Cannot send session cookie - headers already sent" error when using session_start()?