How to check in the database if the registration has already been made PDO

Asked

Viewed 4,834 times

2

How do I check if the id user no longer has registration in the database and continue with the 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;
    }
}
  • Ever tried to make a select id_user from tb_comment where id_user = idLogged and check if it returns any lines?

  • It is then only q I am very novice in PHP I must make the select inside the if or outside ?

  • You want to check if ìdLogger exists in the bank before making the insert, correct?

  • Yes that’s what it is..

2 answers

2


Starting from your code, and assuming all the variables in your $_POST have already been captured, make a select and check through the function fetchAll(), if there has been 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 function was used fecthAll() instead of rowCount() due to a restriction of this latter function as described in documentation:

If the last SQL statement executed by the Associated Pdostatement was a SELECT statement, some Databases may Return the number of Rows returned by that statement. However, this behaviour 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, follow 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:

http://php.net/manual/en/pdostatement.fetchall.php

https://stackoverflow.com/questions/11360451/php-pdo-fetchall-returns-empty-array

  • Notice: Undefined variable: query

  • Fatal error: Call to a Member Function bindParam() on null in

  • @Williamalvares pardon, discouragement my hehe, already corrected the variable $query. see if now the query works.

  • It worked, thanks.. I was doing it in a way here that didn’t seem to be anything wrong, man.. and I still don’t know why it didn’t work out the way I did, man

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

THEN YOU COMPARE IT TO 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']); 

            }
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.