Carlos Santiago
Carlos Santiago

Reputation: 73

Check if value exist in Mysql Database on PHP

When I'm updating an item (ativo) of an employee (colaborador) I need to check if an employee that the user input exists or not in the DB, and if it doesn't - give an error message. I don't know how can I do it, can you guys point me to some tutorial that explains it? Thanks in advance!
This is my query btw:

 $pdo = Database::connect();

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE ativos SET ativo = ?, comentario = ?, data_aquisicao = ?,
                localizacao = ?, fabricante = ?, modelo = ?, 
                imei = ?, numero_serie = ?, ativo_sap = ?, 
                anexo_a = ?, evento = ?, data_evento = ?,
                id_colaborador = (SELECT id_colaborador 
                                    FROM colaboradores 
                                    WHERE nome = ? 
                                    LIMIT 1
                                  ) 
        WHERE id_ativo = ?";

$q = $pdo->prepare($sql);
$q->execute(array($ativo,$comentario,$data_aquisicao,$localizacao,
            $fabricante,$modelo,$imei,$numero_serie,$ativo_sap,
            $anexo_a,$evento,$data_evento,$id_colaborador,$id));

And this is the input (i don't know if it's needed to validate if the row exist)

<input autocomplete="off" name="id_colaborador" type="text"  placeholder="Nome do Colaborador" value="<?php echo !empty($nome)?$nome:'';?>" class='auto'>

Upvotes: 0

Views: 82

Answers (1)

Leandro Finger
Leandro Finger

Reputation: 86

Your query is not considering the possibility of homonyms. So, you'd better use some auto_complete field to get the 'id_colaborador' based on the name and keep it in a hidden input field and then execute the update with the exact values.

Upvotes: 1

Related Questions