How can PHP be used to write data to a database upon button click and handle redirection based on the outcome?
To write data to a database upon button click and handle redirection based on the outcome, you can use PHP to handle the form submission, insert the data into the database, and then redirect the user to a different page based on the success or failure of the database operation.
<?php
// Check if the form is submitted
if(isset($_POST['submit'])){
// Connect to the database
$conn = new mysqli('localhost', 'username', 'password', 'database');
// Check the connection
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
// Get the form data
$data = $_POST['data'];
// Insert data into the database
$sql = "INSERT INTO table_name (column_name) VALUES ('$data')";
if($conn->query($sql) === TRUE){
// Redirect to success page
header("Location: success.php");
exit();
} else {
// Redirect to error page
header("Location: error.php");
exit();
}
// Close the connection
$conn->close();
}
?>
Keywords
Related Questions
- How can one effectively troubleshoot issues with mysqli_query in PHP?
- What are the differences between reading files locally on the web server with PHP and reading files locally on the client's computer?
- What are the benefits and drawbacks of using server-side code like PHP versus client-side solutions like CSS for text truncation and display issues?