Opening DB connection in class method - php

To open a DB connection, I currently use this class method :
function openDB() {
// 1. Create a database connection
$conn = mysqli_connect("x" , "x", "x","x");
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
However, I want to instead use my config file
require("assets/configs/db_config.php");
Obviously this file contains the DB connection information.
How can I do away with
$conn = mysqli_connect("x" , "x", "x","x");
And simply make $conn and make it use DB_Config.php instead?

For you config file return an array of the values you need
return array("host"=>"example.com", "dbname"=>"mydb", "username"=>"dbuser", "password"=>"secret");
Then in your openDb function do this.
function openDB() {
// 1. Create a database connection
$config = include("/path/to/config.php");
$conn = mysqli_connect($config["host"] , $config["username"], $config["password"],$config["dbname"]);
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}

Change
function openDB()
to
function openDB($server, $user, $pass, $dbName)
and pass those variables to mysqli_connect
and pass data from included file.I suppose, you have them in some sort of constants or defines.
Also, it would be good idea to haveDB connection somewhere globally.

Related

PHP Pass variables between PHP files

I have a DB connection in a connection.php file.
With
"require_once"
I include the connection function in a second .php file.
In this second .php file I call another function from an another .php file and I would like to pass the connecction variable to this function.
In main file.php i have this:
require_once("connection.php");
require_once("print.php");
DBconnection(); //Standard connection to a DB
print("connection");
In connection.php i have:
function DBconnection()
{
$connection= new mysqli($host, $user, $password, $database);
if ($connection->connect_errno)
{
echo "$connection->connect_error . ".";
exit();
}
}
Can I pass the connection variable from connection.php to print("connection")?
print("connection") is a function that print something from the DB choosen from connection.php
So you need to create a function, which you have but below is an example:
function functionName($your, $variables, $here)
{
//code
}
Then you would pass variables into it like so...
functionName($your, $variables, $here);
Your function isn't returning a value, so if you want to pass that object back to the calling code, you just need to return it:
function DBconnection()
{
$connection = new mysqli($host, $user, $password, $database);
if ($connection->connect_errno) {
echo $connection->connect_error . " . ";
exit;
}
return $connection;
}
Then, just store the function result to a variable so you can use it later:
require_once("connection.php");
require_once("print.php");
$db = DBconnection(); //Standard connection to a DB

Should objects be created chronologically as class defined?

I am having a strange error while creating objects. While I create an objects in chronological orders as classed defined, it is going on good. But when I change the order or object creation, it gives error.
The classes I am using are as follows:
<?php
class dbClass{
private $dbHost, $dbUser, $dbPass, $dbName, $connection;
function __construct(){
require_once("system/configuration.php");
$this->dbHost = $database_host;
$this->dbUser = $database_username;
$this->dbPass = $database_password;
$this->dbName = $database_name;
}
function __destruct(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
function mysqlConnect(){
$this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("MySQL connection failed!");
mysql_select_db($this->dbName,$this->connection);
}
function mysqlClose(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
}
class siteInfo{
private $wTitle, $wName, $wUrl;
function __construct(){
require_once("system/configuration.php");
$this->wTitle = $website_title;
$this->wName = $website_name;
$this->wUrl = $website_url;
}
function __destruct(){
}
function showInfo($keyword){
if($keyword=="wTitle"){
return $this->wTitle;
}
if($keyword=="wName"){
return $this->wName;
}
if($keyword=="wUrl"){
return $this->wUrl;
}
}
}
?>
The problem is when I create objects in the following order, it is working perfectly:
include("system/systemClass.php");
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
$siteInfo = new siteInfo();
But if I change the order to following
include("system/systemClass.php");
$siteInfo = new siteInfo();
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
It gives error!
Warning: mysql_connect() [function.mysql-connect]: Access denied for user '#####'#'localhost' (using password: NO) in /home/#####/public_html/#####/system/systemClass.php on line 19
MySQL connection failed!
Your problem comes from the unconventional use of a configuration file that is read ONCE, but should be used in all classes.
When you instantiate the dbclass first, the configuration is read, probably variables get assigned, and you use these in the constructor.
After that, instantiating siteinfo will not read that file again, which is less harmful, because you only end up with an empty object that does return a lot of null, but does work.
The other way round, you get a siteinfo object with all the info, but a nonworking dbclass.
My advice: Don't use a configuration file that way.
First step: Remove the require_once - you need that file to be read multiple times.
Second step: Don't read the file in the constructor. Add one or more parameters to the constructor function and pass the values you want to be used from the outside.
Info: You can use PHP code files that configure stuff, but you shouldn't define variables in them that get used outside. This will work equally well:
// configuration.php
return array(
'database_host' => "127.0.0.1",
'database_user' => "root",
// ...
);
// using it:
$config = require('configuration.php'); // the variable now has the returned array

Handling my connection variable for login script use [duplicate]

This question already has answers here:
mysqli_query() expects parameter 1 to be mysqli, object given
(3 answers)
Closed 2 years ago.
Currently I am using
$con=mysqli_connect("x","x","x","x");
to handle my database connection on the login script. However, I'm trying to transition this to an OOP style approach such as
$con = new dbclass();
$con->openDB();`
I'm not having any luck with this though.
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 103
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 104
Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 109
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\c\login.php on line 111
Acess denied, wrong username or password?
This is the method I'm using to do this.
function openDB() {
$config = include("/assets/configs/db_config.php");
$conn = mysqli_connect($config["host"] , $config["username"], $config["password"],$config["dbname"]);
// 1. Create a database connection
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
Can anyone make any suggestions. Do I need to use mysqli_connect() somewhere within my method. Or even better, within my db_config file :
<?php
return array("host"=>"x", "dbname"=>"x", "username"=>"x", "password"=>"x");
mysqli_report(MYSQLI_REPORT_ERROR);
?>
include() does not cause the variables defined therein to become an array - they are automatically imported into the scope in which you are calling the function. Since you are not defining $config inside the include file, you're never accessing the array.
So, $config = include('your_script.php') doesn't do what you likely think it does.
You should update the function as follows (and change the array definition inside db_config.php to define $host, $username, $password and $dbname).
function openDB()
{
include("/assets/configs/db_config.php");
$conn = mysqli_connect($host, $username, $password, $dbname);
// 1. Create a database connection
if(!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
That having been said, this isn't the best way to handle DB connections in an OOP application. If you need to move the config file, you have to update the Database class. It would be better to pass in the variables to your openDB() function as parameters, and then retrieve them from a config script in your controller somewhere.
For example, the following is much better practice:
function openDB($username, $password, $dbname, $host = 'localhost')
{
$conn = mysqli_connect($host, $username, $password, $dbname);
if(!$conn)
{
$this->error_msg = 'connection error could not connect to the database!';
return false;
}
$this->conn = $conn;
return true;
}
Try using this only initiate like $db = new db(); no need to open db it will already connect
EDIT
here is code of db_config.php
$db_host = 'localhost';
$db_user = 'root';
$db_password = '';
$db_name = 'bs_admin';
class db
{
public $dbh;
public $error;
public $error_msg;
// Create a database connection for use by all functions in this class
function __construct()
{
require(dirname(dirname(__FILE__)) . '/config/db_config.php');
if($this->dbh = mysqli_connect($db_host, $db_user, $db_password, $db_name))
{
// Set every possible option to utf-8
mysqli_query($this->dbh, 'SET NAMES "utf8"');
mysqli_query($this->dbh, 'SET CHARACTER SET "utf8"');
mysqli_query($this->dbh, 'SET character_set_results = "utf8",' .
'character_set_client = "utf8", character_set_connection = "utf8",' .
'character_set_database = "utf8", character_set_server = "utf8"');
}
else
{
// Log an error if the connection fails
$this->error = true;
$this->error_msg = 'Unable to connect to DB';
}
// Add a row to any table
public function insert($table,$field_values)
{
$query = 'INSERT INTO ' . $table . ' SET ' . $field_values;
mysqli_query($this->dbh,$query);
}
}

Is it possible to use a $myqli->real_escape_string in side of a custom class with out loading the connection again?

Is it possible to use a $myqli->real_escape_string in side of a custom class with out loading the connection again? Take the code below. $mysqli is created twice is it possible to use the connection already established?
<?php
$mysqli = new mysqli('127.0.0.1','user','password','table');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit('connect failed!');
}
// connected
class save {
public $datatosave = '';
function __construct ($new) {
$mysqli = new mysqli('127.0.0.1','user','password','table');
$this->datatosave = $mysqli->real_escape_string($new);
}
}
$infromation = " ' test";
$newinfo = new save ($infromation);
echo $newinfo->datatosave;
$mysqli->close();
?>\
should still output \' test
Since you are catching the connection with the $mysqli variable, just pass that into your __construct function when you initialize the class.
class save {
public $datatosave = '';
function __construct ($new, $mysqli_attr) {
$this->datatosave = $mysqli_attr->real_escape_string($new);
}
}
$infromation = " ' test";
$newinfo = new save ($infromation, $mysqli);
echo $newinfo->datatosave;

php pdo connection scope

Hey guys I have a connection class I found for pdo. I am calling the connection method on the page that the file is included on. The problem is that within functions the $conn variable is not defined even though I stated the method was public, and I was wondering if anyone had an elegant solution other then using global in every function. Any suggestions are greatly appreciated.
CONNECTION
class PDOConnectionFactory{
// receives the connection
public $con = null;
// swich database?
public $dbType = "mysql";
// connection parameters
// when it will not be necessary leaves blank only with the double quotations marks ""
public $host = "localhost";
public $user = "user";
public $senha = "password";
public $db = "database";
// arrow the persistence of the connection
public $persistent = false;
// new PDOConnectionFactory( true ) <--- persistent connection
// new PDOConnectionFactory() <--- no persistent connection
public function PDOConnectionFactory( $persistent=false ){
// it verifies the persistence of the connection
if( $persistent != false){ $this->persistent = true; }
}
public function getConnection(){
try{
// it carries through the connection
$this->con = new PDO($this->dbType.":host=".$this->host.";dbname=".$this->db, $this->user, $this->senha,
array( PDO::ATTR_PERSISTENT => $this->persistent ) );
// carried through successfully, it returns connected
return $this->con;
// in case that an error occurs, it returns the error;
}catch ( PDOException $ex ){ echo "We are currently experiencing technical difficulties. We have a bunch of monkies working really hard to fix the problem. Check back soon: ".$ex->getMessage(); }
}
// close connection
public function Close(){
if( $this->con != null )
$this->con = null;
}
}
PAGE USED ON
include("includes/connection.php");
$db = new PDOConnectionFactory();
$conn = $db->getConnection();
function test(){
try{
$sql = 'SELECT * FROM topic';
$stmt = $conn->prepare($sql);
$result=$stmt->execute();
}
catch(PDOException $e){ echo $e->getMessage(); }
}
test();
You can declarate database class where you carrying conn pdo class, then you don't must duplicates instaces of this. And all database operations you can doing by this class. I mean my answer is what you searching.
But i see, you using only PDO hadle class in Product Factory pattern. You can use normal full database support class under PDO (includes queryies execution from one function) and without this design pattern when you don't want to use many database connectors engines.

Categories