How can PHP be used to store selected items from a form into a MySQL database?
To store selected items from a form into a MySQL database using PHP, you can first establish a connection to the database, retrieve the form data using $_POST or $_GET, sanitize the input to prevent SQL injection, and then insert the data into the database using SQL queries.
<?php
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve form data
$item1 = $_POST['item1'];
$item2 = $_POST['item2'];
// Sanitize input
$item1 = mysqli_real_escape_string($conn, $item1);
$item2 = mysqli_real_escape_string($conn, $item2);
// Insert data into the database
$sql = "INSERT INTO table_name (item1, item2) VALUES ('$item1', '$item2')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Keywords
Related Questions
- What best practices should be followed when handling file paths and permissions in PHP scripts to avoid potential errors?
- Are there any potential security risks when using file_get_contents to display external text files in PHP?
- How does the use of mysql_real_escape_string impact the security and functionality of PHP scripts?