When building dynamic websites I use a php include to make my connections to the database. The included file is very basic:
mysql_connect($hostname = 'host', $username = 'user', $password = 'password');
mysql_select_db('database');
This works fine.
In some places I use an AJAX system to create drag-and-drop reordering of database records which updates the database at the same time, it is adapted from something I found on the internet. This uses its own connection code:
class SortableExample {
protected $conn;
protected $user = 'user';
protected $pass = 'password';
protected $dbname = 'database';
protected $host = 'host';
public function __construct() {
$this->conn = mysql_connect($this->host, $this->user, $this->pass);
mysql_select_db($this->dbname,$this->conn);
}
This also woks fine.
What it means, however, is that I have to add the username, password, host and database to two separate files. Sometimes the second one is forgotten and causes the website to fail.
My question is, how can I either combine both connection files into one, OR how can I get the second block of code to accept external variables so that I only have to enter the actual values in one place?
Your last question is easy.
db.config.php
$host = '';
$user = '';
$pass = '';
$db = '';
db.plain.php
include 'db.config.php';
$conn = mysql_connect($host, $user, $pass);
mysql_select_db($db,$conn);
db.class.php
include 'db.config.php';
class SortableExample
{
protected $conn;
public function __construct()
{
global $host, $user, $pass, $db;
$this->conn = mysql_connect($host, $user, $pass);
mysql_select_db($db,$this->conn);
}
}
You can simply put the database connection code in another file and included that everywhere you need it.
Create a single entry point for your database connection.
Use a Singleton with lazy instantiation for that:
class ConnectionProvider {
protected $conn;
protected $user = 'user';
protected $pass = 'password';
protected $dbname = 'database';
protected $host = 'host';
private static $__instance;
private function __construct() {
$this->conn = mysql_connect($this->host, $this->user, $this->pass);
mysql_select_db($this->dbname,$this->conn);
}
public static function getInstance() {
if ( self::$__instance == null) {
self::$__instance = new ConnectionProvider();
}
return self::$__instance;
}
public function getConnection() {
return $this->conn;
}
}
And then, from your code
ConnectionProvider::getInstance()->getConnection();
to use the connection wherever you need it.
SortableExample would thus become:
class SortableExample {
protected $conn;
public function __construct() {
$this->conn = ConnectionProvider::getInstance()->getConnection();
}
...
}
Related
Having trouble understanding classes and inheritance:
core.php:
$servername = "****";
$database = "****";
$username = "****";
$password = "****";
try {
$pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
class Database {
protected $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
}
}
class User extends Database {
private $ip;
private $sessionId;
public function __construct($ip, $sessionId) {
$this->ip = $ip;
$this->sessionId = $sessionId;
}
public function getSessionInfo () {
$stmt = $this->pdo->prepare(".."); <-- error here
....
}
}
When calling:
require_once 'api/core.php';
$database = new Database($pdo);
$user = new User($_SERVER['REMOTE_ADDR'], $_SESSION['info']['id']);
In this contest $database, and $user variables are not related to each other:
require_once 'api/core.php';
$database = new Database($pdo);
$user = new User($_SERVER['REMOTE_ADDR'], $_SESSION['info']['id']);
Thus, calling prepare() on $user won't work.
You need a mechanism, at least like this , although not a good practice to assign Database to a User:
$user->setDatabase($database);
Instead create a static Database object, initiate it before User initiation, and call it statically within User object, or any other object, make it available for all objects.
A quick fix would look like this, where User doesn't extend Database, because it's wrong. User is not a Database.
$database = new Database();
$user = new User();
$user->setDatabase($database); //sets $db variable inside User
//User.php
namespace MyApp;
class User{
private Database $db;
public function setDatabase($db){
$this->db = $db;
}
public function doSomething(){
$this->db->getPdo()->prepare('..');
}
}
//Database.php
namespace MyApp;
class Database{
private $pdo; //returns PDO object
function __construct(){
//create pdo connection
$this->pdo = ..
}
function getPdo(){
return $this->pdo;
}
}
Database should be injected to objects or used by objects, you shouldn't be extending Database just to have it. If you want to do it properly, in an object-oriented way.
Remember PHP doesn't allow multiple inheritances by extend. Tomorrow, you might want to have a Person class that every User will extend, but since you did it wrong in the beginning, and wasting precious extend on Database, it won't be possible. And by not having a control of how many database instances you have created, you will run into issues. You need to know for sure that you have only a single connection object for one database, if of course the opposite is a must - which in your case I doubt.
Of course this will change if you have multiple database requirements, and more sophisticated app structure.
You are receiving this error because User Instance has pdo empty. try this code
$servername = "****";
$database = "****";
$username = "****";
$password = "****";
try {
$pdo = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
class Database {
protected $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
}
}
class User extends Database {
private $ip;
private $sessionId;
public function __construct($pdo, $ip, $sessionId) {\
parent::__construct($pdo)
$this->ip = $ip;
$this->sessionId = $sessionId;
}
public function getSessionInfo () {
$stmt = $this->pdo->prepare("..");
....
}
}
then
require_once 'api/core.php';
$user = new User($pdo, $_SERVER['REMOTE_ADDR'], $_SESSION['info']['id']);
hope it helps.
So, I'm in the middle of writing a web application for one of my clients, and I've decided to keep the database connection in a class. The following code is what I have:
class databaseConnection {
private $hostname = 'hn.app.dev';
private $username = 'root';
private $password = '';
private $database = 'hn_app_dev';
public function connect() {
$host = mysqli_connect($this->hostname, $this->username, $this->password);
if ($host) {
$connection = mysqli_select_db($host, $this->database);
if (!$connection) {
die('An error occured while trying to connect to the database.');
}
return $connection;
}
}
}
I am using the standard PHP function of mysqli_query to send queries to the database. I am using the following to send queries to the database:
function fetch_from_db($query) {
$connection = new databaseConnection();
$query = mysqli_query($connection->$connection, 'QUERY');
}
I'm new to using classes in my code. I'm still learning, as we all are. I've checked about but cannot find a fix for my issue. I know what the issue is: it's an issue with the class being an object, and something to do with fetching the returned $connection variable from it.
How can I fix this issue so that I can connect correctly to my database? Also, could anyone point me in the direction of some documentation that I could learn the fix so I can tackle this in future.
Thank you!
There are a lot of different ways you could write a object to handle connections and queries to the database.
What matters most is what your trying to achieve.
I would think these would be a few features you would like to have.
Single Connection
Runs SQL and returns mysqli results.
Access to the connection for escaping values.
It looks like you want to store your credentials within the object it self. ( I would suggest passing these in as a value in __construct()
These are a few basic features, that could easily be expanded apon.
class databaseConnection {
//private $hostname = 'hn.app.dev';
//private $username = 'root';
//private $password = '';
//private $database = 'hn_app_dev';
private $connection; // this is where the object will store the connection for other methods to access it
public function __construct($host, $username, $password, $database)
//public function connect() {
$this->connection = mysqli_connect($host, $username, $password);
if ($host) {
$this->connection->select_db($database);
if (!$this->connection) {
die('An error occured while trying to connect to the database.');
}
return $connection;
}
}
// this is so databaseConnection $db can access the connection for escaping MySQLi SQL
public function connection(){
return $this->connection;
}
function fetch_from_db($query) {
//$connection = new databaseConnection(); // I don't believe you really want to create a instance of this object inside of itself
//$query = mysqli_query($connection->$connection, 'QUERY');
$query = $this->connection->query($query); // we will use the object oriented style instead of the above procedural line
return $query; // return the results to the $results var in the bottom example
}
// this is a magic function that is called when the object is destroyed, so we will close the connection to avoid to many connections
function __destruct(){
$this->connection()->close();
}
}
// make a new datbaseConnection class with specific credentials
$db = new databaseConnection('localhost', 'someuser', 'somepass', 'somedb');
$sql = 'SELECT * FROM tableName LIMIT 100';
// call the fetch_from_db function from the new databaseConnection $db
$results = $db->fetch_from_db($sql);
// print the results
while($result = $results->fetch_assoc()){
print_r($result); // print_r on each row selected from db
}
You can learn more about OOP and PHP Objects in the Manual and there are many tutorials available online about specifically classes to manage database connections and queries.
http://php.net/manual/en/language.oop5.php
Hope this helps!
If you're going to keep it in a class, you never call the connect() function. But if you want it connected when you initiate the class, change the connect() function to __construct() and remove the return and assign it to a public variable.
class databaseConnection {
private $hostname = 'hn.app.dev';
private $username = 'root';
private $password = '';
private $database = 'hn_app_dev';
public $connection;
public function __construct() {
$host = mysqli_connect($this->hostname, $this->username, $this->password);
if ($host) {
$connection = mysqli_select_db($host, $this->database);
if (!$connection) {
die('An error occured while trying to connect to the database.');
}
$this->connection = $host;
}
}
}
After that, you can get the database connection in your function like:
function fetch_from_db($query) {
$connection = new databaseConnection();
$query = mysqli_query($connection->connection, 'QUERY');
}
Now, after having said all that, you don't want to create a new instance in every function to access the database. So possibly making it static and create an init() function of sorts so it takes less memory in the overall application.
For class documentation PHP's Classes/Objects page will help. Specifically the 'Examples' link.
<?php
class databaseConnection {
private $hostname = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'onlinylh_sggsfaculty';
public function connect() {
$host = mysqli_connect($this->hostname, $this->username, $this->password,$this->database);
if ($host) {
return $host;
}
else{
echo "Error";
}
}
}
function fetch_from_db($query) {
$conn = new databaseConnection();
$r = mysqli_query($conn->connect(), $query);
}
fetch_from_db()
?>
This Worked For me.
In JSP, if I want to connect to the database, I would create a Java class called DBManager with the following code:
public class DBManager {
private final static String DB_URL = "jdbc:mysql://localhost:3306/mydb";
private final static String DB_USERNAME = "root";
private final static String DB_PASSWORD = "root";
public static Connection conn = null;
private static Statement stmt = null;
/**
* Tests connection with the database by getting connection using the
* database url and username and password. And creates a dumb statement and
* closes it to make sure everything is working fine.
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
stmt = conn.createStatement();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now, I can easily do something like:
PreparedStatement pstmt = DBManager.conn.prepareStatement("SELECT * FROM USER");
I'm learning PHP on my own and "most" of the online tutorials actually don't teach how to do stuff the right way.
They all do it in the traditional way in each page they need a connection:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Which is wrong because say you want to change your password? Then, you have to change it in each and every page that you used that password.
My question: how can I do something equivalent/similar to that Java class in PHP?
EDIT:
<?php
class DBManager {
public static $conn = null;
private static $hostname = "localhost";
private static $username = "root";
private static $password = "root";
private static $dbname = "tutorme";
protected function __construct() {
try {
DBManager::$conn = new PDO("mysql:host=localhost;dbname=tutorme", DBManager::$username, DBManager::$password);
DBManager::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
public static function getInstance() {
if (null === DBManager::$conn) {
DBManager::$conn = new DBManager();
}
return DBManager::$conn;
}
}
?>
I searched a little and came up with the above code. However, now when I call
$stmt = DBManager::getInstance()->prepare("INSERT INTO SUBJECT (SubjectTitle, SubjectName) VALUES (:subject,:subj)");
I get an error that there's no function in DBManager called prepare()
which means that my DBManager::getInstance is returning a DBManager object instead of PDO conn object
You have one obvious mistake:
DBManager::$conn = new DBManager();
You don't want that!
Just call new DBManager() and the $conn var will be initiliazed!
And also here are some minor changes,
<?php
class DBManager {
public static $conn = null;
private static $hostname = "localhost";
private static $username = "root";
private static $password = "root";
private static $dbname = "tutorme";
private function __construct() {
try { // why not using $hostname and $dbname?!
DBManager::$conn = new PDO("mysql:host=" . DBManager::$hostname . ";dbname=" .DBManager::$dbname, DBManager::$username, DBManager::$password);
DBManager::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
// getConnection() is a better naming of the function
public static function getConnection() {
if (is_null(DBManager::$conn)) {
new DBManager();
}
// now $conn is initialized
return DBManager::$conn;
}
}
?>
make a class just like what's in java and let's call it database.php
in the file u want to do something
include 'database.php';
.... your code .....
tip: look for "autoload"
is that what you want?
you can start off with this
class Database{
function __construct(){
$this->host = HOST;
$this->user = DB_USER;
$this->pass = DB_PASS;
$this->db = DATABASE;
$this->con = $this->connect();
}
function connect(){
$q = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
if($q) return $q; die("Couldn't Connect to Database");
}
}
other file like so for example
include 'Database.php';
$db = new Database();
mysqli_query($db->con, "QUERY_HERE");
I want to ask whether is good practice to have single instance of database connection or declare new every times when we needed? I have this two designs shown in below:
This is database class:
<?php
class Database extends PDO {
//Variable declaration
private $host = "localhost";
private $passwd = "";
private $username = "root";
private $dbname = "";
//Connect to DB when the class construct
public function __construct($host=NULL, $dbname=NULL, $username=NULL, $passwd=NULL) {
if(isset($host) && !empty($host)) {
$this->host = $host;
}
if(isset($dbname) && !empty($dbname)) {
$this->dbname = $dbname;
}
if(isset($username) && !empty($username)) {
$this->username = $username;
}
if(isset($passwd) && !empty($passwd)) {
$this->passwd = $passwd;
}
parent::__construct("mysql:dbname=$this->dbname;host=$this->host", $this->username, $this->passwd, NULL);
parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
parent::setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
}
?>
Method 1 : Dependency Injection
<?php
class User {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
//Some update and insert below here
}
class Employee {
private $db;
public function __construct(Database $db) {
$this->db = $db;
}
//Some update and insert below here
}
?>
So, I will do this when I want to use the classes:
<?php
$db = new Database();
$user = new User($db);
$user->update($id,$data);
$emp = new Employee($db);
$emp->delete($id);
?>
or the other ways?
Method 2:
<?php
class User {
private $db;
public function __construct() {
$this->db = new Database();
}
//Some update and insert below here
}
class Employee {
private $db;
public function __construct() {
$this->db = new Database();
}
//Some update and insert below here
}
?>
and when I want to use it I will:
<?php
$user = new User();
$user->update($id,$data);
$emp = new Employee();
$emp->delete($id);
?>
Which method is preferable or better? Offer an explanation if possible.
Clearly the dependency injection method is better because it avoids creating multiple connections to the same database.
The problem you will face though is to inject the $db object in every constructors of your class. That's where Dependency injection containers can help you. Their role is to handle creating objects (and thus passing the dependencies in the constructors).
Have a look at this article: Understanding dependency injection which shows an example using dependency injection with a container.
Personally I usually like to have something like this for my applications, named sql.php and required on the top of each page. I really like this approach because it makes it really easy to make changes to any of the credentials or adding a new variable with a different table name in it. Helps with version control also.
// Vars
$host = "localhost"; // Host name
$username = "blah"; // Mysql username
$password = "999999"; // Mysql password
$db_name = "db"; // Database name
$main_table = "table11"; // Main CONTENT Storage Table Name
// Connect to server and select database.
mysql_connect($host, $username, $password, $db_name)or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
I'm currently writing my first PHP application using OOP and PDO. In doing so I'm working on a connection class so that I can initiate a database connection when needed. I believe the terms for the way I am doing it is dependency injection.
I currently have an error when trying to access the connection.
This is my connection class:
class db{
private $host = '';
private $dbname = '';
private $username = '';
private $password ='';
public $con = '';
function __construct(){
$this->connect();
}
function connect(){
try{
$this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'We have a problem!';
}
}
}
And this is how I am trying to call it inside of other classes.
private $con;
public function __construct(db $con) {
$this->con = $con;
}
However this is the error I receive when trying to run it.
Catchable fatal error: Argument 1 passed to users::__construct() must be an instance of db, none given.
Any advice on what I am doing incorrectly would be much appreciated.
You will need to first create your DB instance and pass it to the constructor of your 'Other' class
$db = new DB();
$class = new OtherClass($db);
Apart from that, there are other issues:
The DB class constructor did not assign values to the database name, user and password etc. One way of doing it is to pass those settings to the constructor of DB and assign the values to the private properties.
class DB{
private $host = '';
private $dbname = '';
private $username = '';
private $password ='';
public $con = '';
function __construct($host, $dbname, $username, $password){
$this->host = $host;
$this->dbname = $dbname;
$this->username = $username;
$this->password = $password;
$this->connect();
}
function connect(){
try{
$this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'We have a problem!';
}
}
}