To update data into a MySQL database using a PHP form, you can follow these steps:
Connect to the database:
You need to establish a connection between your PHP script and the MySQL database. This can be done using the mysqli_connect () function, which takes four parameters: the database server host, username, password, and database name.
<?php
$servername = "localhost";
$username = "yourusername";
$password = "yourpassword";
$dbname = "yourdatabasename";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Create a form:
You need to create a form that will allow users to enter the data that they want to update in the database. You can use HTML to create the form.
<form method="post" action="update.php">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Update">
</form>
Handle the form submission:
You need to handle the form submission using PHP. When the user submits the form, the data is sent to a PHP script that will update the database.
<?php
// Check if the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form data
$name = $_POST["name"];
$email = $_POST["email"];
// Update the database
$sql = "UPDATE users SET email='$email' WHERE name='$name'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
}
In the above code, we first check if the form was submitted using the $ _SERVER [" REQUEST_METHOD "] variable. We then get the form data using the $_POST variable. Finally, we update the database using an SQL query that updates the email field in the users table for the specified name.
Close the connection:
Once you have updated the database, you should close the connection to the database using the mysqli_close() function.
mysqli_close($conn);
That's it! With these steps, you can update data into a MySQL database using a PHP form.