public function connect()
{
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
try
{
$PDO = new PDO ( 'mysql:host=localhost;dbname=profocus', 'root', '', $opt );
}
catch ( PDOException $e )
{
$e->getMessage( Route::ErrorPage() );
}
return $PDO;
}
$db = new Database();
$cnn = $db->connect();
<?php
class model_home extends model
{
public function __construct()
{
parent::__construct();
var_dump($db);
}
public function return_data()
{
$name = "228";
$stmt = $cnn->prepare("INSERT INTO headers (parent) VALUES (:parent)");
$stmt->bindParam(":parent", $name);
$stmt->execute();
}
}
?>
Fatal error: Call to a member function prepare() on null
<?php
namespace Common;
final class Connection
{
protected static $link;
public static function init() {
if ( is_null(self::$link) ) {
try {
$attr = array(
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => TRUE,
);
self::$link= new \PDO("mysql:host=localhost;dbname=localhost;charset=utf8", "local", "host", $attr);
} catch (\PDOException $e) {
echo "error";
file_put_contents('error.txt', $e->getMessage(), FILE_APPEND);
}
}
}
/**
* @return \PDO;
*/
public static function con() {
return self::$link;
}
}
//код....
//код....
//код....
Load::init();
Connection::init();
$router = new Router();
<?php
namespace Common\Base;
use Common\Connection;
abstract class Model {
/**
* prefix for tables
*/
const PREFIX = "";
/**
* @var
*/
protected $table;
/**
* @var
*/
protected $key;
/**
* @return mixed
*/
public function findAll() {
return $this->fetch("SELECT * FROM " . self::PREFIX . $this->table . " ");
}
/**
* @param array $args
* @return array|string
*/
public function findBy(Array $args) {
$stmt = Connection::con()->prepare("SELECT * FROM " . self::PREFIX . $this->table . " where {$this->key} = ?");
$data = "";
if ( $stmt->execute($args) ) {
while ($row = $stmt->fetch()) {
$data[] = $row;
}
}
return $data;
}
/**
* @param $query
* @return mixed
*/
protected function fetch($query) {
$stmt = Connection::con()->query($query);
$stmt->setFetchMode(\PDO::FETCH_ASSOC);
$data = "";
while ($row = $stmt->fetch()) {
$data[] = $row;
}
return $data;
}
}