Skip to content
PHP Logo

What are the potential security risks of inserting user input directly into a database query in PHP?

Inserting user input directly into a database query in PHP can lead to SQL injection attacks, where malicious users can manipulate the query to access, modify, or delete data from the database. To prevent this, you should always use prepared statements with parameterized queries to sanitize and validate user input before executing the query.

php
// Example of using prepared statements to insert user input into a database query safely

// Assuming $conn is the database connection

// User input
$userInput = $_POST['user_input'];

// Prepare the SQL statement
$stmt = $conn->prepare("INSERT INTO table_name (column_name) VALUES (?)");
$stmt->bind_param("s", $userInput);

// Execute the statement
$stmt->execute();

// Close the statement and connection
$stmt->close();
$conn->close();