Connection error using namespace

Asked

Viewed 88 times

1

I have a file that is responsible for the connection to BD and is in PDO.

<?php

namespace clientes\model;

class conexaoPDO {

public static $instance;

private function __construct() {

}

public static function getIntance() {

    if (!isset(self::$instance)) {

        self::$instance = new \PDO('mysql::host=localhost;dbname=erpsuper', 'root', '', array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
        self::$instance->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        self::$instance->setAttribute(\PDO::ATTR_ORACLE_NULLS, \PDO::NULL_EMPTY_STRING);
    }
    return self::$instance;
}

}

However I am not able to connect the system to the database, is appearing an error that I am not able to solve.

Erro:
<b>Fatal error</b>:  Call to private 
clientes\model\conexaoPDO::__construct() from invalid context in 
<b>C:\xampp\htdocs\ERPSUPER\view\clientes\pesqcliente.php</b> on line 
<b>15</b><br />

Follow the code of routine:

/*
 * Script:    DataTables server-side script for PHP and MySQL
 * Copyright: 2012 - John Becker, Beckersoft, Inc.
 * Copyright: 2010 - Allan Jardine
 * License:   GPL v2 or BSD (3-point)
*/

require_once("../../bootstrap.php");

use clientes\model\conexaoPDO;


$conn = new conexaoPDO();

class TableData {



public function get($table, $index_column, $columns) {
    // Paging
    $sLimit = "";
    if ( isset( $_GET['start'] ) && $_GET['length'] != '-1' ) {
        $sLimit = "LIMIT ".intval( $_GET['start'] ).", ".intval( 
    $_GET['length'] );
    }

    // Ordering
    $sOrder = "";
    if ( isset( $_GET['order'][0]['column'] ) ) {
        $sOrder = "ORDER BY  ";

        for ( $i=0 ; $i<count($columns) ; $i++ ) {
            if ( $_GET[ 'columns'][$i]['orderable'] == "true" ) {
                $sortDir = (strcasecmp($_GET['order'][0]['dir'], 'ASC') == 
0) ? 'ASC' : 'DESC';
                if($_GET['order'][0]['column'] == $i){
                $sOrder .= "`".$columns[ intval( $_GET['order'][0]['column'] 
) ]."` ". $sortDir .", ";
                }
            }
        }

        $sOrder = substr_replace( $sOrder, "", -2 );

        //if ( $sOrder == "ORDER BY" ) {
        //  $sOrder = "";
        //}
    }

    /* 
     * Filtering
     * NOTE this does not match the built-in DataTables filtering which does 
it
     * word by word on any field. It's possible to do here, but concerned 
about efficiency
     * on very large tables, and MySQL's regex functionality is very limited
     */
    $sWhere = "";
    if ( isset($_GET['search']["value"]) ) {
        $sWhere = "WHERE (";

        for ( $i=0 ; $i<count($columns) ; $i++ ) {


            if ( isset($_GET['search']["value"])) {

                $sWhere .= "`".$columns[$i]."` LIKE :search OR ";


            }
        }
        $sWhere = substr_replace( $sWhere, "", -3 );

        $sWhere .= ')';
    }

    // Individual column filtering
    for ( $i=0 ; $i<count($columns) ; $i++ ) {
        if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == 
"true" && $_GET['sSearch_'.$i] != '' ) {
            if ( $sWhere == "" ) {
                $sWhere = "WHERE ";
            }
            else {
                $sWhere .= " AND ";
            }
            $sWhere .= "`".$columns[$i]."` LIKE :search".$i." ";
        }
    }

    // SQL queries get data to display
    $sQuery = "SELECT SQL_CALC_FOUND_ROWS `".str_replace(" , ", " ", 
implode("`, `", $columns))."` FROM `".$table."` ".$sWhere." ".$sOrder." 
".$sLimit;
    $statement = conexaoPDO::getInstance()->prepare($sQuery);

    // Bind parameters
    if ( isset($_GET['search']['value'])) {
        $statement->bindValue(':search', '%'.$_GET['search']['value'].'%', 
PDO::PARAM_STR);
    }
    for ( $i=0 ; $i<count($columns) ; $i++ ) {
        if ( isset($_GET['bSearchable_'.$i]) && $_GET['bSearchable_'.$i] == 
"true" && $_GET['sSearch_'.$i] != '' ) {
            $statement->bindValue(':search'.$i, 
'%'.$_GET['sSearch_'.$i].'%', PDO::PARAM_STR);
        }
    }
    //var_dump($sQuery);
    $statement->execute();
    $rResult = $statement->fetchAll();

    $iFilteredTotal = current(conexaoPDO::getInstance()->query('SELECT 
FOUND_ROWS()')->fetch());

    // Get total number of rows in table
    $sQuery = "SELECT COUNT(`".$index_column."`) FROM `".$table."`";
    $iTotal = current(conexaoPDO::getInstance()->query($sQuery)->fetch());

    // Output
    $output = array(
        "draw" => intval($_GET['draw']),
        "recordsTotal" => $iTotal,
        "recordsFiltered" => $iFilteredTotal,
        "data" => array()
    );

    // Return array of values
    foreach($rResult as $aRow) {
        $row = array();         
        for ( $i = 0; $i < count($columns); $i++ ) {
            if ( $columns[$i] == "version" ) {
                // Special output formatting for 'version' column
                $row[] = ($aRow[ $columns[$i] ]=="0") ? '-' : $aRow[ 
$columns[$i] ];
            }
            else if ( $columns[$i] != ' ' ) {
                $row[] = $aRow[ $columns[$i] ];
            }
        }
        $output['data'][] = $row;
    }

    echo json_encode( $output );
}
}

header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');
// Create instance of TableData class
$table_data = new TableData();

// Get the data
$table_data->get('clientes', 'id', array('id', 'nome', 'fantasia', 
'cnpj_cpf','municipio','nome_contato','email'));

Could you help me?

  • 1

    If you have a Singleton, it doesn’t make much sense to try to create an object via constructor like this line $conn = new conexaoPDO();

1 answer

0


Probably the error is in the line that tries to create an object via constructor because it is marked as private. Since you’re wearing a Singleton ... that doesn’t make much sense.

Line that generates the error:

$conn = new conexaoPDO();

Important Delhate of Connection Class:

private function __construct() {}
  • Hello rray, Good Afternoon! ?

  • @Samuelvincenzo $conn not used anywhere, so you can remove that line $conn = new conexaoPDO();

  • è that I forgot to change the lines, but even if I remove this line appears another error saying that can not connect

  • @Samuelvincenzo which is the exact error message?

  • this error appears: <b>Fatal error</b>: Call to Undefined method clients model connectedPDO::getInstance() in <b>C: xampp htdocs ERPSUPER view clients pesqclient.php</b> on line <b>89</b><br />

  • @Samuelvincenzo his method was defined as getIntance() and you call them are as conexaoPDO::getInstance() see that there was one missing s in the definition of the name.

  • Thank you so much was that very! Valew

Show 2 more comments

Browser other questions tagged

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