What is the purpose of the HTML form in the context of PHP and MySQL database interaction?
The purpose of the HTML form in the context of PHP and MySQL database interaction is to collect user input data that can be submitted to a PHP script for processing and storing in a MySQL database. The form allows users to input data such as text, numbers, checkboxes, radio buttons, etc., which can then be sent to a PHP script for handling database operations like inserting, updating, or deleting records.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Connect to MySQL database
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Collect form data
$name = $_POST['name'];
$email = $_POST['email'];
// Insert data into MySQL database
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
Keywords
Related Questions
- What are the potential pitfalls of indiscriminate filtering, sanitizing, or quoting of user inputs in PHP, and how can developers avoid them?
- What are the best practices for handling JSON data in PHP and extracting specific values from it?
- In what ways can the PHP community support beginners who are facing challenges in learning and implementing PHP code?