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;
}
}
?>
Related
Am new to PDO, I have constructed the class as shown below. At Some point, I want to use the private variables in another script which requires this dbconnection.php
dbconnection.php
<?php
class DBconnect
{
private $host = 'localhost';
private $username = 'db_user';
private $password = 'pass';
private $dbname = 'db';
protected function connect()
{
$config = 'mysql:host='.$this->host.';dbname='.$this->dbname;
$pdo = new PDO($config, $this->username, $this->password);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
}
}
user.php
<?php
require dbconnection.php
//how can I call the private variables here?
I am modifying a script that I bought and I am having trouble making the Database name variable that is set in the Database class be the result of the variable I construct above it. I need the $dbName variable to be set to the combination of "mmo_" appended to the variable $username that I get from my database. The name of the database should be "mmo_school" with school being the $username variable that is pulled from database. However, it fails unless I put the text of the variable in single quotes after $dbName = . But I need the database name to be dynamically set based on which user is using the script. I hope that this makes sense and I really appreciate your help!!
$username = "school";
$newname = "mmo_" . $username; **// the results of this would be "mmo_school"**
class Database
{
private static $dbName = $newname ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'username';
private static $dbUserPassword = 'password';
private static $cont = null;
public function __construct() {
exit('Init function is not allowed');
}
public static function connect() {
// One connection through whole application
if ( null == self::$cont ) {
try {
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
} catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect() {
self::$cont = null;
}
}
if I type in $dbName = 'mmo_school' ; THIS WORKS.
if I try to use the variable I create as shown above...IT DOESN'T!!!
THANKS FOR YOUR HELP!!
Create a public static method to set the host, username, password, and etc. Also, i would change your constructor to private not public.
Database::setDB('mmo_' . $username);
// or
Database::setConnectInfo('mmo_' . $username, 'some host', $username, 'some password');
$db = Database::connect();
class Database
{
private static $dbName = $newname ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'username';
private static $dbUserPassword = 'password';
private static $cont = null;
private function __construct() {
exit('Init function is not allowed');
}
public static function setDB($dbName){
self::$dbName = $dbName;
}
// or use this function
public static function setConnectInfo($dbName, $dbHost, $dbUsername, $dbUserPassword){
self::$dbName = $dbName;
self::$dbHost = $dbHost;
self::$dbUsername = $dbUsername;
self::$dbUserPassword = $dbUserPassword;
}
public static function connect() {
// One connection through whole application
if ( null == self::$cont ) {
try {
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
} catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect() {
self::$cont = null;
}
}
In your class you have to call $newname as a global variable. With this minor change your code should work.
$username = "school";
$newname = "mmo_" . $username; **// the results of this would be "mmo_school"**
class Database {
private static $dbName = "" ;
private static $dbHost = 'localhost' ;
private static $dbUsername = 'username';
private static $dbUserPassword = 'password';
private static $cont = null;
function __construct($init_parameter) {
global $newname;
$this->$dbName = $newname;
}
public static function connect() {
// One connection through whole application
if ( null == self::$cont ) {
try {
self::$cont = new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);
} catch(PDOException $e) {
die($e->getMessage());
}
}
return self::$cont;
}
public static function disconnect() {
self::$cont = null;
}
}
because single quotes don't do variable expansion - use double quotes
$var = 'dingo';
$name = 'xyz_$var'; // result 'xyz_$var'
$name = "xyz_$var"; // result 'xyz_dingo'
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 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");