i have a question about php.
I was wondering how can i add this code to a new object so i can later just add it to existing code and use it.
<?php
$mysqli = new mysqli("localhost", "root", "", "kooliasi");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
printf ("System status: %s\n", $mysqli->stat());
$mysqli->close();
?>
Thanks !
Make a class for the connection:
class Database{
private static $link = null ;
public static function getConnection ( ) {
if (self :: $link) {
return self :: $link;
}
$dsn = "mysql:dbname=social_network;host=localhost";
$user = "user";
$password = "pass";
self :: $link = new PDO($dsn, $user, $password); //OR mysqli - matter of preference
return self :: $link;
}
}
Then you can get the connection like this:
Database::getConnection();
This is a Singleton Pattern. You could use this if you like, but it is hard to scale - However, I think it will be fine for your needs. It takes a lot of load off your database.
There is a php.ini setting for prepending a file to every script -> http://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
You can create a db class where you can keep the connection handle. Add functions to the class as needed. For example
class db{
private $link;
public function __construct(){
$this->link = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,DB_NAME);
}
public function __destruct() {
mysqli_close($this->link);
}
public function query($q){
... add code here for the query
}
}
Then to use the class you call:
$db = new db();
$db->query($parameters_you_want_to_pass);
Related
I want to be able to call a function which connects to my database, without creating multiple objects, including or having to write the same construct in each class. I Basically want to call a construct function in other classes.
like this below.
class Database{
public function __construct(){
$this->conn = new mysqli("host", "user", "password", "db");
// Check connection
if (!$this->conn) {
die("Connection failed: ".mysqli_connect_error());
}
}
}
class User{
// call Database->__construct();
}
class OtherClass{
// call Database->__construct();
}
ofcourse this isn't the way to go but i don't really know what would be a viable way.
I thought maybe this would work. but it doesn't
Making a new Database object in class to construct a connection
class Database{
public function __construct(){
$this->conn = new mysqli("host", "user", "password", "db");
// Check connection
if (!$this->conn) {
die("Connection failed: ".mysqli_connect_error());
}
}
}
class User{
$conn = new Database();
}
Dependecy injection or constructor injection seems like a nice solution. But i don't know if it's made for something like this and how to apply it.
class Database{
public function connection(){
$this->conn = new mysqli("host", "user", "password", "db");
// Check connection
if (!$this->conn) {
die("Connection failed: ".mysqli_connect_error());
}
}
}
class User{
private $db;
public function __construct(Database $conn){
$this->db = $conn;
}
}
Here what i am doing for connection
class DBConnection{
protected static $db;
private function __construct() {
try {
self::$db = new PDO( 'mysql:host=localhost;dbname=db_abc', 'root', '' );
//self::$db = new PDO( 'mysql:host=localhost;dbname=db_phonebook', 'root', 'QAZwsx2016!' );
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e) {
echo "Connection Error: " . $e->getMessage();
}
}
public static function getInstance() {
if (!self::$db) {
new DBConnection();
}
return self::$db;
}
public function __destruct() {
$db=NULL;
}
}
And here how I am using to another model class
class User{
private $db;
public function __construct() {
$this->db = DBConnection::getInstance();
}
public function getUsers(){
//....................
//....................
//$sql =
$query = $this->db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$query->execute();
$customers = $query->fetchAll();
//return .........
}
If you want pure OOP way, please look into the factory methods, and look facade design pattern, Its all about how you gonna achieve some this.
This one is my way (simple way) but to architecture better see the different design patterns.
One useful article here link
and
Design Patterns with PHP-The right way link
I'm trying to use db connection parameter inside function, i tried to global it but it does not working.
$host = 'localhost';
$username = 'b**s';
$password = '1******m';
$dbname = 'b*********e';
$connection = new mysqli($host, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
When i'm executing the query it returning error, becuase i didn't pass $connection parameter inside function.
function insertData(){
{......}
if($connection->query($sql)){
$response['success'] = 'User record successfully added!';
}
}
Can anyone guide me what is best to use without passing parameter inside function. I would like to appreciate if someone guide me.
In your function you should do something like
global $connection;
then use it below like
if($connection->query($sql)){
$response['success'] = 'User record successfully added!';
}
This is well documented in manual, i suggest you go have a look.
Create a database class and access it by object
<?php
class Database {
private static $db;
private $connection;
private function __construct() {
$this->connection = new MySQLi(/* credentials */);
}
function __destruct() {
$this->connection->close();
}
public static function getConnection() {
if (self::$db == null) {
self::$db = new Database();
}
return self::$db->connection;
}
}
?>
Then just use $db = Database::getConnection(); wherever I need it.
DbConnect.php
<?php
/**
* Handling database connection
*/
include_once ('Config.php');
class DbConnect {
private $conn;
function __construct() {
}
/**
* Establishing database connection
* #return database connection handler
*/
function connect() {
// Connecting to mysql database
$this->conn = new mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
// returing connection resource
return $this->conn;
}
}
class DbHandler {
private $conn;
function __construct() {
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}}
?>
config.php
<?php
/**
* Database configuration
*/
define('DB_USERNAME', 'medma');
define('DB_PASSWORD', 'medma');
define('DB_HOST', 'localhost');
define('DB_NAME', 'medma_sameer');
/**
* MSG91 configuration
*/
define('MSG91_AUTH_KEY', "130558AmTMgKzL582187bb");
// sender id should 6 character long
define('MSG91_SENDER_ID', 'MEDMA1');
define('USER_CREATED_SUCCESSFULLY', 0);
define('USER_CREATE_FAILED', 1);
define('USER_ALREADY_EXISTED', 2);
?>
Please tell me what could be the problem though i have posted before Not able to hit api to verify otp ( Used Volley)
but when i started testing each php file on my localhost folder where i have mounted i got stuck with the very initial step which is database connection the code i wrote above doesn't show anything except blank
There are 2 problems here that could cause the page to be blank:
The first is that you don't actually output anything in your script, at least not in the code you have posted.
The bigger problem is that this is probably wrong as you don't seem to be inside a method / class:
$db = new DbConnect();
$this->conn = $db->connect();
$this is defined in the scope of a method so using it like you are doing would lead to a fatal error:
Fatal error: Using $this when not in object context in ...
As a side-note: If you want to show the contents of a variable, you should use var_dump() instead of echo because the last only gives any meaningfull output for numbers and strings; not for database connections.
First of all you bad invoke a connection here
$db = new DbConnect();
$this->conn = $db->connect();
You can not access property conn in this scope (outside of a class) this way
You can do this using $db->conn. However in this situation you can't access it aswell as it is a private
If you would like to do this using your class you can try
$db = new DbConnect();
$conn = $db->connect();
and under $conn u have a db connection.
#edit:
Maybe try use this
<?php
include_once ('Config.php');
/**
* Handling database connection
*/
class DbConnect {
private static $_instance; //The single instance
private $_conn;
public static function getInstance() {
if(!self::$_instance) { // If no instance then make one
self::$_instance = new self();
}
return self::$_instance;
}
private function __construct() {
// Connecting to mysql database
$this->_conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
}
// Get connection
function getConnection() {
return $this->_conn;
}
}
To make a connection to database you can do that
$db = DbConnect::getInstance();
$conn = $db->getConnection();
$query= "SELECT foo FROM .....";
$result = $conn->query($query);
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.
Procedural PHP works for me, but when I try to code like I do in objective C I cannot seem to get the functions to work. I think it has something to do with my variable scope and the functions not returning any values. Where am I going wrong with my code here?
<?php
require_once("constants.php");
class Main {
public $menu;
public $connection;
function connectToDatabase() {
//connect to database & check connection
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
}
function queryDatabase($select, $from) {
$result = mysqli_query($connection,"SELECT $select FROM $from");
}
function closeDatabaseConnection() {
mysqli_close($connection);
}
function displayMenu() {
//connect to database & check connection
connectToDatabase();
//get menu data
queryDatabase(*, pages);
//construct menu data
echo '<ul class="mainNavigation">';
while($row = mysqli_fetch_array($result))
{
echo '<li><a href="' . $row['filename'] . '.php">';
echo $row['menu_name'];
echo '</a></li>';
}
echo '</ul>';
//close connection
closeDatabaseConnection();
}
function displayFooter() {
}
function getUser() {
}
function userLogIn() {
}
}
?>
if you want to use a method or variable inside it's own class, you have to put $this-> in front of it. For exmaple this connectToDatabase(); would become this $this->connectToDatabase();
Instead of using $connection, you should use $this->connection, and run it like so:
$Db = new Main();
$Db->connectToDatabase();
If you want to access a property inside a method, make sure to reference it with $this->prop, rather than just $prop. If the method is static, use self::prop instead.
$this refers to the current instantiation of the class. You would use the scope resolution operator (::) if the method/property is static (DBConnection::connection DBConnection::connectToDatabase())/
Also, I'd rename class 'Main' to something else like DBConnection (PHP doesn't use main methods like C does), then:
$Db = new DBConnection();
$Db->connectToDatabase();
Because in PHP, although you can have one class in one PHP file named connection.php, with a class of Main, if you have another class following the same pattern, then you'll have two Main classes.
There are all kinds of things wrong with this class, so I will focus on a few key points and maybe you can fix it from there without us having a total rewrite
First, consider this:
public $connection;
function connectToDatabase() {
//connect to database & check connection
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
}
You declare a class variable $connection, which is ok. But in your function you assign a local variable instead of accessing the class variable. From within a class, you would call all class members using $this. So the function should be:
function connectToDatabase() {
//connect to database & check connection
$this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
}
Now, other methods attempt to call functions but they need to do the same thing:
function displayMenu() {
//connect to database & check connection
// this should just check to see if $connection is populated. if not then call this method
$this->connectToDatabase();
And this method is not accessing the class var for connection:
function queryDatabase($select, $from) {
$result = mysqli_query($this->connection,"SELECT $select FROM $from");
}
those few examples should give you the basic idea of accessing class methods and variables. You can ask specific questions and we may update, but for now this should get you going.
Here is a mysqli connection class that I use regularly. It might not answer your question but you can study it and it should help you better understand the concept. It did for me anyway.
class DBConnection
{
protected $mysqli;
private $db_host='localhost';
private $db_name='';
private $db_username='';
private $db_password='';
public function __construct() {
$this->mysqli = new mysqli($this->db_host,$this->db_username,
$this->db_password, $this->db_name) or die($this->mysqli->error);
return $this->mysqli;
}
public function getLink() {
return $this->mysqli;
}
public function query($query) {
return $this->mysqli->query($query);
}
public function real_escape_string($str) {
return $this->mysqli->real_escape_string($str);
}
function __destruct(){
$this->mysqli->close();
}
}
And then when you need to connect to the database in another class call it in the construct function like so:
public function __construct(DBConnection $mysqli) {
$this->mysqli = $mysqli->getLink();
}