How can PHP be used to insert form data into a database with specific field names and values?
To insert form data into a database with specific field names and values using PHP, you can use SQL queries along with PHP variables to dynamically insert the form data. You can use prepared statements to prevent SQL injection attacks and ensure data security.
<?php
// 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);
}
// Get form data
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
$field3 = $_POST['field3'];
// Prepare SQL query
$stmt = $conn->prepare("INSERT INTO table_name (field1, field2, field3) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $field1, $field2, $field3);
// Execute the query
$stmt->execute();
// Close the statement and connection
$stmt->close();
$conn->close();
?>
            
        Keywords
Related Questions
- How can a PHP query be used to retrieve only new entries from the last hour?
- In PHP, what are some considerations for structuring the order of content output, such as including server-side tasks before sending content to the client, to optimize performance and prevent issues with headers?
- What are the potential performance implications of using separate functions versus if() statements in PHP code?