I'm creating a CMS that provides dynamic database creation at the initial project setup stage.
I have defined the database configuration details as constants in config.php file:
//Database Name
define('DEFAULT_DB_NAME', 'cms');
//User Name
define('DEFAULT_USER_NAME', 'root');
//Password
define('DEFAULT_PASSWORD', '');
//Host Name
define('DEFAULT_HOST_NAME', 'localhost');
I included the config.php file in my database connection file (db.class.php):
<?php
include_once '../../config/config.php';
class Db{
protected $conn;
protected $host = DEFAULT_HOST_NAME;
protected $username = DEFAULT_USER_NAME;
protected $password = DEFAULT_PASSWORD;
protected $dbname = DEFAULT_DB_NAME;
public function __construct(){
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->dbname);
if($this->conn->connect_error){
die("<h3>Connection Failed!!! Error: " . $this->conn->connect_error . "</h3>");
}
}
}
I also have created a dynamic Style sheet (admintheme.php) that modifies the admin panel based on user preference:
<?php
header("Content-type: text/css;");
include_once '../../model/admintheme.class.php';
$theme = new Admintheme();
$result = $theme->ReadAdminTheme();
if($result == '' || $result == '0'){
$sidebarBg = "#111";
$sidebarPosition = "left";
$sidebarunset = "left";
$sidebarright = "unset";
}
else{
$row = $result->fetch_assoc();
$sidebarBg = $row['sidebarbg'];
$sidebarPosition = $row['sidebar_position'];
if($sidebarPosition == "left"){
$sidebarunset = "right";
}
else{
$sidebarunset = "left";
}
}
?>
/*-- ------------------------xx----------------------- */
/***** Content Section Starts *****/
.content{
margin-<?= $sidebarPosition; ?>: auto;
}
/***** Content Section Ends *****/
/**** Side Bar Section Starts *****/
.sidebar-nav{
background-color: <?= $sidebarBg; ?>;
<?= $sidebarPosition; ?>: 0px;
}
The issue is that when I use static data in "db.class.php" file (ex. directly write "localhost" in place of the constant and so on..) then "admintheme.php" works fine and displays the desired output, but when I use constants in place of the static data then all other functionalities of the project work fine and retrieve data from the database except "admintheme.php".
The "admintheme.php" also works fine when the constants are defined inside the "db.class.php" or if the "config.php" file is in the same directory as of the "db.class.php" but while including the the "config.php" file from other directory, all other data is retrieved except "admintheme.php".
**No direct error is received but in the browser's console, it states (include_once(../../config/config.php): failed to open stream: No such file or directory...)
**Included path is correct in both "db.class.php" and "admintheme.php".
Any help is greatly appreciated.
Adding "DIR" magic constant solved the issue.
Related
This question already has an answer here:
Using MySQLi from another class in PHP
(1 answer)
Closed last year.
Now I want to finally move on and use classes. But I can't figure out a proper way to have access to mysql in functions of my classes without inclusion of the so called db.php file on top of each file.
db.php
class ConnectionDB{
private $server = "localhost";
private $username = "root";
private $password = "";
private $db = "oop_crud";
private $conn;
public function __construct(){
try{
$this->conn = new mysqli($this->server, $this->username,$this->password,$this->db);
}
catch (Exception $e){
echo "Connection faild" .$e->getMessage();
}
}
}
Usermodel.php
include 'db.php';
$ConnectionDB = new ConnectionDB();
class usermodel {
public function insert()
{
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$password = $_POST['password'];
if ((!empty($name)) && (!empty($email)) && (!empty($mobile)) && (!empty($password))) {
$data = "INSERT INTO `register` (`u_id` , `name`, `mobile`,`email`,`password`) VALUES (NULL , '$name', '$mobile' , '$email', '$password')";
if ($sql = $this->conn->query($data)) {
echo "Yes";
}else{
echo "No";
}
}else{
echo '<div class="alert alert-danger alert-dismissible fade show"><button type="button" class="close" data-dismiss="alert">×</button><strong>Danger!</strong> All Field are Required </div>';
}
}
}
}
?>
i want to call ConnectionDB class in my usermodel file
What you should do is to think about an implementation of psr-4 autoloading. Please read more about this here: PSR-4
The easiest way to autoload classes is to use composer and composer init command in your project: Composer Installation
Once you run this command it will guide you through a few steps. Please choose "project" as a type and follow the instructions.
Then include autoload.php file from vendor/autoload.php in your index.php file and voila - if you follow psr-4 rules then all the classes will be loaded automatically without a need to use include 'db.php'; or similar code.
I have two files, one config.php and source.php in a subdirectory. In the config file I have something that looks like this
<?php
//app settings
$GLOBALS['app_url'] = 'http://www.website.com/subdirectory'; //ex:
//demo mode
$GLOBALS['demo_mode'] = 0; //possible values: 0 or 1
$GLOBALS['db_table']['sms'] = 'sms_numbers';
$GLOBALS['db_table']['sms_history'] = 'sms_history';
?>
In the config.php file, I have this string $GLOBALS['app_url'] = 'http://www.website.com/subdirectory'; for the base URL and I'd like to make it so that the base URL is automatically detected. I'd like to use something similar to this <?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>. I'm using these files under different directories and that's why I'd like to combine them in order to make it automatic without me having to update the base URL manually every time I create a new subdirectory.
Also, inside config.php I have:
//Admin access
$GLOBALS['admin_username'] = 'admin';
$GLOBALS['admin_password'] = 'password';
These values are not in a database but a local file named source.php and I'd like to be able to update the values "admin" and "password" from this source.php file.
Inside the source.php file I guess I'd have to have something thta'd look like this: $username = 'admin';
I'm really sorry but I'm new and would like to learn this stuff. I appreciate any help I can get.
Thank you
Use global constants in config.php
define('APP_URL', 'http://www.website.com/subdirectory');
Then anywhere in the code you can do:
$path = APP_URL . "/path/to/file"
I dont recommend storing admin_username and admin_password as global variables or constants, instead you can create a class in your config.php that contains the values.
Config Example:
config.php
define('APP_URL','http://www.website.com/subdirectory');
define('DEMO_MODE',0); //possible values: 0 or 1
.....
class DB{
var $conn;
public function __construct()
{
$user = "admin";
$pass = "pass";
$host = "127.0.0.1";
$database = "database_name";
$this->conn = mysqli_connect($host, $user, $pass, $database);
}
}
Then in your index.php file you do:
require_once("config.php")
$db = new DB;
$conn = $db->conn();
....
I'm currently making a PHP script and I need some help. Firstly it allows the user to enter database information on a file called install.html which presents a form to the user. The form uses GET to then send that information to a second install file which creates the relevant tables, enters the information into the tables and then allows the user to carry on with the script.
However I was wondering. In the second install file I used:
$databaseServer = $_GET["databaseServer"];
in order to get the information that was entered into the form. Is there anyway I can then send these variables ($databaseServer, $databaseName, $databaseUser, $databasePassword) to another file called db.php that I will include on top of every file I write that requires an SQL connection. I have looked at GLOBAL variables but they didn't work properly. I could have been doing something wrong however.
You could save a configuration array to a file:
<?php
class Config
{
public $path;
public function __construct($path)
{
$this->path = $path;
}
public function store($config)
{
$dump = var_export($config, true);
$dump = '<?php return ' . $dump . ';';
file_put_contents($this->path, $dump);
}
public function retrieve()
{
return include $this->path;
}
}
// Build your config array
$config['database'] = $_GET['database'];
$config['username'] = $_GET['username'];
// Make sure your server can write to this path
$configurator = new Config(__DIR__ . '/config/config.php');
// Save your config
$configurator->store($config);
// Get your config later
$read_config = $configurator->retrieve();
// Check our config against the saved version
assert($config == $read_config);
var_dump($read_config);
I will be straight to the point with this. Can't seem to find it anywhere on the internet. Maybe it is not even possible, i dont know. I do really like to use the method "divide and rule", created it myself. Splitting as much files as possible for easy management (small files and such).
But here is my problem:
I have 5 files:
index.php
inc/config.php
inc/Database.class.php
inc/sidebar.php
inc/forms.php
Okay, what i have done is this:
in my config.php file i included the Database.class.php file and created an object.
include 'Database.class.php';
$user = "root";
$pass = "";
$host = "localhost";
$database = "blah blah";
$db = new Database($user, $pass, $host, $database);
$db->connect();
So i included this config.php and sidebar.php in my index.php file.
(shortened the code, but it functions the same)
include 'inc/config.php';
include 'inc/sidebar.php';
In my sidebar i have a form, for users to login.
in sidebar.php i just include forms.php, this is the forms.php:
(I used print_r to debug my file, to see if anything returns and i left out the method loginFormShow because it is very long and not relevant)
function loginFormProcess($user, $pass)
{
$db->select(blah blah some variables);
$res = $db->getResult();
print_r($res);
}
if (!isset($_POST['submit'])) {
loginFormShow();
} else {
if ($_POST['user'] == "")
{
loginFormShow(1);
}
else if ($_POST['pass'] == "")
{
loginFormShow(2);
}
else
{
$user = $_POST['user'];
$pass = $_POST['pass'];
loginFormProcess($user, $pass);
}
}
And thus, what the problem is. When i try to call the function loginFormProcess, it cant use the object $db.
Can i use 1 object for this? Because on the index page i am going to require some other data from the database. Do i need to create an object for the index page and one for the login form?
Is there any other solution?
If i am not clear, i would love to give some more explanation.
Cheers,
Clemenz
The best solution would be to pass the database object to the function's arguments as follows:
function loginFormProcess($user, $pass, Database $db) {
And call it with an appropriate Database object. This is what know as dependency-injection.
Try this:
function loginFormProcess($user, $pass)
{
global $db;
$db->select(blah blah some variables);
$res = $db->getResult();
print_r($res);
}
For reference: http://php.net/manual/en/language.variables.scope.php
You need to declare $db as global.
Try this:
function loginFormProcess($user, $pass)
{
global $db;
$db->select(blah blah some variables);
$res = $db->getResult();
print_r($res);
}
See: http://www.php.net/manual/en/language.variables.scope.php
The variable $db is created as a global variable in your config.php file. This is invisible from inside the loginFormProcess function. A shotcut solution you can use is declaring your intention of using a global variable by adding the statement global $db; as the first statement inside your function
I have a html page that calls a php object to get some data back from the database. It works fine, but the script was getting unwieldy so I decided to break some of it out into a bunch of functions.
So I have the following files:
// htdocs/map.php
<?php
include("config.php");
include("rmap.php");
$id = 1;
$gamenumber = getGameNumber($id);
echo $gamenumber;
?>
// htdocs/config.php
<?php
$_PATHS["base"] = dirname(dirname(__FILE__)) . "\\";
$_PATHS["includes"] = $_PATHS["base"] . "includes\\";
ini_set("include_path", "$_PATHS[includes]");
ini_set("display_errors", "1");
error_reporting(E_ALL);
include("prepend.php");
?>
// includes/prepend.php
<?php
include("session.php");
?>
// includes/session.php
<?php
includes("database.php");
class Session {
function Session() {
}
};
$session = new Session;
?>
// includes/database.php
<?php
include("constants.php");
class Database {
var $connection;
function Database() {
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());
}
function query($query) {
return mysql_query($query, $this->connection);
}
};
/* Create database connection */
$database = new Database;
?>
// includes/rmap.php
<?php
function getGameNumber($id) {
$query = "SELECT gamenumber FROM account_data WHERE usernum=$id";
$result = $database->query($query); // line 5
return mysql_result($result, 0);
}
?>
And constants has a bunch of defines in it (DB_USER, etc).
So, map.php includes config.php. That in turn includes prepend.php which includes session.php and that includes database.php. map.php also includes rmap.php which tries to use the database object.
The problem is I get a
Fatal error: Call to a member function on a non-object in
C:\Develop\map\includes\rmap.php on line 5
The usual cause of this is that the $database object isn't created/initialised, but if I add code to show which gets called when (via echo "DB connection created"; and echo "using DB connection";) they are called (or at least displayed) in the correct order.
If I add include("database.php") to rmap.php I get errors about redefining the stuff in constants.php. If I use require_once I get the same errors as before.
What am I doing wrong here?
$database is not in the scope of function GetGameNumber.
The easiest, though not necessarily best, solution is
<?php
function getGameNumber($id) {
global $database; // added this
$query = "SELECT gamenumber FROM account_data WHERE usernum=$id";
$result = $database->query($query); // line 5
return mysql_result($result, 0);
}
?>
global is deemed not perfect because it violates the principles of OOP, and is said to have some impact on performance because a global variable and all its members are added to the function's scope. I don't know how much that really affects performance, though.
If you want to get into the issue, I asked a question on how to organize such things a while back and got some good answers and links.
You need to include
global $database;
at the top of getGameNumber(), since $database is defined outside of getGameNumber itself
Your $database varibleis not accessible from the function's scope automatically. You might need to declare it as global $database; in the function.
Scopes in PHP are explained in the documentation: http://de3.php.net/manual/en/language.variables.scope.php
Please also mind that PHP 4and MySQL3 are out of support for a looooong time and might contain security problems and other unfixed issues.