How can PHP be used to store and manage user voting data in a database or text file for a survey on a website?
To store and manage user voting data in a database or text file for a survey on a website, you can use PHP to handle the data input from users, validate the input, and then store it in a database or text file. You can create a form for users to submit their votes, process the form submission using PHP, and then insert the data into a database table or write it to a text file for storage and later analysis.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "survey_db";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$vote = $_POST['vote'];
// Insert the vote into the database
$sql = "INSERT INTO survey_results (vote) VALUES ('$vote')";
if ($conn->query($sql) === TRUE) {
echo "Vote recorded successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// Close the database connection
$conn->close();
?>
Keywords
Related Questions
- How can preg_match_all be used effectively in PHP to extract specific data from a string using regex?
- What is the difference between = and == in PHP and how does it relate to assigning values from an array?
- How can the use of htmlspecialchars() function enhance security when outputting JSON data in an HTML table using PHP?