PHP PDO does not run UPDATE on same page of SELECT

2

Problem: making UPDATE work
Question: Is the script correct?
Request: Identify the reason for not doing the UPDATE and generating error. Error: Notice: Undefined variable: db e Fatal error: Call to a member function prepare () on a non-object
Note: in another project I use the same update and select and it works on the same page Thanks: everyone who can give a light
Code:

<?php
include ("conexao.php");
$email = $_POST['email'];
// Checando se o email informado está cadastrado
$resultad = $db->select_pdo("SELECT * FROM pessoa WHERE email= '{$email}'");
if ( count($resultad) ) {
foreach($resultad as $row) {
  if($row['12'] == 0);
}  
}else {
    echo "<div class='inf' align='center'>Este email não está cadastrado em nosso banco de dados.</div><br /><br />";

            exit();

        }

// gerar senha aleatória
$recupera  = $_POST['recupera'];
switch ($recupera){

case "recupera" :

    recupera_senha($email);
}

function recupera_senha($email){

function geraSenha(){

            //caracteres que serão usados na senha randomica
            $chars = 'abcdxyswzABCDZYWSZ0123456789';
            //ve o tamnha maximo que a senha pode ter
            $max = strlen($chars) - 1;
            //declara $senha
            $senha = null;

            //loop que gerará a senha de 8 caracteres
            for($i=0;$i < 8; $i++){

                    $senha .= $chars{mt_rand(0,$max)};

            }
            return $senha;          
    }

    $senha_randomica   =  geraSenha();
    $senha = md5($senha_randomica);


$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
$headers .= "From: NOME - Webmaster<[email protected]>"; 

$subject = "Sua nova senha SITE";

$message = "Olá, redefinimos sua senha.<br /><br />
           <strong>Nova Senha</strong>: {$senha_randomica}<br /><br />

           <a href='http://LINK/formulario_login.html'>

http://LINK/formulario_login.html

           </a><br /><br />
           Obrigado!<br /><br />
           Webmaster<br /><br /><br />

           Esta é uma mensagem automática, por favor não responda!";

            mail($email, $subject, $message, $headers);

            echo "Sua nova senha foi gerada com sucesso e enviada para o seu email!<br      />
                 Por favor verifique seu email!<br /><br />";



            //Atualiza cadastro
            $db->select_pdo("SELECT * FROM pessoa WHERE email ='{$email}'");
            $data=array ($email);
            $db->update_pdo('UPDATE pessoa SET 'senha_pessoa'=?', $data);
}
?>

connection -------------

<?php
ob_start();
Class PDODatabase{
private $host = 'localhost';
private $user = 'USER';
private $pass= 'SENHA';
private $dbname = 'BASE';
private $DBH;
private $STH;
public $err;
public $result;

//funcao publica para pegar ultimo registro
public function lastInsertId(){
return $this->DBH->lastInsertId();
}
//connect to database and make error system
public function __construct(){
//Connct to database
try{
$this->DBH = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->user,     $this->pass);
$this->DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $err){
echo $this->err->getMessage();
}
}
//close database connection
public function  close_pdo(){
$this->DBH = null;
}
//delete query from database
public function  delete_pdo($sql){
try{
$this->STH = $this->DBH->prepare($sql);
$this->STH->execute();
}
catch(PDOException $err){
return "When we try to delete your query we get this message" . $err->getMessage();
}
}
//update query from database
public function  update_pdo($sql,$data){
try{
$this->STH = $this->DBH->prepare($sql);
$this->STH->execute($data);
return true;
}
catch(PDOException $err){
return "When we try to delete your query we get this message" . $err->getMessage();
}
}
//insert into database
public function  insert_pdo($sql,$data){
try{
$this->STH = $this->DBH->prepare($sql);
$this->STH->execute($data);
}
catch(PDOException $err){
return "When we try to delete your query we get this message" . $err->getMessage();
}
}
//select from database
public function  select_pdo($sql){
$this->STH = $this->DBH->prepare($sql);
$this->STH->execute();
return $this->result = $this->STH->fetchAll();
}
//Row count
public function rowCount_pdo($sql)
{
$this->STH = $this->DBH->prepare($sql);
return   $this->result = $this->STH->rowCount();
}
}
$database = new PDODatabase();
$db =& $database;
//ob_end_flush();
?>

--------- end connection

    
asked by anonymous 24.03.2015 / 15:10

1 answer

1

My suggestion is to separate the geraSenha() setting from within recupera_senha($email) or simply remove geraSenha() .

A function defined within the other

function recupera_senha($email){
function geraSenha(){

You can switch to:

function recupera_senha($email, $db){
  //código ...
  $senha_randomica   =  geraSenha();
 //mais código ...
}

function geraSenha(){
 //código...
 return ....
}

Functions only see variables passed as arguments in the function signature or created within it or a function can not access a global variable.

To fix the problem you can do this:

Change:

function recupera_senha($email){

To:

function recupera_senha($email, $db){

Another suggestion is in place of the $db switch for another function that returns the connection to the database.

    
24.03.2015 / 15:43