How can a user input text be securely stored in a database using PHP?
When storing user input text in a database using PHP, it is important to prevent SQL injection attacks by sanitizing the input data. One way to securely store user input text is by using prepared statements with parameterized queries. This helps to separate the SQL query from the user input, reducing the risk of SQL injection vulnerabilities.
// Establish a database connection
$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);
}
// Prepare a SQL statement with a parameterized query
$stmt = $conn->prepare("INSERT INTO table_name (user_input) VALUES (?)");
$stmt->bind_param("s", $user_input);
// Set the user input and execute the statement
$user_input = $_POST['user_input'];
$stmt->execute();
// Close the statement and the database connection
$stmt->close();
$conn->close();
Related Questions
- How can variable values affect the success of a mysql_query() function in PHP?
- How can the issue of data not being transmitted on the first click of the "OK" button be resolved in the PHP code?
- What are the potential security risks associated with copying and pasting code from external sources without full understanding in PHP development?