Validate, if already exists do not INSERT

2

I have the following code that registers in the database the id of an article that the user liked.

$sql = "INSERT INTO favoritos (id_user, id_oferta)
VALUES ('$login_session', '$id')";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

As I have the code, the user can like the same article as often as he likes.

How can I resolve this situation?

    
asked by anonymous 22.08.2015 / 18:47

4 answers

4

does the search for this favorite and if it exists do not insert it.

$sql = "select * from favoritos where id_user=? and id_oferta=? limit 1"
$stmt=$conn->prepare($sql);
$stmt->excute(array($login_session,$id));
$result= $stmt->fetch(PDO::FETCH_ASSOC)

 if($result != false){ //ja existe
//   ..insere no banco
 }
    
22.08.2015 / 19:09
2

Another solution to not having to make two requests in the database is to do an insert with select :

INSERT INTO 
  favoritos (id_user, id_oferta)
SELECT
  ('$login_session', '$id')
WHERE 
  NOT EXISTS( SELECT 1 FROM favoritos WHERE id_user = '$login_session' AND id_oferta = '$id')
    
23.08.2015 / 21:05
2

I would use ON DUPLICATE KEY . You can read more at DOC . The advantage is having a single query for insert and update .

INSERT INTO favoritos( id_user, id_oferta )
VALUES( $login_session, $id )
ON DUPLICATE KEY UPDATE id_user = $login_session, id_oferta = $id
    
23.08.2015 / 18:10
1

If someone has a similar problem, my code is as follows:

//verifica se já existe
$query = mysql_query("select * from favoritos where id_user='$login_session' AND id_oferta='$id'", $connection);
$rows = mysql_num_rows($query);
if ($rows != false) {
echo "ja existe";
} else {

 //Faz o que eu quero :p
}
    
22.08.2015 / 19:32