PHP mySQLi update table

2019-04-13 16:20发布

问题:

Currently, I am using PHP to get some from the backend and insert into the database using mysqli. Below is the code used:

$conn = new mysqli('localhost', 'username', 'pwd', 'db');

// check connection
if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}

$sql = "INSERT INTO `birthday` (`birthday`) VALUES ('$birthday')";

// Performs the $sql query and get the auto ID
if ($conn->query($sql) === TRUE) {
  echo 'The auto ID is: '. $conn->insert_id;
}
else {
  echo 'Error: '. $conn->error;
}

Now if I am going to fetch the information again, how to I update this value? Currently, it will create another row and insert the value again.

Thanks In Advance

回答1:

What I typically do is something like this.

Also, you need to make sure you have a field or something that is unique to this record. Basically, it will always INSERT the way it's written, since we're just checking one value (birthday)

Here's an example

$conn = new mysqli('localhost', 'username', 'pwd', 'db');

    // check connection
    if (mysqli_connect_errno()) {
      exit('Connect failed: '. mysqli_connect_error());
    }          
            // check to see if the value you are entering is already there      
            $result = $conn->query("SELECT * FROM birthday WHERE name='Joe'");
            if ($result->num_rows > 0){ 
                // this person already has a b-day saved, update it
                $conn->query("UPDATE birthday SET birthday = '$birthday' WHERE name = 'Joe'");
            }else{
                // this person is not in the DB, create a new ecord
                $conn->query("INSERT INTO `birthday` (`birthday`,`name`) VALUES ('$birthday','Joe')");
            }    


回答2:

This should work. But will say I find it confusing that you have the db name, table name and variable name set as “birthday”

$sql = "INSERT INTO `birthday` (`birthday`) VALUES ('$birthday') ON DUPLICATE KEY UPDATE birthday = $birthday;";


标签: php mysqli