I want to check in my sql table if a row already existes.
I want to save data if it does not exists in my table. I'm using in select query but it doesn't work.
this is my code:
$sql = "INSERT INTO searchtable (word, position, count) VALUES (:word , :position, :count)";
$statement = $db->prepare($sql);
$temp="SELECT COUNT(word) AS searchtableFromword FROM searchtable WHERE word=$title" ;
if($temp== 0 )
'word' => $title,
'position' => $fileNum,
'count' => $titleVal
IF you only want to insert a record when it does not exists, just use INSERT IGNORE
$sql = "INSERT IGNORE INTO searchtable (word, position, count) VALUES (:word , :position, :count)"; $statement = $db->prepare($sql);
This will make sure that existing rows are left intact an a new one will be inserted if the record is absent.
If you use the IGNORE keyword, errors that occur while executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row is discarded and no error occurs. Ignored errors may generate warnings instead, although duplicate-key errors do not.
Of course for this to be successful, you need a unique index on the the column of interest