我有一个名为 user_bio
的表。我为用户名 conor
手动输入了一行:
id: 1
age: 30
studying: Business
language: English
relationship_status: Single
username: conor
about_me: This is conor's bio.
个人简介对于用户来说是唯一的,显然,用户不能通过将个人简介插入数据库来手动设置他们的个人简介。考虑以下场景:
- 以
Conor
身份登录。由于 Conor 在数据库中已有一行,我只想运行UPDATE
查询来更新用户名等于 conor 的字段。 - 以
Alice
身份登录。因为 Alice 在数据库中没有对应于她的用户名的行。然后我想运行一个INSERT
查询。对于所有用户,所有用户都必须输入他们的详细信息,然后进行相应更新。
目前,当数据库中不存在任何行时,我正在努力向数据库中插入数据。
这是我目前的做法:
$about_me = htmlentities(trim(strip_tags(@$_POST['biotextarea'])));
$new_studying = htmlentities(trim(strip_tags(@$_POST['studying'])));
$new_lang = htmlentities(trim(strip_tags(@$_POST['lang'])));
$new_rel = htmlentities(strip_tags(@$_POST['rel']));
if(isset($_POST['update_data'])){
// need to check if the username has data already in the db, if so, then we update the data, otherwise we insert data.
$get_bio = mysqli_query($connect, "SELECT * FROM user_bio WHERE username ='$username'");
$row_returned = mysqli_num_rows($get_bio);
$get_row = mysqli_fetch_assoc ($get_bio);
$u_name = $get_row['username'];
if ($u_name == $username){
$update_details_query = mysqli_query ($connect, "UPDATE user_bio SET studying ='$new_studying', language ='$new_lang',
relationship_status = '$new_rel', about_me = '$about_me' WHERE username ='$username'");
echo " <div class='details_updated'>
<p> Details updated successfully! </p>
</div>";
} else {
$insert_query = mysqli_query ($connect, "INSERT INTO user_bio
VALUES ('', '$age','$new_studying','$new_lang','$new_rel', '$username', '$about_me'");
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
echo " <div class='details_updated'>
<p> Details added successfully! $row_returned </p>
</div>";
}
}
当以 Conor 身份登录时,UPDATE
查询工作正常。但是同样,当以 Alice
身份登录时,INSERT
不起作用。
最佳答案
MySQL 支持 INSERT ... ON DUPLICATE KEY UPDATE
类型的查询。所以你不需要做一些查询来检查你的 php 代码中的行是否存在,只需添加正确的索引并让你的数据库处理这个。
您可以阅读有关此类查询的信息 here
关于php - 如何测试数据库中是否存在行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36392449/