Tags
Asked 2 years ago
17 Jun 2021
Views 143
Hilma

Hilma posted

Change an Insert statement to an update statement in PHP/MySQL

Change an Insert statement to an update statement in PHP/MySQL
ruby-rails

ruby-rails
answered Apr 28 '23 00:00

To change an INSERT statement to an UPDATE statement in PHP/MySQL, you need to modify the SQL query to update the existing record instead of inserting a new one. Here's an example code snippet that shows how to update a record in a table named "users" with a given ID:


<?php
// Connect to the database
$conn = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Check if the record exists
$id = 1; // Replace with the ID of the record you want to update
$sql = "SELECT * FROM users WHERE id=$id";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // Update the existing record
    $sql = "UPDATE users SET name='John Doe', email='john.doe@example.com' WHERE id=$id";

    if (mysqli_query($conn, $sql)) {
        echo "Record updated successfully";
    } else {
        echo "Error updating record: " . mysqli_error($conn);
    }
} else {
    // Insert a new record if it doesn't exist
    $sql = "INSERT INTO users (name, email) VALUES ('John Doe', 'john.doe@example.com')";

    if (mysqli_query($conn, $sql)) {
        echo "New record created successfully";
    } else {
        echo "Error creating record: " . mysqli_error($conn);
    }
}

// Close the database connection
mysqli_close($conn);
?>

In the above code, we first check if the record with the given ID exists in the table using a SELECT statement. If the record exists, we update it using an UPDATE statement. If the record doesn't exist, we insert a new record using an INSERT statement.

Note that you should replace "username", "password", "database", " users ", "name", " email ", and " id" with your own values. Also, don't forget to close the database connection using mysqli_close () after you're done with it.
Post Answer