How can PHP be used to store form data in a database and display a success or error message in a pop-up window?
To store form data in a database using PHP, you can use MySQLi or PDO to establish a connection to the database, sanitize the input data to prevent SQL injection, and then insert the data into the database. To display a success or error message in a pop-up window, you can use JavaScript to show an alert based on the result of the database operation.
<?php
// Establish 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);
}
// Sanitize form data
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
// Insert data into database
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo '<script>alert("Data inserted successfully");</script>';
} else {
echo '<script>alert("Error: ' . $conn->error . '");</script>';
}
$conn->close();
?>
Keywords
Related Questions
- What is the function mysql_insert_id() in PHP and how can it be used to retrieve the ID of a newly inserted database entry?
- What are some basic SQL functions that are essential for programming a forum/board in PHP?
- How can PHP be optimized to accurately display whether a specific location is open or closed at a given time?