PHP mySQLi更新表
目前,我正在使用PHP从后端获取一些,并使用mysqli插入数据库。以下是使用的代码:PHP mySQLi更新表,php,mysqli,Php,Mysqli,目前,我正在使用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`
$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;
}
现在,如果要再次获取信息,如何更新此值?当前,它将创建另一行并再次插入值
提前感谢我通常会这样做 此外,您需要确保您有一个字段或该记录特有的内容。基本上,它总是以写入的方式插入,因为我们只是检查一个值(生日) 这里有一个例子
$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')");
}
为什么在重复密钥更新时要进行三次查询?Jake-很公平,他仍然需要一个唯一的密钥,这就是我想要展示的。在您发布的示例中,它基本上要检查b-day是否存在,如果不创建b-day,如果创建b-day,则将其更新为原来的值。而且,只有两个查询:)一个要检查,另一个作为操作。啊,好的。“那我更好地理解你的逻辑。”你的解决方案有效。但是有没有不使用WHERE name='Joe'进行更新的方法?因为“我的表”只有一列名为“生日”来存储该值。@aandroidtest如果只有一个名为“生日”的字段存储生日值(如1/1/2000),那么您确实无法“更新”该记录,因为它与您要更新的值相匹配。如果您不想让它继续使用相同的数据插入和增长表,您可以使用Jakes的建议,或者使用类似的方法使生日字段唯一。更改表生日添加唯一(生日);