<?php
$mysql_host='mysql1.000webhost.com';
$mysql_dbname='a8130617_skola';
$mysql_username='something';
$mysql_password='something';
class mysql {
try{
public $db = new PDO("mysql:host=$mysql_host;dbname=$mysql_dbname",
$mysql_username, $mysql_password);
}
catch(PDOException $e){
echo $e->getMessage();
}
} //ERROR EXCLAMATION MARK HERE???
?>
why does netbeans 6.9.1 consider this to be false syntax?
many thanks
Do you know anything about OOP ?
Class should contain fields and/or methods. You just surrounded a piece of code with class{}. It is not programming.
Read about OOP in PHP - here is manual: http://php.net/manual/en/language.oop5.php
Read it for your own good.
Edit:
I know that following example can make you much lazy but I'll take a shoot and believe you will read more.
Example class for connections can look like:
class Mysql {
protected $_host;
protected $_dbname;
protected $_username;
protected $_password;
protected $_db;
public function __construct($host = null, $dbname = null, $username = null, $password = null)
{
$this->_host = $host;
$this->_dbname = $dbname;
$this->_username = $username;
$this->_password = $password;
}
public function connect()
{
try {
$this->_db = new PDO('mysql:host=' . $this->_host . ';dbname=' . $this->_dbname, $this->_username, $this->_password);
}
catch(PDOException $e){
echo $e->getMessage();
}
}
public function getDb()
{
return $this->db;
}
public function setHost($host)
{
$this->_host = $host;
return $this;
}
public function getHost()
{
return $this->_host;
}
public function setDbname($dbname)
{
$this->_dbname = $dbname;
return $this;
}
public function getDbname()
{
return $this->_dbname;
}
public function setUsername($username)
{
$this->_username = $username;
return $this;
}
public function getUsername()
{
return $this->_username;
}
public function setPassword($password)
{
$this->_password = $password;
return $this;
}
public function getPassword()
{
return $this->_password;
}
}
And example usage:
$mysql = new Mysql('mysql1.000webhost.com', 'a8130617_skola', 'something', 'something');
$mysql->connect();
try{
public $db = new PDO("mysql:host=$mysql_host;dbname=$mysql_dbname",
$mysql_username, $mysql_password);
}
catch(PDOException $e){
echo $e->getMessage();
}
Try catch blocks need to be inside a method. But going with that, not sure why you are wrapping this in a class? Your class is a wrapper for an already defined class.
Related
Hey guys how can i assign PDO to my AbstractRepository class?
I got this error
#Fatal error: Uncaught TypeError: Cannot assign PDO to property #
class DataBase {
private $conn;
public static $instance;
private static $dsn = 'mysql:host=localhost;dbname=db';
private static $username = 'db';
private static $password = 'db';
public function __construct()
{
try {
$this->conn = new PDO(self::$dsn, self::$username, self::$password);
} catch (\PDOException $exception) {
echo 'Problem mit der Datenbankverbindung' . $exception->getMessage();
die();
}
}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function getConnection() {
return $this->getInstance()->conn;
}
}
abstract class AbstractRepository{
protected DataBase $connection;
public function __construct(){
$this->connection = DataBase::getInstance()->getConnection();
}
}
This is how you can return the Value of type PDO
class DataBase extends PDO{
public static $instance;
private static $dsn = 'mysql:host=localhost;dbname=db';
private static $username = 'db';
private static $password = 'db';
public function __construct()
{
try {
parent::__construct = new PDO(self::$dsn, self::$username, self::$password);
} catch (\PDOException $exception) {
echo 'Problem mit der Datenbankverbindung' . $exception->getMessage();
die();
}
}
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
abstract class AbstractRepository{
protected DataBase $connection;
public function __construct(){
$this->connection = DataBase::getInstance();
}
}
Today I did some modifications into my database class. One of them was to use singleton pattern but I'm not 100% sure if i'm doing it right since I have never done this before.
It seems to work tho but still not sure if it does what's supposed to do.
Here is a sample. What do you think? Any suggestions are welcome :)
<?php
class Database {
protected static $instance;
private static $dsn = DB_TYPE.":host=".DB_HOST.";dbname=".DB_NAME;
private static $username = DB_USER;
private static $password = DB_PASS;
private function __construct() {
try {
self::$instance = new PDO(self::$dsn, self::$username, self::$password);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
die($e->getMessage());
}
}
private function __clone() { }
public static function getInstance() {
if(!self::$instance) {
new Database();
}
return self::$instance;
}
public function read($query, $data = [])
{
$DB = Database::getInstance();
$stm = $DB->prepare($query);
if($stm) {
$check = $stm->execute($data);
if($check) {
$result = $stm->fetchAll(PDO::FETCH_OBJ);
}
}
}
if(is_array($result) && count($result) > 0) {
return $result;
}
return false;
}
}
// test
echo '<pre>';
print_r(Database::read("SELECT * FROM table"));
I've made a simple Database class to handle my database connections. But it's somehow not working? At first it wasn't working with MySQLi, so i tried PDO – which ain't working either.
I am however eager to make PDO work. I've already googled and searched here at StackOverflow, but without luck.
Here's my class:
class Database
{
// Local
protected $_host = "localhost";
protected $_user = "root";
protected $_pass = "root";
protected $_database = "hs";
protected $_connection;
// Construct
private function __construct()
{
try
{
$this->_connection = new PDO('mysql:host=localhost;dbname=hs', $this->_user, $this->_pass);
$this->_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
}
public function login($usr, $pwd)
{
echo "hi";
}
}
And here's the execution:
if(isset($_POST['hs_login']))
{
$db = new Database;
$db->login($_POST['hs_username'], $_POST['hs_password']);
}
Thanks in advance! :)
Constructors are always public so change that like so:
class Database
{
// Local
protected $_host = "localhost";
protected $_user = "root";
protected $_pass = "root";
protected $_database = "hs";
protected $_connection;
// Construct
public function __construct()
{
try
{
$this->_connection = new PDO('mysql:host=localhost;dbname=hs', $this->_user, $this->_pass);
$this->_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
}
public function login($usr, $pwd)
{
echo "hi";
}
}
Also, new Database is a method call so change that like so:
if(isset($_POST['hs_login']))
{
$db = new Database;
$db->login($_POST['hs_username'], $_POST['hs_password']);
}
Just wanted to point out, that there are some cases, when you can use private constructors. One of the practical use of them is with Databases, so it's relevant in your case as well. This design pattern is called Singleton pattern, and it relies on static method calls. You don't have to instantiate the class, as instantiation is handled by the class itself. I've put together an example:
<?php
class Database {
private static $instance = null;
private $db;
private static $last_result;
private function __construct() {
try {
$pdo_param = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$this->db = new PDO("mysql:host=YOUR_HOSTNAME;dbname=YOUR_DBNAME", "YOUR_USERNAME", "YOUR_PASSWORD", $pdo_param);
}
catch (PDOException $e) {
die($e->getMessage());
}
}
private static function getInstance() {
if (self::$instance == null) {
self::$instance = new self();
}
return self::$instance;
}
public static function query($sql) {
try {
$instance = self::getInstance();
$stmt = $instance->db->prepare($sql);
$stmt->execute();
self::$last_result = $stmt->fetchAll();
return self::$last_result;
}
catch (PDOException $e) {
die($e->getMessage());
}
}
public static function prepare($sql, $params) {
try {
$instance = self::getInstance();
$stmt = $instance->db->prepare($sql);
$stmt->execute($params);
self::$last_result = $stmt->fetchAll();
return self::$last_result;
}
catch (PDOException $e) {
die($e->getMessage());
}
}
}
$users = Database::query("SELECT * FROM users");
$filtered_users = Database::prepare("SELECT * FROM users WHERE username = :username", array(":username" => "john_doe"));
?>
<pre><?php
print_r($users);
print_r($filtered_users);
?></pre>
Singleton design pattern is really useful when you want to make sure, that there's ONLY ONE instance of a class in any given time.
I have a simple database class that basically encompasses the functions below, so I decided to make discreet classes to do the same thing, my question specifically is what functionality would I need in the user and password classes to be ready for a production environment
$db = new DB;
$link = $db->connect()->getLink();
class DB {
public $connection = array();
public function __construct() {
return $this;
}
public function connect($host=null, $user=null, $pass=null, $database=null) {
$this->connection = new Connection($host, $user, $pass, $database);
$this->connection->connect();
$this->link = $this->connection->getLink();
if ($this->connection->ping()) {
if (!is_null($database)) {
if (!$this->connection->databaseConnect($database)) {
throw new\Exception('Unable to connect to the server.');
}
}
}else{
throw new \Exception('Unable to connect to the server.');
}
return $this;
}
public function getLink() {
return $this->link;
}
}
class Connection {
protected $chost='localhost';
protected $cuser='guest';
protected $cpass='password';
protected $cdatabase='PROFORDABLE';
function __construct($host=null, $user=null, $pass=null, $database=null) {
$host = !is_null($host) ? $host : $this->chost;
$user = !is_null($user) ? $user : $this->cuser;
$password = !is_null($pass) ? $pass : $this->cpass;
$database = !is_null($database) ? $database : $this->cdatabase;
$this->set('host', $host)->set('user', $user)->set('password', $password)->set('database', $database);
return $this;
}
public function connect() {
$link = mysqli_connect($this->host->getHost(), $this->user->getUser(), $this->password->getPassword());
if (!is_object($link)) {
throw new \Exception("An error has occurred while connecting to the server.");
}
$this->link = $link;
}
public function databaseConnect($database) {
if (!mysqli_select_db($this->getLink(), $database)) {
throw new \Exception("Unable to select the database.");
}
}
public function getLink() {
return $this->link;
}
public function ping() {
if (mysqli_ping($this->link)) {
return TRUE;
}
return FALSE;
}
public function set($name, $param) {
if (!isset($name) || !isset($param)) return $this;
$class = __NAMESPACE__.'\\'.ucwords($name);
$this->$name = new $class($param);
return $this;
}
public function get($name) {
$getfunc = 'get'.ucwords($name);
return $this->$name->$getFunc();
}
}
class Host {
public function __construct($host) {
$this->setHost($host);
}
public function setHost($host) {
$this->host = $host;
}
public function getHost() {
return $this->host;
}
}
class User {
public function __construct($user) {
$this->setUser($user);
}
public function setUser($user) {
$this->user = $user;
}
public function getUser() {
return $this->user;
}
}
class Password {
public function __construct($password) {
$this->setPassword($password);
}
public function setPassword($password) {
$this->password = $password;
}
public function getPassword() {
return $this->password;
}
public function sha($value) {
return sha1($value);
}
}
class guestPassword extends Password {
const PASSWORD='password';
public function __construct() {
return PASSWORD;
}
}
class Database {
public function __construct($database) {
$this->setDatabase($database);
}
public function setDatabase($database) {
$this->database = $database;
}
public function getDatabase() {
return $this->database;
}
}
class Query {
}
Usually the DB class just holds the connection as well. It's over-design to make a separate connection class.
I'd worry more about the API of DB than the internals.
any help on keeping track of multiple connections??
class DB {
public $connections = array();
public $threads = array();
public $lastThread=null;
public function __construct() {
$this->connect();
return $this;
}
public function connect($host=null,$user=null,$pass=null,$db=null) {
$connection = new Connection($host, $user, $pass, $db);
if (!$connection->ping() || !$connection->databaseConnect($connection->get('database'))) {
throw new \Exception('ping or database select problem');
}
$threadId = mysqli_thread_id($connection->getLink());
$this->connections[$threadId] = $connection;
$this->threads[] = $threadId;
$this->lastThread = $threadId;
return $this;
}
public function getLink($threadId=null) {
if (is_null($threadId)) {
if (!isset($this->lastThread)
return $this->connections[$this->lastThread]->getLink();
}else{
return $this->connections[$threadId]->getLink();
}
}
}
class Connection {
public $link;
public $host='localhost';
public $user='guest';
public $pass='password';
public $database='PROFORDABLE';
function __construct($host=null, $user=null, $pass=null, $database=null) {
if (!is_null($host)) $this->host = $host;
if (!is_null($user)) $this->user = $user;
if (!is_null($pass)) $this->pass = $pass;
if (!is_null($database)) $this->database = $database;
$this->connect($this->host, $this->user, $this->pass);
$this->databaseConnect($this->database);
return $this;
}
public function connect() {
$link = mysqli_connect($this->host, $this->user, $this->pass);
if (!is_object($link)) {
throw new \Exception("Not object");
}
$this->link = $link;
}
public function databaseConnect($database=null) {
if (!is_null($database)) $this->database = $database;
if (!mysqli_select_db($this->getLink(), $this->database)) {
return FALSE;
}
return TRUE;
}
public function getLink() {
return $this->link;
}
public function ping() {
if (mysqli_ping($this->link)) {
return TRUE;
}
return FALSE;
}
public function set($param, $value) {
$this->$param = $value;
}
public function get($param) {
return $this->$param;
}
}
$db = new DB;
$link = $db->getLink();
$res = mysqli_query($link, 'SELECT TITLE, DESCRIPTION FROM PRO_CONTENT ORDER BY DATE ASC LIMIT 3');
$content=array();
while ($row = mysqli_fetch_assoc($res)) {
$content[] = $row;
}
var_dump($content);
Can anybody please guide me with a sample code to establish a database connection in php using singleton class.
class DatabaseSingleton
{
// [Singleton]
private static $instance = null;
public static function getInstance()
{
if (!self::$instance)
{
self::$instance = new self();
}
return self::$instance;
}
private function __clone(){}
// [/Singleton]
private $connection = null;
private function __construct()
{
$this->connection = mysql_connect('localhost','root','admin');
if ($this->connection)
{
mysql_select_db('my_database');
}
}
//
// crud operations go here.
//
}
$db = DatabaseSingleton::getInstance();
$db->SomeCRUDOperation();
Something like that perhaps? Very basic, but should give you a starting point.
That's how a singleton-pattern looks like:
<?php
class SingletonClass
{
static private $instance = null;
static public function getInstance()
{
if (null === self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
private function __construct(){}
private function __clone(){}
}
$singletonClass = SingletonClass::getInstance();
Now you can put random functions and parameters in there that handle your DB-stuff. I hope that answers your question.
See the manual for an example on how to implement the Singleton pattern: http://www.php.net/manual/en/language.oop5.patterns.php
Then just establish the database connection in your class constructor.
I use something like this:
class DBConn
{
static private $_db = null; // The same PDO will persist from one call to the next
private function __construct() {} // disallow calling the class via new DBConn
private function __clone() {} // disallow cloning the class
/**
* Establishes a PDO connection if one doesn't exist,
* or simply returns the already existing connection.
* #return PDO A working PDO connection
*/
static public function getConnection()
{
if (self::$_db == null) { // No PDO exists yet, so make one and send it back.
try {
self::$_db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
// Use next line for debugging only, remove or comment out before going live.
// echo 'PDO says: ' . $e->getMessage() . '<br />';
// This is all the end user should see if the connection fails.
die('<h1>Sorry. The Database connection is temporarily unavailable.</h1>');
} // end PDO connection try/catch
return self::$_db;
} else { // There is already a PDO, so just send it back.
return self::$_db;
} // end PDO exists if/else
} // end function getConnection
} // end class DBConn
/**
* And you can use it as such in a class
* */
class Post {
public function __construct(){
$this->db = DBConn::getConnection();
}
public function getPosts()
{
try {
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM posts";
foreach ($this->_dbh->query($sql) as $row) {
var_dump($row);
}
/*** close the database connection ***/
$this->_dbh = null;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}
I am using something like below
class Database
{
private $_connection;
private static $_instance; //The single instance
private $_host = "HOST";
private $_username = "USERNAME";
private $_password = "PASSWORd";
private $_database = "DATABASE";
public static function getInstance() {
if(!self::$_instance) { // If no instance then make one
self::$_instance = new self();
}
return self::$_instance;
}
private function __construct() {
$this->_connection = new mysqli($this->_host, $this->_username,
$this->_password, $this->_database);
// Error handling
if(mysqli_connect_error()) {
trigger_error("Failed to conencto to MySQL: " . mysqli_connect_error(),
E_USER_ERROR);
}
}
// Magic method clone is for prevent duplication of connection
private function __clone() { }
public function getConnection() {
return $this->_connection;
}
}
$db = Database::getInstance();
$mysqli = $db->getConnection();
$sql_query = "SELECT foo FROM etc";
$result = $mysqli->query($sql_query);