I am making a select for deletar
or inserir
records in my bd
according to the amount of records returned, but the tests I have done are not correct, I do not know exactly how to count the records in a return pdo
.
I've already used count
and it did not work, I think I'm making a lot of mistakes when trying.
I'll post the commented code to help with understanding, the code is this:
// VERIFICANDO DIREITOS
$sqlInterface = "
SELECT
gasUsuarioServico.IdUsuario,
gasUsuarioServico.IdServico,
gasServico.IdInterface
FROM
gasUsuarioServico
INNER JOIN gasServico ON (gasUsuarioServico.IdServico = gasServico.IdServico)
WHERE
(gasUsuarioServico.IdUsuario = ?) AND
(gasServico.IdInterface = ?)";
$stm = $pdo->prepare($sqlInterface);
// DEFINE O TIPO DA VARIÁVEL PDO::PARAM_INT OU STR
$stm->bindValue(1, $IdUsuario, PDO::PARAM_INT);
$stm->bindValue(2, $IdInterface, PDO::PARAM_INT);
$stm->execute();
$registros = $stm->fetchAll(PDO::FETCH_ASSOC);
// TENTATIVA DE CONTAGEM DE REGISTROS RETORNADOS
$conSqlDel = count($registros);
if( $conSqlDel == 0 ){
$sqlDel = "DELETE FROM gasUsuarioInterface WHERE gasUsuarioInterface.IdUsuario = ? AND gasUsuarioInterface.IdInterface = ?";
$stm = $pdo->prepare($sqlDel);
$stm->bindValue(1, $IdUsuario, PDO::PARAM_INT);
$stm->bindValue(2, $IdInterface, PDO::PARAM_INT);
$retorno = $stm->execute();
} else {
$sqlInterfaceReg = "
SELECT *
FROM
gasUsuarioInterface
WHERE
(gasUsuarioInterface.IdUsuario = ?) AND
(gasUsuarioInterface.IdInterface = ?)";
$stm = $pdo->prepare($sqlInterfaceReg);
// DEFINE O TIPO DA VARIÁVEL PDO::PARAM_INT OU STR
$stm->bindValue(1, $IdUsuario, PDO::PARAM_INT);
$stm->bindValue(2, $IdInterface, PDO::PARAM_INT);
$stm->execute();
$registros = $stm->fetchAll(PDO::FETCH_ASSOC);
$countInsert = count($registros);
if ($countInsert == 0) {
$arrayDados = array('IdUsuario' => $IdUsuario, 'IdServico' => $IdInterface );
$retorno = $crud->insert($arrayDados);
}
}
In the test I made the variable $ conSqlDel return 2 records, but in my bd the value is zero, that is, no records returned.
I'm sending a JSON return, like this:
// MENSAGEM AO USUÁRIO
if ($retorno):
$retorno = array('codigo' => 1, 'mensagem' => print_r($conSqlDel) );
echo json_encode($retorno);
exit();
else:
$retorno = array('codigo' => '0', 'mensagem' => ' Registro não foi atualizado' );
echo json_encode($retorno);
exit();
endif;
I do not know how to check the contents of the variables, since a simple echo
or print_r
does not work.