我目前使用此查询从我的php应用程序更新数据库中的列表:
$query = "INSERT INTO listings (title, description) VALUES ('$title','$description')";
此列表表有一个'postid'列,因为它是自动递增的主键。
我不想做INSERT IGNORE并检查postid。相反,我想保持表结构相同,并检查$ title是否存在..如果它存在则不插入。
php / mysql是否允许我以某种方式运行:
If ($title does not exist) {
$query = "INSERT INTO listings (title, description) VALUES ('$title','$description')";
}
如果是这样,我该怎么写呢?
感谢您的任何建议。
答案 0 :(得分:2)
你可以做下垂:
查询数据库以查看是否已存在具有给定标题的列表,如果计数查询返回0,则执行insert语句:
$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')");
}
但我强烈建议你不要这样操纵你的数据库。最好使用ORM或数据库类,而不是将SQL语句放在一起。
祝你好运。答案 1 :(得分:0)
试试这个:
INSERT INTO listings (title, description) VALUES ('$title','$description')
FROM dual WHERE not exists (SELECT title FROM listings WHERE title = '$title');
或者你可以这样做:
$result = mysql_query("UPDATE listings SET description = '$description' WHERE title ='$title';");
if (mysql_affected_rows() == 0) {
$result = mysql_query("INSERT INTO listings (title, description) VALUES ('$title','$description');");
}