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)
{
//....
}
Related
I've got two files dbconnect.php and config.php
dbconnect.php
<?php
class connect{
public function __construct(){
$config = require_once __DIR__ . 'config.php';
}
private $dbhost = $config['host'];
private $dbuser = $config['username'];
private $dbpass = $config['pass'];
private $dbname = $config['dbname'];
public function startConn(){
$this->DBcon = null;
try{
$this->DBcon = new PDO("mysql:host=".$this->dbhost.";dbname=".$this->dbname, $this->dbuser, $this->dbpass);
}catch(Exception $e){
echo "error connecting:";
}
return $this->DBcon;
}
}
?>
config.php
<?php
/**
* Contains all configurations
*
*/
return [
'dbname' => 'user',
'pass' => '#user.intern1',
'username' => 'user1',
'host' => 'localhost',
];
?>
in my dbconnect.php file;
how do I include variables from my config.php into the class connect
If I do it the following way above;
it yells at me and gives me Fatal error:
"Parse error: syntax error, unexpected '$config' (T_VARIABLE) in C:\xampp\htdocs\hngfun\profile\adeojoemmanuel\php-handler\dbconfig.php on line 8"
I'm taking a guess here. But I can clearly see that you are setting $config as a local variable in the constructor. That means it is not available once you leave the constructor.
<?php
class connect{
public function __construct(){
$config = require_once __DIR__ . 'config.php';
$this->dbhost = $config['host'];
$this->dbuser = $config['username'];
$this->dbpass = $config['pass'];
$this->dbname = $config['dbname'];
}
private $dbhost ;
private $dbuser ;
private $dbpass ;
private $dbname ;
public function startConn(){
$this->DBcon = null;
try{
$this->DBcon = new PDO("mysql:host=".$this->dbhost.";dbname=".$this->dbname, $this->dbuser, $this->dbpass);
}catch(Exception $e){
echo "error connecting:";
}
return $this->DBcon;
}
}
Declared properties like private $dbhost cannot be assigned values that are dependent on runtime data, such as $config['host'];
Quoting from the PHP Docs:
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
The solution, assign the values in your constructor:
class connect{
public function __construct(){
$config = require_once __DIR__ . 'config.php';
private $this->dbhost = $config['host'];
private $this->dbuser = $config['username'];
private $this->dbpass = $config['pass'];
private $this->dbname = $config['dbname'];
}
private $dbhost;
private $dbuser;
private $dbpass;
private $dbname;
public function startConn(){
$this->DBcon = null;
try{
$this->DBcon = new PDO("mysql:host=".$this->dbhost.";dbname=".$this->dbname, $this->dbuser, $this->dbpass);
}catch(Exception $e){
echo "error connecting:";
}
return $this->DBcon;
}
}
You need to set inside constructor:
private $dbhost;
private $dbuser;
private $dbpass;
private $dbname;
public function __construct(){
$config = require_once __DIR__ . 'config.php';
$this->dbhost = $config['host'];
$this->dbuser = $config['username'];
$this->dbpass = $config['pass'];
$this->dbname = $config['dbname'];
}
The first problem is that you can't just return anything from your config.php file. You can only return a result inside a function. One way to implement this is to declare the array as a global variable and then use it inside all other php files that would need that configuration array.
<?php
/**
* Contains all configurations
*
*/
$dbconfig = array(
'dbname' => 'user',
'pass' => '#user.intern1',
'username' => 'user1',
'host' => 'localhost',
);
?>
<?php
require_once __DIR__ . 'config.php';
class connect{
public function __construct(){
}
private $dbhost = $dbconfig['host'];
private $dbuser = $dbconfig['username'];
private $dbpass = $dbconfig['pass'];
private $dbname = $dbconfig['dbname'];
public function startConn(){
$this->DBcon = null;
try{
$this->DBcon = new PDO("mysql:host=".$this->dbhost.";dbname=".$this->dbname, $this->dbuser, $this->dbpass);
}catch(Exception $e){
echo "error connecting:";
}
return $this->DBcon;
}
}
?>
I am doing something using classes in php for very first time.
I am trying to fetch an return object array items in class.
This is my class
class User {
$dbconn = include("config.php");
private $dbHost = $dbconn->host;
private $dbUsername = $dbconn->username;
private $dbPassword = $dbconn->pass;
private $dbName = $dbconn->database;
private $userTbl = 'users';
function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
}
This is my config.php file
return (object) array(
'host' => 'localhost',
'username' => 'my_user',
'pass' => 'my_pass',
'database' => 'my_db'
);
How do i do it?
PHP Parse error: syntax error, unexpected '$dbconn' (T_VARIABLE)
You can't have executable code in a variable definition, only static values. So this sort of thing is not supported:
class foo {
public $var = result_of_some_function();
}
If you want to initialize a value, use the constructor. You're probably better off reading it as a config file:
class User {
public function __construct() {
$config = json_decode(file_get_contents('config.json'));
$conn = new mysqli($config->host, ...);
}
}
Or better, using dependency injection:
class User {
protected $db = null;
public function __construct($db) {
$this->db = $db;
}
}
Then in your code that creates a user object:
$db = new Db($config);
$user = new User($db);
The other way is to define constants in config file and use them in class.
in config.php file
define('HOST', 'localhost');
define('USERNAME', 'my_user');
define('PASS', 'my_pass');
define('DATABASE', 'my_db');
In class file
include("config.php")
class User {
private $dbHost = HOST;
private $dbUsername = USERNAME;
private $dbPassword = PASS;
private $dbName = DATABASE;
private $userTbl = 'users';
function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
}
Include this:
$dbconn = include("config.php");
in your construct function.
Maybe you should change in your code to
function __construct()
{
//included db file
include 'config.php';
if (!isset($this->db))
{
//code here
}
Try this way of using it.
<?php
class User
{
private $dbconn = null;
private $dbHost;
private $dbUsername;
private $dbPassword;
private $dbName;
private $userTbl = 'users';
function __construct()
{
include 'config.php'; //included file in constructor
if (!isset($this->db))
{
$this->dbHost= $this->dbconn->host;
$this->dbUsername= $this->dbconn->username;
$this->dbPassword= $this->dbconn->pass;
$this->dbName= $this->dbconn->database;
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if ($conn->connect_error)
{
die("Failed to connect with MySQL: " . $conn->connect_error);
} else
{
$this->db = $conn;
}
}
}
}
Config.php
<?php
$this->dbconn= (object) array(
'host' => 'localhost',
'username' => 'my_user',
'pass' => 'my_pass',
'database' => 'my_db'
);
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");
Im newbie in OOP. I have class Database
class Database{
private $host;
private $user;
private $pass;
private $db;
public $mysqli;
function db_connect(){
$this->host = 'localhost';
$this->user = 'root';
$this->pass = '';
$this->db = 'db';
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->mysqli;
}
Inside class Database i have function db_num
function db_num($sql){
$num = mysqli_num_rows(mysqli_query($this->mysqli,"{$sql}"));
return $num;
}
But it cant connect to database when im using in con argument $this->mysqli
It is bad practice to mix mysqli object style and procedural style.
Try this:
function db_num($sql){
$result = $this->mysqli->query($sql);
return $result->num_rows;
}
Be sure to connect to the database before you call db_num(), e.g.:
$db = new Database();
$db->db_connect();
$db->db_num("SELECT fields FROM YourTable");
A cleaner way in my opinion would be to call db_connect inside the constructor:
class Database{
private $host;
private $user;
private $pass;
private $db;
public $mysqli;
public function __construct() {
$this->db_connect();
}
private function db_connect(){
$this->host = 'localhost';
$this->user = 'root';
$this->pass = '';
$this->db = 'db';
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->mysqli;
}
public function db_num($sql){
$result = $this->mysqli->query($sql);
return $result->num_rows;
}
}
$db = new Database();
$db->db_num("SELECT fields FROM YourTable");
<?php
/**
* Creating a class for the database connection
* To start using the database connection like this: $database = DatabaseFactory::getFactory()->getConnection();
*/
class DatabaseFactory {
protected $servername = "servername";
protected $username = "root";
protected $password = "root";
protected $dbname = "databasename";
private static $factory;
private $database;
public static function getFactory() {
if(!self::$factory) {
self::$factory = new DatabaseFactory();
}
return self::$factory;
}
public function getConnection() {
if(!$this->database) {
try {
$this->database = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
} catch (mysqli_sql_exception $e) {
$error = $e->getMessage();
echo "Error:" .$error;
exit;
}
}
return $this->database;
}
}
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!';
}
}
}