首页 > 解决方案 > PHP在数据库中验证是否存在重复

问题描述

我有这个功能:

public function addToFavoriteList($eventId, $userId)
{
    $sql = "INSERT INTO favorites (eventi_id, user_id) VALUES ($eventId, $userId)";
    $resultSet = $this->db->execute($sql);
    if (!$resultSet) {
        return array('error' => 'event exsist in favorites');
    }
    return array('error' => '');
}

我想检查事件是否已经存在于数据库中,以便我可以为用户显示错误消息。我写了类似的东西,但它不起作用。

if (isset($_POST['addToFavourite'])) {
    $eventId = htmlspecialchars(trim($_POST['id']));
    $addToFavoriteOutcome = $eventMgr->addToFavoriteList($eventId, $userId);

    if (isset($addToFavoriteOutcome)) {
        $errorMessage = $addToFavoriteOutcome['error'];
    }
}

标签: phphtmlsqldatabase

解决方案


尝试改变这个:

if (isset($addToFavoriteOutcome)) {
    $errorMessage = $addToFavoriteOutcome['error'];
}

对此

if ($addToFavoriteOutcome) {
    $errorMessage = $addToFavoriteOutcome['error'];
}

推荐阅读