PHP的mysqli更新表(PHP mySQLi update table)

2019-08-08 11:39发布

目前,我使用PHP从后台得到一些使用的mysqli插入到数据库中。 下面是使用的代码:

$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;
}

现在,如果我要再次读取该信息,如何我更新此值? 目前,它会创建另一行,并再次插入值。

提前致谢

Answer 1:

我通常做的就是这样的事情。

另外,你需要确保你有一个字段或东西是独特的这条记录。 基本上,它总是插入它的编写方式,因为我们只是检查一个值(生日)

下面是一个例子

$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')");
            }    


Answer 2:

这应该工作。 但是会说我觉得这混乱的,你有数据库名,表名和变量名设置为“生日”

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


文章来源: PHP mySQLi update table
标签: php mysqli