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'
Related
I'm stuck in that situation that when I use $this->conn it returns:
Uncaught Error: Using $this when not in object context
but if I don't use it, then it said:
Undefined variable: conn
class save extends forma
{
private $servername = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'world';
public $conn;
protected $table;
private function __construct()
{
if (!$this->table)
die('No table name provided');
}
function connect()
{
$conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($conn->connect_error) {
die($this->conn->connect_error);
}
return $this->conn;
}
public function saugoti($id,$pakeitimui=0, $kas=0)
{
$this->connect();
if(isset($_POST['saugoti']))
{
$table = "bmp_test";
$id = $_POST['id'];
$pav = $_POST['pav'];
$adr = $_POST['adr'];
$tel = $_POST['tel'];
if ($pakeitimui == 0)
{
$sql1 = "SHOW FIELDS FROM $table ";
$result = $conn->query($sql1);
You want to use the class variable $conn everywhere (this will be written as $this->conn) instead of $conn (which is a local variable).
Replacing all occurences of $conn by $this->conn in your code will solve that problem.
The main reason it was not working is you are using $this->conn->connect_error in connect function while storing connection in $conn which is local variable and not class variable
If you dont want to call $this->connect(); in every function then below code might work for you
class save extends forma
{
private $servername = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'world';
public $conn;
protected $table = 'test_table';
public function __construct()
{
if (!$this->table)
die('No table name provided');
$this->connect();
}
function connect()
{
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_error) {
die($this->conn->connect_error);
}
return $this->conn;
}
public function saugoti($id,$pakeitimui=0, $kas=0)
{
if(isset($_POST['saugoti']))
{
$table = "bmp_test";
$id = $_POST['id'];
$pav = $_POST['pav'];
$adr = $_POST['adr'];
$tel = $_POST['tel'];
if ($pakeitimui == 0)
{
$sql1 = "SHOW FIELDS FROM $table ";
$result = $this->conn->query($sql1);
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)
{
//....
}
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 want to print out all content of the 'forum_question' table.
What am i doing wrong? No matter what, i will get the message "Nothing found!",
but i am sure the $db->connect DOES work, so it must be something with the query or loadRows functions.
This is my database class:
<?php
class Database {
private $host;
private $user;
private $password;
private $rows;
private $result;
private $dbName;
private $connection;
private $isReady;
public function __construct() {
$this->result = null;
$this->isReady = false;
}
/* setters */
public function setHost($host){ $this->host = $host; }
public function setUser($user){ $this->user = $user; }
public function setPassword($password){ $this->password = $password; }
public function setDbName($dbName){ $this->dbName = $dbName; }
/* Interface functions */
public function initiate($host=null,$user=null,$password=null,$dbName=null) {
if(isset($host,$user,$password,$dbName)==false) {
die("Please provide require settings.");
}
$this->setHost($host);
$this->setUser($user);
$this->setPassword($password);
$this->setDbName($dbName);
$this->isReady = true;
}
public function connect() {
if($this->isReady==false) {
die("Not ready to connect, please initiate connection");
}
$connection_string = "mysql:host=".$this->host.";dbname=".$this->dbName;
$this->connection = new PDO($connection_string, $this->user, $this->password);
$this->query("SET NAMES 'utf8'",$this->connection); // ensure character/language support
}
public function disconnect() {
$this->connection = null;
$this->isReady = false;
$this->setHost = null;
$this->setUser = null;
$this->setPassword = null;
$this->setDbName = null;
}
public function query($sql) {
$this->result = $this->connection->query($sql);
}
public function countRows() {
return $this->result->rowCount(); }
public function loadRows() {
if(!$this->result) die("Nothing found!");
$this->rows = array();
foreach ($this->result as $row) {
$this->rows[] = $row;
}
return $this->rows;
}
} // End of Database class
?>
This is my index file:
<?php
require_once 'class_database.php';
$db = new Database();
$db->initiate("localhost","USER","PASSWORD","DATABASE");
$db->connect();
$db->query("SELECT * FROM 'forum_question'");
$db->loadRows();
?>
Why don't you try with different connection script? For instance:
<?php
$mysql_server = "localhost";
$mysql_user = "USER";
$mysql_password = "PASSWORD";
$mysql_db = "DATABASE";
$mysqli = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($mysqli->connect_errno) {
printf("Connection failed: %s \n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
works fine, all you have to do is:
<?php
require_once "connection.php";
$query = "SELECT * FROM 'forum_question'";
$mysqli->query($query);
$mysqli->close();
Assuming that you saved the connection script in file "connection.php".
I have a database class that uses PDO. Here's a portion example of it:
class db {
private $host;
private $username;
private $password;
private $con;
private $pdo;
public function __construct( $database = "dnname" )
{
$this->host = "localhost";
$this->username = "username";
$this->password = "pass";
$conStr = "host={$this->host};dbname={$database}";
try {
$this->pdo = new PDO( "mysql:$conStr", $this->username, $this->password );
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
echo "error ". $e->getMessage();
}
}
public function fetch_single_row($sql, $data)
{
if( $data !== null )
$data = array_values( $data ); // Incase it's an associative array
$sel = $this->pdo->prepare( $sql );
$sel->execute( $data );
$sel->setFetchMode( PDO::FETCH_OBJ );
$obj = $sel->fetch();
return $obj;
}
I would like to use this class and its functions (it has more than I've included) inside other classes.
I have tried many many different things, but the only thing that works so far is starting a new instance of db in every new class which I think is bad practice. For instance:
class cms {
function cms(){
$this->db = new db();
}
function is_admin($id) {
if($this->db->fetch_single_row("SELECT id FROM user WHERE id = ? LIMIT 1", array($id))){
return true;
} else {
return false;
}
}
in my index.php, I include these classes and use them:
include("db.class.php");
include("cms.class.php");
$cms = new cms();
if($cms->is_admin($id)){
//code here
}
What is the correct way to accomplish this?
Take a look into the Singleton Design Pattern, it works great for a DB class
I used to use a class like this for quite a while
abstract class DB
{
protected static $instance;
protected $db;
protected static $host = 'host';
protected static $user = 'user';
protected static $pass = 'pass';
protected static $database;
public static function getInstance()
{
if (!isset(self::$instance)) self::$instance = new static();
return self::$instance;
}
protected function __construct()
{
$this->db = new PDO(sprintf('mysql:host=%s;dbname=%s', static::$host, static::$database), static::$user, static::$pass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function db()
{
return static::getInstance()->db;
}
public function fetch_single_row($sql, $data)
{
if( $data !== null )
$data = array_values( $data ); // Incase it's an associative array
$sel = self::db()->prepare( $sql );
$sel->execute( $data );
$sel->setFetchMode( PDO::FETCH_OBJ );
$obj = $sel->fetch();
return $obj;
}
}
I would then extend that class for each different database I would need to connect to
class Main extends DB
{
protected static $database = 'db';
}
You can then use the class like this
$db = Main::getInstance();
$obj = $db->fetch_single_row($sql, $data);