Uncaught Error: Call to a member function fetchColumn () on boolean

0

Hello, why do I get that error? this function is to validate if there is a user or not but I get this problem:

  

Fatal error: Uncaught Error: Call to a member function fetchColumn ()   on boolean in C: \ xampp \ htdocs \ login_oracle \ funcs \ funcs.php: 50 Stack   trace: # 0 C: \ xampp \ htdocs \ login_oracle \ registry.php (38):   userExist ('ortega') # 1 {main} thrown in   C: \ xampp \ htdocs \ login_oracle \ funcs \ funcs.php on line 50

function userExist ($ user)         {             global $ db;

        $num = $db->query("SELECT COUNT(*) FROM usuarios WHERE DEPARTMENT_ID=". $usuario)->fetchColumn(); //<<<<<<< AQUI ESTA EL PROBLEMA

        printf("<script type='text/javascript'>alert('LO DEVUELTO ES : $num'); </script>"); 

        if ($num != 0)
        {
            return true;
        } 
        else {
            return false;
        }
    }

I could use rowCount but since it is a select this in ORACLE does not work well, only with update, insert or stop. How else can I know the number of rows affected from the last select query I made in PDO ORACLE? or how can I solve that code error. thanks

    
asked by RicardoBarros 12.12.2017 в 20:21
source

2 answers

1

Your code has two problems:

  • It is vulnerable to SQL injection. To correct it, you must implement prepared queries.
  • You are not using fetchColumn well.
  • Apart from this, we will use other techniques, such as the ternary operators , to simplify the code .

    Since you mention it in the question, rowCount you do not need it here, because what your query does is precisely to count the rows that there are.

    I propose this solution:

        $strSQL="SELECT COUNT(*) FROM usuarios WHERE DEPARTMENT_ID=:id";
        $stmt = $db->prepare($strSQL);
    
        if ($stmt){
            /*Pasamos los datos aparte para evitar la Inyección de código malicioso*/
            $arrParams=array(":id"=>$usuario);
            $stmt->execute($arrParams);
            $num=$stmt->fetchColumn();
            /*El operador ternario permitirá hacer la evaluación una sola vez*/
            $bolResultado=($num != 0) ? true : false;
            printf("<script type='text/javascript'>alert('LO DEVUELTO ES : $num'); </script>"); 
    
        }else{
    
            $bolResultado=false;                        
        }
    
        return $bolResultado;
    
        
    answered by 13.12.2017 в 00:42
    0

    When the query does not return any result as an INSERT or has an error, I think it returns true or false.

    you could validate it like this:

    $query = $db->query("SELECT COUNT(*) FROM usuarios WHERE DEPARTMENT_ID=". $usuario);
    if (!is_bool($query)){
       $num = $query->fetchColumn();
    } else ...
    

    Greetings.

        
    answered by 12.12.2017 в 22:00