PHP PDO does not run UPDATE on the same SELECT page

Asked

Viewed 393 times

2

Problem: make UPDATE work
Question: Is the script correct?
Request: Identify the reason for not doing UPDATE and generate error.
Error: Notice: Undefined variable: db and 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: to all 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();
?>

---------connected end

  • 1

    Eduardo, can you [Dit] your question to make it more readable.

  • Formatting done, thanks @gmsantos

  • 2

    Pass the $db variable to the function.

1 answer

1

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

A function defined within the other

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

Can change 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 argument in the function signature or created within it or a function cannot access a global variable.

To fix the problem can do so:

Change:

function recupera_senha($email){

To:

function recupera_senha($email, $db){

Another suggestion is instead of the parameter $db exchange for another function that returns the connection to the database.

  • Connection file data I’m using added to the question.

  • Your connection is right, what is missing is to pass it as parameter in function @Duardo belt, :P then put another example.

  • On hold @rray, thank you!

  • @Eduardocorreia follows the example this is what is happening with your code, when the first time will give error it is necessary to uncomment the commented lines and comment on the not commented :P.

Browser other questions tagged

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