How can the PHP script be modified to allow users to add new records directly on the webpage?
To allow users to add new records directly on the webpage, you can create a form on the webpage where users can input the necessary data for the new record. Then, you can modify the PHP script to handle the form submission, validate the input, and insert the new record into the database.
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve form data
$name = $_POST['name'];
$email = $_POST['email'];
// Prepare and execute the SQL query to insert new record
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record added successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close database connection
$conn->close();
}
?>
<!-- HTML form for users to input new record data -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="email">Email:</label>
<input type="email" name="email" id="email">
<input type="submit" value="Add Record">
</form>
Related Questions
- What security considerations should be taken into account when passing user input through POST requests in PHP?
- How can PHP be optimized to ensure that only the necessary content is displayed without duplication or errors?
- How can the file permissions (CHMOD) of a directory created with PHP be changed to a specific value?