-1
I created a PHP class to update the data of a record in a table in the mysql database:
<?php
class InsertAccess{
public function insert_access($reg){
require_once('../conn/conecta.php');
$status = '1';
try{
$sql = "UPDATE `tab_login` SET `last_access` = :date_access, `status` = :sts WHERE `registro` = :reg";
$access = $conecta->prepare($sql);
$access->bindParam(":reg", $reg, PDO::PARAM_STR);
$access->bindParam(":date_access", date('Y-m-d H:i:s'), PDO::PARAM_STR);
$access->bindParam(":sts", $status, PDO::PARAM_STR);
$access->execute();
}catch (Exception $ex){
echo 'ERRO: '.$ex;
}
}
}
?>
You’re giving me an undefined variable message:
Notice: Undefined variable: conecta in C:\wamp64\www\my_dir\actions\class_access.php on line 13
Can anyone tell me the correct way to use a php class to perform this type of action?
connects.php
try {
$servidor = 'localhost';
$usuario = 'root';
$senha = '';
$banco = 'my_db';
$conecta = new PDO("mysql:host=$servidor;dbname=$banco", $usuario , $senha, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$conecta->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(PDOException $e) {
echo 'ERRO DE CONEXÃO: ' . $e->getMessage();
}
Function call
$access_class = new InsertAccess();
$access_class->insert_access($item);
The Insertaccess class is a separate php file, and I’m using it in another php file doing the instance as shown above.
What is in this require at the beginning of the method?
– rray
@rray File that connects to the database using PDO.
– Henqsan
Surely this variable is not declared in conecta.php
– Atila Silva
CONNECTS
$conecta = new PDO("mysql:host=$servidor;dbname=$banco", $usuario , $senha, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$conecta->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
– Henqsan
@Henqsan This code (above) is all the content of the file
conecta.php
?– Valdeir Psr
@Valdeirpsr edited the question and includes the whole code of conecta.php
– Henqsan
@Henqsan Substitua
echo 'ERRO DE CONEXÃO: ' . $e->getMessage();
fordie('ERRO DE CONEXÃO: ' . $e->getMessage());
, makes more sense. Some connection error appears when accessing the class methodInsertAccess
?– Valdeir Psr
@Valdeirpsr no connection error.
– Henqsan
Why create a class that only serves to run an Insert in the bank?
– Costamilam
@Guilhermecostamilam, I thought it best to do so, since I can reuse the class.
– Henqsan
You could do only one function without the class, know the DAO pattern?
– Costamilam
@Guilhermecostamilam, actually I am not an expert in php, but I will give a search on the DAO standard.
– Henqsan