开发者

How to check for existence of a row in mysql without using INSERT IGNORE?

开发者 https://www.devze.com 2023-04-07 14:36 出处:网络
I currently use this query to update listings in my database from my php app: $query = "INSERT INTO listings (title, description) VALUES (\'$title\'开发者_Python百科,\'$description\')";

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

$query = "INSERT INTO listings (title, description) VALUES ('$title'开发者_Python百科,'$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?


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.


Try this:

INSERT INTO listings (title, description) VALUES ('$title','$description')
FROM dual WHERE not exists (SELECT title FROM listings WHERE title = '$title');

Or you can do like this:

$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');");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消