Bom dia,
Por favor, podem me ajudar? Estou reiniciando o uso de PHP depois de vários anos para auxiliar dois colegas a manter seu site. Ele estava rodando até dia 28 quando apareceu o seguinte erro: Fatal error: Call to a member function prepare() on a non-object in /var/www/html/planpharma.com.br/web/assets/lib/Connect.php on line 58
A estrutura está relacionada assim:
<?php
include_once 'MyPDO.php';
class Connect {
private $conn;
private $type = OBJECT;
private $class = '';
public function __construct(){
$this->conn = new MyPDO();
}
private function valid($parametros){
$arr;
foreach ($parametros as $key => $value){
$arr[":".$key] = $value;
}
return $arr;
}
/**
* Carrega pelo Id
*/
public function getById($tableName, $Id, $locale = false)
{
$sql = " Select * from $tableName Where Id = :Id ";
$parametros['Id'] = $Id;
return $this->exec($sql, $parametros, $locale);
}
public function getTableStructure($tableName) {
$sql = "SHOW FULL COLUMNS FROM ".$tableName;
return $this->exec($sql);
}
/**
*
* executa a sql
* @param string $sql
* @param string[] $parametros
*/
public function exec($sql, $parametros = null, $locale = false) {
$result;
try {
if ($locale){
$statement = $this-> conn->prepare("SET lc_time_names = 'pt_BR'");
$statement->execute();
}
$statement = $this-> conn->prepare ("SET names utf8"); // linha 58 que apresenta o problema//
$statement->execute();
$statement = null;
// para o debug escreve a sql e parametros
messageDebug("SQL: ".$sql);
messageDebug($parametros);
// se nao enviou parametros
if ($parametros == null || (is_array($parametros) && count($parametros) <=0 ) ){
$statement = $this->conn->prepare($sql);
$statement->execute();
}
else{
//douglas para verificar erros que n?o apareceram de outra maneira
$this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// executa a sql
$statement = $this->conn->prepare($sql);
// faz o bind
$statement->execute($parametros);
}
// tipo de retorno
switch ($this->type) {
case NORMAL:
$result = $statement->fetchAll();
break;
case OBJECT:
$result = $statement->fetchAll(PDO::FETCH_OBJ);
break;
case JSON:
$result = json_encode($statement->fetchAll(PDO::FETCH_OBJ));
break;
case O_CLASS:
$result = $statement->fetchAll(PDO::FETCH_CLASS, $this->class);
break;
default:
$result = $statement->fetchAll();
break;
}
} catch (Exception $e) {
messageDebug($e);
}
return $result;
}
/**
* faz o update
* @param string $parametros
* @param string $tabela
* @param string $where - pode passar o parametro where inteiro, ou somente o id
*/
public function update($param, $table, $where){
/**
************************** EXEMPLO DE USO *******************************
* $record["firstName"] = "Carol";
* $record["lasTname"] = "Jones";
* $conn->AutoExecute($table,$record,'UPDATE', "lastname like 'Sm%'");
* # executes "UPDATE $table SET firstName='Carol',lasTname='Jones' WHERE lastname like 'Sm%'";
***************************************************************************
*/
$result = false;
// valida alguns parametros
if (!$this->valideSql($param, $table)){
return $result;
}
// valida o campo where
if(empty($where) or $where == ""){
messageDebug("o campo where precisa de pelo menos 1 parametro");
return $result;
}
$result = $this->autoExecute($table, $param, UPDATE, $where);
return $result;
}
/**
*
* INSERE UM NOVO
* @param array $param
* @param String $table
*/
public function create($param, $table) {
$result = false;
// valida alguns parametros
if (!$this->valideSql($param, $table)){
return $result;
}
// executa a insercao
$result = $this->autoExecute($table, $param, INSERT);
return $result;
}
/**
*
* validar parametros
*/
private function valideSql($param, $table){
$result = true;
if (count($param) == 0 or !is_array($param) ){
messageDebug("Parametros nao pode ser vazio e deve ser um array contendo os nome dos campos");
$result = false;
}
if( empty($table) or $table == ""){
messageDebug("tabela nao pode ser vazio ");
$result = false;
}
return $result;
}
/**
*
* gera o sql de update ou insert
* @param string $tabela
* @param array $parametros
* @param string $type
* @param string $where
*/
private function autoExecute($table, $param, $type, $where = null){
$result = null;
$sql = "";
$statement = $this->conn->prepare("SET names utf8");
$statement->execute();
$statement = null;
try {
switch ($type) {
case UPDATE:
$i = 0; $params="";
foreach ($param as $key => $value) {
if ($i > 0)
$params.= ", ";
$params .= " $key= :$key";
$i++;
}
if (is_numeric($where)){
$where = " id = ".$where;
}
$sql = " UPDATE ".$table." SET ".$params." WHERE ".$where;
break;
case INSERT :
$i = 0;
$keys = "";
$values = "";
foreach ($param as $key => $value) {
if ($i > 0){
$keys.= ", ";
$values.=", ";
}
$keys .= $key;
$values.= ":$key";
$i++;
}
$sql = " INSERT INTO ".$table." (".$keys.") VALUES (".$values.")";
break;
case DELETE :
if (is_numeric($where)){
$where = " id = ".$where;
}
$sql = " DELETE FROM ".$table." WHERE ".$where;
break;
}
messageDebug($sql);
messageDebug($param);
$stmt = $this->conn->prepare($sql);
messageDebug($stmt);
$result = $stmt->execute($param);
messageDebug($result);
if ($type == INSERT){
$result = $this->conn->lastInsertId();// $stmt->fetch(PDO::FETCH_ASSOC);
messageDebug($result);
}
} catch (Exception $e) {
messageDebug($e);
}
return $result;
}
public function close(){
$conn = null;
}
/**
*
* deleta uma linha
* @param string $tabela
* @param int $id
*/
public function delete($table, $whereOrId, $param = null){
$result = false;
if( empty($whereOrId) or $whereOrId == "" or (is_numeric($whereOrId) and $whereOrId == 0)){
messageDebug("o campo ID nao pode ser vazio");
return $result;
}
if( empty($table) or $table == ""){
messageDebug("o campo tabela nao pode ser vazio");
return $result;
}
// executa a delecao
$result = $this->autoExecute($table, $param, DELETE, $whereOrId);
return $result;
}
public function setType($type){
$this->type = $type;
}
public function setClass($class){
$this->class = $class;
}
}
?>
MyPDO.php
<?php
include 'constants.php';
class MyPDO extends PDO{
// host
private $host = array(true => 'localhost', false => 'cdbwebto-plan.mysql.uhserver.com');
// tipo de banco
private $driver = 'mysql';
// porta
private $port = '3306';
// nome do banco
private $dbName = "cdbwebto_plan";
// usuario do banco
private $user = array(true => 'root', false => 'cdbwebto_plan');
// senha do banco
private $password = array(true => '123456', false => 'IkaQddZHG1@'); // está no banco de produ??o
public function __construct(){
try
{
parent::__construct($this->driver.':host='.$this->host[TEST].';port='.$this->port.';dbname='.$this->dbName,$this->user[TEST], $this->password[TEST]);
//instancia o objeto PDO, conectando com o banco mysql
$conn = new PDO('mysql:host=localhost;port=3306;dbname=compreal_compre', 'root', '');
}
catch (PDOException $i)
{
messageDebug("Erro: <code>" . $i->getMessage() . "</code>");
}
}
/**
*
* Pega os drivers disponiveis
*/
function driversAvailable() {
return PDO::getAvailableDrivers();
}
}
?>