How can PHP be used to securely store and retrieve user data like addresses in a database?
To securely store and retrieve user data like addresses in a database using PHP, you can use prepared statements to prevent SQL injection attacks. Additionally, you can hash sensitive data like passwords before storing them in the database to enhance security. Make sure to validate and sanitize user input to prevent any malicious code from being executed.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare a SQL statement using prepared statements
$stmt = $conn->prepare("INSERT INTO users (address) VALUES (?)");
$stmt->bind_param("s", $address);
// Sanitize and validate user input
$address = filter_var($_POST['address'], FILTER_SANITIZE_STRING);
// Execute the statement
$stmt->execute();
// Retrieve user data securely
$user_id = 1; // Example user ID
$stmt = $conn->prepare("SELECT address FROM users WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
// Display the user's address
echo $row['address'];
// Close the connection
$stmt->close();
$conn->close();
?>
Keywords
Related Questions
- Are there any existing PHP functions or libraries that can handle word wrapping while ignoring HTML tags?
- How can developers ensure the synchronization of data and events between PHP-generated content and JavaScript-driven interactions to maintain a coherent and responsive user experience in a dynamic web application?
- How can PHP functions like file_get_contents and file_put_contents be utilized to retrieve and display external images on a website?