doulu1914 2011-09-26 18:32
浏览 80
已采纳

如何在不使用INSERT IGNORE的情况下检查mysql中是否存在行?

I currently use this query to update listings in my database from my php app:

$query = "INSERT INTO listings (title, description) VALUES ('$title','$description')";

This listings table has a 'postid' column as it's primary key that auto increments.

I don't want to do an INSERT IGNORE and have it check postid. Instead, I'd like to keep the table structure the same and check to see if $title exists.. and not insert if it does.

Will php/mysql allow me to somehow run a:

If ($title does not exist) {
$query = "INSERT INTO listings (title, description) VALUES ('$title','$description')";
}  

If so, how would I write that?

Thanks for any suggestions.

  • 写回答

2条回答 默认 最新

  • drydaenth257216154 2011-09-26 19:44
    关注

    You can do the dollowing:

    Query your database to see if there is already any list with the given title and if the count query returns 0, execute your insert statement:

    $result = mysql_query('SELECT count(*) as total from listings where title="$title"');
    
    $result = mysql_fetch_array($result);    
    
    if($result['total'] == 0){
        $query = mysql_query("INSERT INTO listings (title, description) VALUES ('$title','$description')");
    }
    

    But I strongly suggest you to do not manipulate your database this way. Better to use an ORM or a database class instead of putting your SQL statements all over the place.

    Good luck.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部