doulu1914 2011-09-27 02: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-27 03: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条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题