I created a connection in db.php class like this:
class db
{
public $isConnected;
protected $database;
public function __construct($username, $password, $host, $dbname, $options=array())
{
$this->isConnected = true;
try {
$this->database= new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$this->database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->database->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
$this->isConnected = false;
throw new Exception($e->getMessage());
}
}
public function select($query, $params=array()){
try{
$stmt = $this->database->prepare($query);
$stmt->execute($params);
return $stmt->fetch();
}catch(PDOException $e){
throw new Exception($e->getMessage());
}
}
}
and I am accessing this class in state.php page like this:
<?php
$database = new db("root", "", "localhost", "bhaskar_hindi_dbs", array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$getrows = $database->select("SELECT state_id, state_name FROM state");
foreach($getrows as $row){
?>
but I have multiple pages in my project. Now I need to set this below variable also in db class and make a connection to the constructor according to this.
$host = localhost;
$username = "";
$password ="";
$dbname = "";
$options = "";
Can anyone suggest how to set this variable in the DB class and how to call DB class from state.php page?
add this at the top of your state.php file
require 'db.php';
this if the db.php file in the same directory, if not then
require 'path_to_where_the_db.php_file_is/db.php';
I dont see the issue if you pass them on in the state.php but if you dont want to you can do this:
class db
{
public $isConnected;
protected $database;
private $_dbOptionArray;
const DB_USER = 'root';
const DB_PASS = 'pass';
const DB_HOST = 'host';
const DB_NAME = 'name';
public function __construct($username, $password, $host, $dbname, $options=array())
{
$this->_dbOptionArray = [];//set your options here
$this->isConnected = true;
try {
$this->database= new PDO("mysql:host={self::DB_HOST};dbname={self::DB_NAME};charset=utf8", self::DB_USER, self::DB_PASS, $this->_dbOptionArray);
$this->database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->database->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
$this->isConnected = false;
throw new Exception($e->getMessage());
}
}
public function select($query, $params=array()){
try{
$stmt = $this->database->prepare($query);
$stmt->execute($params);
return $stmt->fetch();
}catch(PDOException $e){
throw new Exception($e->getMessage());
}
}
}
Set parameters by creating a factory.
DatabaseFactory.php
include("db.php");
class DatabaseFactory
{
protected $db;
public function __construct()
{
$this->db = new db("root", "", "localhost", "bhaskar_hindi_dbs", array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
public function getConnection()
{
return $this->db;
}
}
Then you can include DatabaseFactory.php in other pages without having to re-enter the parameters every time. Then use it like this:
include "DatabaseFactory.php";
$DBFactory = new DatabaseFactory();
$Database = $DBFactory->getConnection();
$query = ...; // your query
$Database->select($query);
You can easily change the parameters, reuse on all your pages or change database type this way later down the road if you wished.
You can use another function to extend parent function.
class dbConfig extends db {
private $engine;
private $host;
private $database;
private $user;
private $pass;
public function __construct(){
$this->engine = 'mysql';
$this->host = 'localhost';
$this->database = '';
$this->user = '';
$this->pass = '';
$dns = $this->engine.':dbname='.$this->database.";host=".$this->host;
parent::__construct( $dns, $this->user, $this->pass );
}
}
Related
I'm a beginner looking to learn more about PHP OOP, so there are things I don't know, in the ShowUsers() method, I would like to display all users in the database, but I'm not getting it, because I don't know how to call the connection property. If I've been using encapsulation, it would be easy, but I'm using the connection property as local, and I really don't know how to call this property, how can I call it without using encapsulation?
db.php
<?php
class DbConnect {
private $host = 'localhost';
private $dbname = 'database';
private $username = 'root';
private $password = '';
public function __construct() {
try {
$conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception) {
throw new Exception($exception->getMessage());
}
}
}
main.php
<?php
require_once 'db.php';
class Main extends DbConnect {
public function __construct() {
parent::__construct();
}
public function ShowUsers() {
$sql = "SELECT * FROM users";
$result = parent::__construct()->prepare($sql); //Problem here
$result->execute();
}
}
$object = new Main();
$object->ShowUsers();
Note: I don't want to use encapsulation to make it work, I want to learn how to call the variable without using encapsulation, if possible.
Based on the code above and the comments, I recommend that you declare $conn as protected in your DbConnect class:
<?php
// db.php
class DbConnect {
private $host = 'localhost';
private $dbname = 'database';
private $username = 'root';
private $password = '';
protected $conn;
public function __construct() {
try {
$this->conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception) {
throw new Exception($exception->getMessage());
}
}
}
Then in main.php, you can do:
<?php
// main.php
require_once 'db.php';
class Main extends DbConnect {
public function __construct() {
parent::__construct();
}
public function ShowUsers() {
$sql = "SELECT * FROM users";
$result = $this->conn->prepare($sql);
$result->execute();
}
}
$object = new Main();
$object->ShowUsers();
?>
I am using a config.php file for a simular something, im trying to put my mysql credentials in there to then use them in a different file, but it does not pass the values,
is there any1 that could help me find a solution.
code config.php:
/* Database credentials*/
$dbHost = 'localhost';
$dbName = 'xx';
$dbUsername = 'xx';
$dbWachtwoord = 'xx';
code dbconnect.php:
<?php include 'config.php';
class Database
{
private $host;
private $db_name;
private $username;
private $password;
public $conn;
public function dbConnection()
{
$this->host = $dbHost;
$this->db_name = $dbName;
$this->username = $dbUsername;
$this->password = $dbWachtwoord;
$this->conn = null;
try
{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
Class.user dbconnection:
<?php
require_once('config.php');
require_once('dbconnect.php');
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
Thanks in advance =)
Rather than thinking about it as passing variables, think about it as passing configuration. It is necessary for your Database class to be aware of those configuration options in order for it to be used. In other words: once you create an instance of class Database it should be configured and ready to use, just like any service would.
I strongly suggest you follow the rule of injecting the configuration as a dependency.
Include 'config.php inside your class
public function dbConnection()
{
include 'config.php';
$this->host = $dbHost;
$this->db_name = $dbName;
$this->username = $dbUsername;
$this->password = $dbWachtwoord;
$this->conn = null;
try
{
You can try below code :
config.php
<?php
return [
'dbHost' => 'localhost',
'dbName' => 'xx',
'dbUsername' => 'xx',
'dbWachtwoord' => 'xx',
];
user class
class USER
{
private $conn;
private $config;
public function __construct()
{
$this->config = include "config.php";
$database = new Database(this->config['dbHost'], $this->config['dbUsername'], $this->config['dbWachtwoord'], $this->config['dbName']);
//...
}
//...
}
dbconnect.php
public function dbConnection($dbHost, $dbName, $dbWachtwoord, $dbName)
{
//....
}
I have two files file1.php and database.php. I have a class 'Connection' in database.php file. I am calling this function as passing query to class 'bar'. But I am getting two errors:
1.Notice: Undefined variable: conn... on line 22
2.Fatal error: Cannot access empty property in.. on line 22
These are the codes I am using. Thank you.
file1.php
require_once('database.php');
$c = new Connection();
$c->bar("Select id, firstname, lastname from users");
$c->execute();
database.php
class Connection{
public $conn;
public function __construct()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testing_pdo";
try {
$this->conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (Exception $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
public function bar($sql)
{
$this->conn->prepare($sql);
return $this->conn->execute();
}
}
I finally made it out. I made few changes in both files.
database.php
class Connection{
private $servername = "localhost";
private $username = "root";
private $password = "";
private $dbname = "testing_pdo";
private $conn;
private $error;
private $stmt;
public function __construct()
{
try {
$this->conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$this->conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (Exception $e) {
$this->error = $e->getMessage();
}
}
public function bar($sql)
{
$this->stmt = $this->conn->prepare($sql);
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
file1.php
include ('database.php');
$c = new Connection();
$c->bar("Select id, firstname, lastname from users");
$c->resultset();
I would like to be able to use $conn in different functions inside my page, but because I initialize it in a try/catch, I receive warnings saying the variable is not initialized. How is it possible to declare it, then initialize it in the try/catch ?
This does not work :
global $conn; // or $conn = null; + $this->conn in the next line
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
EDIT :
Here is a new attempt : a warning says container is not initialized :
$res = $container->db()->query($sql);
The new code :
<?php
class Container {
public function db(){
$host = "localhost";
$user = "root";
$pass = "root";
$dbname = "test";
static $conn = null;
if (!isset($conn)){
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'connected to db';
return $conn;
} catch(PDOException $e){
echo $e->getMessage();
}
}
return $conn;
}
}
$container = new Container();
function query($sql){
$t = microtime(true);
try {
$res = $container->db()->query($sql);
if ($res){
printf( "%0.2f ms : %s", (microtime(true) - $t)*1000, $sql);
return;
}
} catch(Exception $e){
echo $e->getMessage();
}
}
query("SELECT * FROM Animal");
Oh yea, your already using a class. Its just needs little redesign.
I would suggest moving query() into the class, but up to you.
Here is a very simplified example;
class Container(){
protected $conn = null;
//I would have a constructor, but up to you
public function __construct(){
$this->db(); //this will set $this->conn
}
public function db(){
try{
$this->conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo $e->getMessage();
}
}
public function getConn(){
if( ! $this->conn ){
$this->db(); //set $this->conn
}
return $this->conn;
}
public function anyFunctionInYouClass(){
//you now have access to the connection opbject with $this->conn
$this->conn->query(); //orwhatever
}
}
function outsideClass(){
$db = new db();
$db->getConn()->query();
}
//OR
//Good if you are using $db in many functions
$db = new db();
function outsideClass($db){
$db->getConn()->query();
}
This is far from a working example but hopefully the idea is clear.
Sidenote: Don't mix static and instance variables
I have a:
class Person
{
public $data;
public function __construct($name) {
$database = new Database;
$database->prepare('SELECT * FROM persons where name = :name');
$database->bindParam(':name', $name);
$database->execute();
$this->data = $database->fetch();
}
}
and i´m creating persons like this:
$jim = new Person('Jim');
$mike = new Person('Mike');
and this is my database class
class Database
{
private $host = 'localhost';
private $user = 'test';
private $pass = '123';
private $dbname = 'test';
private $dbh;
private $error;
private $stmt;
public function __construct()
{
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
catch(PDOException $e){
$this->error = $e->getMessage();
echo $this->error;
}
}
public function prepare($query)
{
$this->stmt = $this->dbh->prepare($query);
}
public function bindParam($key, $val)
{
$this->stmt->bindParam($key, $val);
}
public function execute()
{
$this->stmt->execute();
}
public function fetch()
{
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
}
I´m getting this message very often
Warning: PDO::__construct(): MySQL server has gone away
I want to confirm if this approach is correct. calling the database in the constructor?
How can i know if the created person exists (i mean exist in the database)
should i do something like this?
$jim = new Person('Jim');
if($jim->data) {
echo 'person exists in the db';
}
thank you