What are best practices for storing and retrieving user-entered data in a database using PHP?
When storing and retrieving user-entered data in a database using PHP, it is important to sanitize inputs to prevent SQL injection attacks. This can be done using prepared statements with parameterized queries. Additionally, it is recommended to validate user inputs to ensure data integrity.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sanitize user input
$userInput = mysqli_real_escape_string($conn, $_POST['user_input']);
// Prepare and execute a parameterized query
$stmt = $conn->prepare("INSERT INTO table_name (column_name) VALUES (?)");
$stmt->bind_param("s", $userInput);
$stmt->execute();
// Retrieve user-entered data
$sql = "SELECT * FROM table_name WHERE column_name = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $userInput);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process retrieved data
}
// Close connection
$conn->close();
Related Questions
- What are the best practices for storing file paths in a database and retrieving them in PHP without exposing sensitive information?
- How can the error "Warning: Cannot modify header information - headers already sent" be resolved when trying to set a cookie in PHP?
- Is using a database a better solution than writing content directly to a file in PHP? Why or why not?