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 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器