Insert in SQL if registration does not exist [duplicate]

0

I have the following PHP function that adds a row to the table:

$idmusica = $_GET['idmusica'];
$queryvota=("
    INSERT INTO euk_sugestoes_votos (idusuario, idmusica)
    VALUES ($userid, $idmusica)
    ");

The table has this structure:

id | idusuario | idmusica

But I wanted you to check if this line with idusuario and idmusica already exists. If it already exists, it should ignore, otherwise it inserts.

How can I do this verification?

Thank you!

    
asked by anonymous 23.04.2018 / 23:25

1 answer

2

If you do not, use index unique to id_usuario , basically it does this automatic check.

idmusica would already solve the problem, but would return an error.

And switching to INSERT INTO as it will not update any field, it will just ignore the registry.

However, REPLACE INTO will change its primary key, if it is index unique .

Another way, also keeping a REPLACE is to use REPLACE , it would look like this, for example:

AUTO_INCREMENT

To create the index, follow the command:

CREATE UNIQUE INDEX idx_unique_idusuario_idmusica
    ON euk_sugestoes_votos (idusuario,idmusica);
    
23.04.2018 / 23:29