What are some best practices for sanitizing user input in PHP before storing it in a MySQL database?
When storing user input in a MySQL database, it is important to sanitize the input to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries in PHP. This method separates the SQL query from the user input, making it impossible for malicious input to interfere with the query execution.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Sanitize user input
$userInput = $_POST['user_input'];
$stmt = $pdo->prepare("INSERT INTO table_name (column_name) VALUES (:user_input)");
$stmt->bindParam(':user_input', $userInput);
$stmt->execute();
Related Questions
- How can DNS settings, such as AAAA records, be utilized in conjunction with PHP for IP version-based redirection on different servers?
- What are some best practices for filtering and displaying specific file types (e.g., images) in a PHP script?
- Is it best practice to use static methods in PHP database classes, considering the limitations it may pose for multiple database connections?