Matarishvan
Matarishvan

Reputation: 2422

check duplicate entries in mysql while Inserting into MySql

This is my MySql table

-----------    --------------
location_id    location_name
-----------    --------------
   1              office
   2              hospital
   3              schools

I am running INSERT INTO query based on the location_id.

what i want is - if location id exists, return some message. else run INSERT query.

My Query

$sql = "SELECT location_id FROM tablename GROUP BY location_id HAVING count(*) > 1";
$rs=parent::_executeQuery($sql);
$rs = parent::getAll($rs);

if($rs)
{
     //RUN INSERT QUERY
}
else
{
     //RETURN SOME MESSAGE
}

Well, this is going inside if block everytime.

Upvotes: 0

Views: 861

Answers (1)

Veerendra
Veerendra

Reputation: 2622

Try the if condition like this

if(count($rs)>0)
{
  // RETURN MESSAGE
}
else
{
    // INSERT QUERY
}

As if($rs) will check if the variable have a value or not and in your case it will have a value 0 if there are no location_id found.

So it will be better to check the count of the result.

Upvotes: 1

Related Questions