3
$sql_insert = "INSERT IGNORE .....";


if(mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error()))
{
      //code to execute
}

I want to execute code if the row is inserted. Is there some time of value that can be returned that would tell me if the statement was inserted or ignored?

Edit: Right now, "code to execute" always executes - even on ignore instances

Bob Cavezza
  • 2,810
  • 7
  • 38
  • 56

2 Answers2

17

mysql_affected_rows() will return 1 or 0, 1 if the insert took place

if(mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error()))
{
      if(mysql_affected_rows($link)==1){
       //insert took place
       }else{
       //no insert
       }


}
  • Thanks - accepted this answer. Quick question - doesn't matter if the mysql_query is in an if statement, correct? - since it will go through every time. – Bob Cavezza Mar 10 '11 at 02:47
  • if(mysql_query that only check if the statement runs\ is valid, wont tell you insert vs ignore –  Mar 10 '11 at 03:00
  • Need to ask something, is there any other instance except duplicate primary key situation when affected rows will return zero ? Or evey case of 0 affected rows in this case be considered that of a duplicate primary key ? – Palak Taneja Jul 15 '14 at 12:15
  • ref.: https://www.php.net/manual/en/mysqli.affected-rows.php – Alex Szücs Mar 16 '21 at 17:24
0

for PDO, answer will be

$query="insert ignore into ...;";
$statement=$link->prepare($query);
$statement->execute();
if($statement->rowCount()==1){
   //insert confirmed;
}else{
   //ignore confirmed;
}
sifr_dot_in
  • 3,153
  • 2
  • 33
  • 42