The process of updating data in a MySQL database using PHP involves the following aspects:
Here's a step-by-step example:
$host = "localhost";
$username = "username";
$password = "password";
$database = "my_database";
// Create connection
$conn = new mysqli($host, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Assuming you have a table named `users` and you want to update the `email` of a user with `id=1`:
$new_email = "newemail@example.com";
$user_id = 1;
$sql = "UPDATE users SET email='$new_email' WHERE id=$user_id";
NOTE: Directly injecting variables into your SQL like this can expose your code to SQL injection. Always use prepared statements (will show later).
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
Errors can be handled using the above condition where we checked if the query execution was successful.
$conn->close();
To prevent SQL injection, it's recommended to use prepared statements:
$stmt = $conn->prepare("UPDATE users SET email=? WHERE id=?");
$stmt->bind_param("si", $new_email, $user_id);
if ($stmt->execute()) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $stmt->error;
}
$stmt->close();
Here, the "si" in `bind_param` means we're binding a string and an integer, respectively. Remember to always sanitize and validate data inputs when dealing with databases to ensure security and data integrity.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here