PHP mySQLi更新表 [英] PHP mySQLi update table
本文介绍了PHP mySQLi更新表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当前,我正在使用PHP从后端获取一些内容,并使用mysqli将其插入数据库.下面是使用的代码:
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.
预先感谢
推荐答案
我通常要做的就是这样.
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)
这是一个例子
$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')");
}
这篇关于PHP mySQLi更新表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文