How can the user modify the code to store the data entered in the JavaScript prompts into PHP variables and then save them in a database?
To store data entered in JavaScript prompts into PHP variables and save them in a database, you can use AJAX to send the data from the client-side to the server-side PHP script. Within the PHP script, you can retrieve the data sent via POST or GET requests, assign them to PHP variables, and then insert them into a database using MySQLi or PDO.
<?php
// Check if data has been sent via POST request
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve data sent from JavaScript prompt
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
// Connect to your database
$conn = new mysqli('localhost', 'username', 'password', 'database');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert data into database
$sql = "INSERT INTO table_name (column1, column2) VALUES ('$data1', '$data2')";
if ($conn->query($sql) === TRUE) {
echo "Data inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close database connection
$conn->close();
}
?>
Related Questions
- What are the best practices for handling form submissions in PHP to ensure data integrity and prevent manipulation?
- How can LEFT JOIN be effectively used in PHP to retrieve and sort data from multiple related tables?
- Is it advisable to extend the PDOStatement class in PHP, or is there a more efficient way to handle error checking in PDO queries?