What are some best practices for handling user input in PHP and storing it in SQL databases?
When handling user input in PHP and storing it in SQL databases, 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. This helps to separate the SQL query from the user input, making it safer to execute.
// Establish a connection 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
$user_input = mysqli_real_escape_string($conn, $_POST['user_input']);
// Prepare and bind the SQL statement
$stmt = $conn->prepare("INSERT INTO table_name (column_name) VALUES (?)");
$stmt->bind_param("s", $user_input);
// Execute the statement
$stmt->execute();
// Close the connection
$stmt->close();
$conn->close();
Related Questions
- What best practices should be followed when validating form input before sending emails with PHPMailer?
- Are there any built-in PHP functions or libraries that can help filter and sanitize HTML content before storing it in a database?
- What is the best practice for redirecting form data to a different page in PHP?