PHP mySQLi 更新表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14554673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:31:10  来源:igfitidea点击:

PHP mySQLi update table

phpmysqli

提问by aandroidtest

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

目前,我正在使用 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;
}

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

提前致谢

回答by OrganizedChaos

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