如果语句不能避免插入查询

时间:2015-04-19 23:15:39

标签: php mysql http

我正在尝试创建一个简单的api,它假设从移动应用程序向不同的新闻添加视图。当我使用以下网址直接在浏览器中测试时:

http://url/addview.php?type=ios&identifier=35605C24-8EA6-4342-Bdfd-245432&newsid=147

如果news_id,type和identifier已经存在,它可以正常工作并添加重复项。但是,当我在我的ios应用程序中通过异步http请求运行此URL时,它似乎总是添加一条新记录,即使它已经存在于d

$con = new mysqli('host','user','pass','db');
$type = $_GET['type'];
$identifier = $_GET['identifier'];
$news = $_GET['newsid'];

$check = $con->prepare("SELECT * FROM views WHERE views.news_id =? AND views.type =? AND views.identifier=?");
$check->bind_param("iss", $news, $type, $identifier);
$check->execute();
$check->store_result();
$check->fetch(); 

if ($check->num_rows == 0) {
    $con->next_result();
    $check->close();
    $add_view = $con->prepare("INSERT INTO views (views.news_id, views.type, views.identifier, views.reg_date) VALUES (?, ?, ?, CURRENT_TIMESTAMP())");
    $add_view->bind_param("iss", $news, $type, $identifier);
    $add_view->execute();
    $add_view->close();
    $con->next_result();


}

$con->close();

1 个答案:

答案 0 :(得分:1)

如果您不想要重复,请添加适当的唯一索引。根据你的逻辑,我认为这将是:

create unique index idx_views_3 on views(news_id, type, identifier);

然后,插入为:

INSERT INTO views (news_id, type, identifier, reg_date)
    VALUES (?, ?, ?, CURRENT_TIMESTAMP())
    on duplicate key update news_id = values(news_id);