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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化