How to verify in the database if the cadastre has already been made PDO

1

How do I check if id of the user no longer has a record in the database and continue with insert ?

if(isset($_POST['submit'])){
    $comment   = trim(strip_tags($_POST['comment']));

    $insert = "INSERT into tb_comment (id_mark, id_user, comment, up_c, down_c, rate, active) VALUES (:post_id, :idLogged, :comment, 0, 0, :star, NOW())";

    try {
        $result = $conexao->prepare($insert);
        $result->bindParam(':post_id', $post_id, PDO::PARAM_INT);
        $result->bindParam(':idLogged', $idLogged, PDO::PARAM_INT);
        $result->bindParam(':star', $star, PDO::PARAM_INT);
        $result->bindParam(':comment', $comment, PDO::PARAM_STR);
        $result->execute();
        $count = $result->rowCount();
        if($count>0){
            echo '<div class="alert alert-sucess">
              <strong>Sucesso!</strong> avaliação cadastrada.
               </div>';
        }else{
          echo '<div class="alert alert-danger">
              <strong>Erro ao cadastrar!</strong> Não foi possível cadastrar a avaliação.
              </div>';
        }

    }catch(PDOException $e){
        echo $e;
    }
}
    
asked by anonymous 10.12.2015 / 22:46

2 answers

2

From your code, assuming that all the variables of your $_POST have already been captured, make a select and check through the function fetchAll() , if there was any return:

$query = $conexao->prepare("select * from tb_comment where id_user = :idLogged");
$query->bindParam(':idLogged', $idLogged, PDO::PARAM_INT);
$query->execute();
$retorno = $query->fetchAll();
if(count($retorno) > 0){
    //usuário está registrado
    //faça o insert aqui
else{
    //nenhum usuário encontrado 
}

Note:

The fecthAll() function was used instead of the rowCount() because of a restriction of this last function, as described in documentation :

  

If the last SQL statement executed by the PDOStatement was   a SELECT statement, some databases may return the number of rows   returned by that statement. However, this behavior is not guaranteed   for all databases and should not be relied on for portable   applications.

That is, it can work, but it is not guaranteed to work as expected. But if you want to test, it follows the same code using rowCount() :

 $retorno = $query->rowCount();
    if($retorno > 0){
        //usuário está registrado
        //faça o insert aqui
    else{
        //nenhum usuário encontrado 
    }

References:

link

link

    
11.12.2015 / 00:10
0
<?php
if(session_id() == '') {
    // checka se tem sessão, se a não tiver sessão , inicia a session
    session_start();
} 

 $checkuser = $_POST['ID'];


    $dados = $conexao_pdo->prepare('SELECT username FROM user WHERE id = ?');
$dados->bindParam(1, $checkuser);
$dados->execute();
if ($dados->rowCount() > 0) {
  $linha = $dados->fetch(PDO::FETCH_OBJ);

  //id não ok
  $_SESSION["checkid"] = "0";

  }else{
     $_SESSION["checkid"] = "1";
     //id ok

  }

    //sessão 0 o id já ta cadastrado e nao pode cadastrar sessão 1 usuário pode cadastrar com id

AFTER YOU COMPARE WITH THE SESSION

if($_SESSION['checkid'] >= 1)  {
            // o id esta disponivel
            $id = $_POST["ID"];


            } else {
                //destroi sessão pois o id não está disponivel 
                $_POST["id"] = "";
                unset($_SESSION['checkid']); 

            }
?>
    
26.01.2017 / 21:59