我正在尝试根据数据库中是否已存在帖子来插入/更新 MySql 数据库(我正在使用唯一的 user_id 进行检查)。以下作品:
$select_query = "SELECT * ";
$select_query .= "FROM test ";
$select_query .= "WHERE user_id = '$user_id'";
$check_user_id = mysqli_query($connection, $select_query);
$query = "INSERT INTO test (";
$query .= " user_id, name, message";
$query .= ") VALUES (";
$query .= " '{$user_id}', '{$name}', '{$message}'";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result) {
echo "Success!";
} else {
die("Database query failed. " . mysqli_error($connection));
}
但是,当我将以下代码与 if/else 语句一起使用时,它不再起作用,尽管控制台报告“成功!” (意味着 $result 有一个值)。任何帮助将不胜感激。谢谢。
$select_query = "SELECT * ";
$select_query .= "FROM test ";
$select_query .= "WHERE user_id = '$user_id'";
$check_user_id = mysqli_query($connection, $select_query);
if (!$check_user_id) {
$query = "INSERT INTO test (";
$query .= " user_id, name, message";
$query .= ") VALUES (";
$query .= " '{$user_id}', '{$name}', '{$message}'";
$query .= ")";
} else {
$query = "UPDATE test SET ";
$query .= "name = '{$name}', ";
$query .= "message = '{$message}' ";
$query .= "WHERE user_id = '{$user_id}'";
}
$result = mysqli_query($connection, $query);
if ($result) {
echo "Success!";
} else {
die("Database query failed. " . mysqli_error($connection));
}