Problems with Pdo error while creating logerror.txt file

Asked

Viewed 95 times

-1

Notice: Undefined variable: strErro

   <?php
  class DB{
  private static $conn;
  static function getConn(){
      if(is_null(self::$conn)){
          self::$conn = new PDO('mysql:host=localhost;dbname=sllapsocial','root','');
          self::$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
     }

     return self::$conn;
  }
   }


   function logErros($errno){
   if(error_reporting()==0) return;

  $exec = func_get_arg(0);

   $errno = $exec->getCode();
   $errstr = $exec->getMessage();
   $errfile = $exec->getFile();
   $errline = $exec->getLine();
   $err = 'CAUGHT EXCEPTION';

  if(ini_get('log_errors')) error_log(sprintf("PHP %s: %s in %s on line     %d",$err,$errstr,$errfile,$errline));

   $strErro = 'erro:'.$err.' no arquivo: '.$errfile.' ( linha '.$errline.' ) ::     IP('.$_SERVER['REMOTE_ADDR'].') data:'.date('d/m/y H:i:s')."\n";
   }

  $arquivo = fopen('logerro.txt','a');
//Aparece aqui Notice: Undefined variable: strErro estou fazendo corréto?
    fwrite($arquivo,$strErro);
    fclose($arquivo);

   set_error_handler('logErros');

1 answer

1


The problem is the scope of the variable $strErro it has been set within the function and cannot be accessed outside of it.

   function logErros($errno){
      //código omitido ...

      if(ini_get('log_errors')) //if em uma linha...
         error_log(sprintf("PHP %s: %s in %s on line     %d",$err,$errstr,$errfile,$errline));

      $strErro = 'erro:'.$err.' no arquivo: '.$errfile.' ( linha '.$errline.' ) ::     IP('.$_SERVER['REMOTE_ADDR'].') data:'.date('d/m/y H:i:s')."\n";
   } //<---- fim da função $strErro não pode ser acessada depois dessa linha.

   //código fora da função....  
   $arquivo = fopen('logerro.txt','a');
   fwrite($arquivo,$strErro);

The simplest solution is to give one return $strErro in the end function. The new call would be made:

$msg = logErros($errno); 
if($msg){
   fwrite($arquivo, $msg);
   fclose($arquivo);
}     
  • Put the return $strErro at the end of logErros() ?

  • 1

    Amazing how a simple indentation CORRECT plays the error to the eyes.

  • 1

    @Papacharlie, for it is first thought if it was not excutado then saw that it was a one line if =\

  • 1

    Yeah, that one } after $strErro is tense, kills any logic - you think it’s one thing but it’s another. The code has "reverse indentation" oo

  • The PDO has nothing to do with it. The problem is that you have mistakes, and when you get one, it appears next, and then another...

Show 1 more comment

Browser other questions tagged

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