I have a created db.php file for all DB configs and db related queries functions in it.
And created functions.php file and extended that db class.
And when calling any method from that functions.php file getting that error:
Fatal error: Cannot declare class db, because the name is already in
use in C:\xampp\htdocs\Final\db.php on line 3
db.php
<?php
class db{
private $host = 'localhost';
private $user = 'abc';
private $pass = 'abc123';
private $dbname = 'testphase2';
protected static $mycon;
/*
This function is to connect with DB
*/
public function dbconnect()
{
if(!isset(self::$mycon))
{
self::$mycon = new mysqli($this->host,$this->user,$this->pass,$this->dbname);
}
if(self::$mycon ==false)
{
return false;
}
return self::$mycon;
}
/*
It is used to query the database
*/
public function getrows($sql)
{
$con = $this->dbconnect();
if(!$con)
{
echo "Failed";
}
else
{
//echo "Connected";
$result = mysqli_query($con,$sql) or die(mysqli_error());
}
return $result;
}
/*
It is used to query and fetch the dataset into array and return from the database
*/
public function fetchrows($query)
{
$rows = array();
$result = $this->getrows($query);
if($result== false)
{
return false;
}
while($row = $result->fetch_assoc())
{
$rows[]= $row;
}
return $rows;
}
public function db_close(){
mysqli_close($this->$mycon);
echo "Connection closed";
}
}
?>
functions.php
<?php
require('db.php');
class functions extends db{
public $currendata = '';
public function fetch_current_Record($id)
{
$con = new db();
$show_existingdata = "Select word from dictionary where id=$id";
$currendata = $con->fetchrows($show_existingdata);
return $currendata;
}
public function get_language()
{
try{
$con = new db();
$query = "SELECT language_id from language";
$result = $con->fetchrows($query);
return $result;
}
catch (Exception $e)
{
echo "Exception MESSAGE: ".$e->getMessage();
}
}
}
?>
Related
This question already has an answer here:
How to use PDO connection in other classes?
(1 answer)
Closed 2 years ago.
Now I learn to create PHP crud operations using OOP concept
In this code I faced some issues
Config.php
<?php
class Database{
private $dbHost = "localhost";
private $dbUsername = "root";
private $dbPassword = "";
private $dbName = "xtratuition";
public $db;
public function __construct(){
if(!isset($this->db)){
try{
$conn = new PDO("mysql:host=".$this->dbHost.";dbname=".$this->dbName, $this->dbUsername, $this->dbPassword);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db = $conn;
}
catch(PDOException $e){
die("Failed to connect with MySQL: " . $e->getMessage());
}
return $this->db;
}
}
}
?>
Modules.php
<?php
include_once("config.php");
class CrudController extends Database{
function sqlSelect($TblName , $Condition){
try{
$query = "SELECT * FROM `xtratuition`.$TblName WHERE $Condition";
$result = $this->db->prepare($query);
$result->execute();
$data = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return $data;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
class LoginController extends CrudController{
public $emailID;
function __construct($email){
$this->emailID = $email;
}
function userLogin(){
$data = $this->sqlSelect("users" , "email = '".$this->emailID."'");
return $data;
}
}
// This is works well
// $login = new CrudController();
// $data = $login->sqlSelect("`users`" , "email = 'klakshmanan48#gmail.com'");
// print_r($data);
$login = new LoginController("klakshmanan48#gmail.com");
$data = $login->userLogin();
print_r($data);
?>
I think I make a mistake in this code.
And I am getting this error
Fatal error: Call to a member function prepare() on null
on this line
$result = $this->db->prepare($query);
If you are defining constructor in child class, you have to call parent constructors explicitly they wont called automatically.
You have to call parent construct in your LoginContoller class
class LoginController extends CrudController{
public $emailID;
function __construct($email){
$this->emailID = $email;
parent::__construct(); //explicit call to parent constructor
}
function userLogin(){
$data = $this->sqlSelect("users" , "email = '".$this->emailID."'");
return $data;
}
}
I have file named dbcontroller.php. This file is an old file with mysql functions. But now i am trying to convert it into mysqli functions. Everything is working fine but $conn in mysqli_connect($conn,$query) is giving an error. How to resolve this?
Code
class DBController {
private $host = "localhost";
private $user = "root";
private $password = "";
private $database = "stores";
/**
* DBController constructor.
*/
public function __construct() {
$conn = $this->connectDB();
if(!empty($conn)) {
$this->selectDB($conn);
}
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password);
return $conn;
}
function selectDB($conn) {
mysqli_select_db($conn,$this->database);
}
function runQuery($query) {
$result = mysqli_query($conn,$query);// error
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function numRows($query) {
$result = mysqli_query($conn,$query);// error
$rowcount = mysqli_num_rows($result);
return $rowcount;
}
}
I think the issue is here:
public function __construct() {
$conn = $this->connectDB();
if(!empty($conn)) {
$this->selectDB($conn);
}
}
here $conn must be a class variable defined with other variables and can be accessed like:
$this->conn
I use of this mvc. (here is the documentation). Now I want to create a module for connect to database and run the query. but there is a error:
Fatal error: Cannot access self:: when no class scope is active in {address(in db.class.php)}
What is the problem ??
db.class.php (in the model folder)
<?php
class db{
/*** Declare instance ***/
private static $instance = NULL;
/*
* #return object (PDO)
*
* #access public
*/
public static function getInstance() {
if (!self::$instance) {
function dataQuery($query, $params) {
// what kind of query is this?
$queryType = explode(' ', $query);
// establish database connection
try {
self::$instance = new PDO('mysql:host=localhost;dbname=spy', USER, PASS);
self::$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = self::$instance->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step tp close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg.'<br>';
}
}
}
return self::$instance;
}
} /*** end of class ***/
?>
init.php (in the includes )
<?php
function __autoload($class_name) {
$filename = strtolower($class_name) . '.class.php';
$file = __SITE_PATH . '/model/' . $filename;
if (file_exists($file) == false)
{
return false;
}
include ($file);
}
/*** a new registry object ***/
$registry = new registry;
/*** create the database registry object ***/
$registry->db = db::getInstance();
?>
index.php: (in the controller folder)
<?php
Class indexController Extends baseController {
public function index() {
error_reporting(E_ALL);
ini_set('display_errors', 1);
define('USER', 'root');
define('PASS', '');
function findKitByMfgPrice($mfg, $price) {
$query = "SELECT * FROM `test` WHERE `prod_name` LIKE ? AND `prod_price` > ?";
$params = array($mfg, $price);
$results = dataQuery($query, $params);
return $results;
}
$mfg = '%Mobeius%';
$price = 34.95;
$kitsByMfgPrice = findKitByMfgPrice($mfg, $price);
echo '<pre>';
$welcome = $kitsByMfgPrice;
/*** set a template variable ***/
$this->registry->template->welcome = $welcome;
/*** load the index template ***/
$this->registry->template->show('index1');
}
?>
Your database should be used this way :
db.php :
class db{
/*** Declare instance ***/
private static $instance = NULL;
/*
* #return object (PDO)
*
* #access public
*/
public static function getInstance() {
if (!self::$instance) {
// establish database connection
try {
self::$instance = new PDO('mysql:host=localhost;dbname=spy', USER, PASS);
self::$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
}
return self::$instance;
}
public static function dataQuery($query, $params) {
// what kind of query is this?
$queryType = explode(' ', $query);
// run query
try {
$queryResults = self::getInstance()->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step tp close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg.'<br>';
}
} /*** end of class ***/
and to use it, in your index :
function findKitByMfgPrice($mfg, $price) {
$query = "SELECT * FROM `test` WHERE `prod_name` LIKE ? AND `prod_price` > ?";
$params = array($mfg, $price);
$results = db::dataQuery($query, $params);
return $results;
}
this should be a good start. But It still looks strange... the dataQuery methods is misplaced, it should not be part of the db class, it should be a local method of your index I think... Must think about it...
today i tried to convert my code to PHP/MySQLi OOP code.
class Database
{
private $host;
private $user;
private $password;
private $db;
private $mysqli;
function __construct()
{
$this->host = "*****";
$this->user = "*****";
$this->password = "******";
$this->db = "*****";
$this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);
if (mysqli_connect_errno()):
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
endif;
}
}
This is a script for the query's:
include_once("WD_Config/database.php");
class Adressen_Db
{
function __construct()
{
$this->database = new Database();
}
public function selecteer()
{
$query = "SELECT * FROM wd_adressen WHERE verborgen = 0 ORDER BY naam ASC";
$result = $this->database->mysqli->query($query);
return $result;
}
}
And this is how i call it.
$adressen = new Adressen_Db;
$adressen_result = $adressen->selecteer();
echo "<p>";
while ($row = $adressen_result->fetch_assoc()):
echo "<a href='http://maps.google.com/?q=".$row['voladres']."' target='_blank'>".$row['naam']."</a> woonachtig op <i>".$row['voladres']."</i><br>";
endwhile;
echo "</p>";
I alway get a "Call to a member function query() on a non-object". Doesn't matter what i trie ...
Can somebody tell me why that is?
Thanks!
The $mysqli variable in class Database is declared private.
You can access it only through setters and getters.
I think while you definitely need to have $mysqli as public so it can be accessed in the other method, there might be something else, as the error would be something like
trying to access private property in database class
or something like that, whereas your script throws a non-object call error
I think your new Adressen_Db; lacks the parenthesis:
$adressen = new Adressen_Db();
You can replace your code with this:
Config.php
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "your_database_name");
Now include this file in your database file
require_once 'config.php';
Class Database {
public $host = DB_HOST;
public $user = DB_USER;
public $pass = DB_PASS;
public $dbname = DB_NAME;
public $link;
public $error;
public function __construct() {
$this->getConnection();
}
private function getConnection() {
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
if (!$this->link) {
$this->error = "Connection failed" . $this->link->connect_error;
return false;
}
}
// for only select query
public function select($query) {
$result = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($result->num_rows > 0) {
return $result;
} else {
return false;
}
}
// for insert, delete and update
public function myquery($query) {
$myquery = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($myquery) {
return $myquery;
} else {
return false;
}
}
}
Now, make your queries like this:
<?php
require_once './lib/Database.php';
?>
<?php
class Admin {
private $db;
public function __construct() {
$this->db = new Database();
}
public function getData(){
$query = "SELECT * FROM admin";
$result = $this->db->select($query);
if($result != false){
while($row = $result->fetch_assoc()){
// do your thing
}
}
}
public function insert(){
$query = "INSERT INTO admin(admin_name) VALUES('$admin_name')";
$result = $this->db->myquery($query);
if($result){
$msg = "User has been added successfully.";
return $msg;
} else {
$msg = "Error while adding user. Please try again.";
return $msg;
}
}
}
Do this.
i want to crete a class that will contain various general variables and functions to be used throughout the website. One of these things will be a database connection. I am trying the following code:
class Sys {
public $dbc = new mysqli('localhost', 'user', 'pass', 'db');
$dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
}
$system = new Sys;
It is giving me a syntax error in the first line of the class... What am i doing wrong?
Thanks
you should do things like this in the constructor. You can only set primitives in the initial declaration. Also you need braces when creating the object.
class Sys {
private $dbc;
private $someInteger = 4; // you can do this
private $someArray = array(); // and this.
public function __construct()
{
$this->dbc = new mysqli('localhost', 'user', 'pass', 'db');
$this->dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
}
public function getDbc()
{
return $this->dbc;
}
}
$system = new Sys();
//$system->getDbc()->soSomethingWithMyDb();
i would advise you to read up on using objects: http://php.net/manual/en/language.types.object.php
You should just declare a public $dbc.
And then have a constructor function function __construct() { ...... } where you initialize it/ set it up.
class Sys {
public $dbc;
function __construct() {
$this->dbc = new mysqli('localhost', 'user', 'pass', 'db');
$this->dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
}
}
$system = new Sys;
class Sys {
var $mysqli;
function DB($database,$server,$user,$pass) {
$this->mysqli = mysqli_connect($server, $user, $pass, $base) or die('Server connection not possible. '. mysqli_connect_error());
}
}
include("db.class.mysqli.php"); // db handler class
// Open the base (construct the object):
$db = new Sys(DB_NAME, SERVER_NAME, USER_NAME, PASSWORD);
This is how I do it
check out the use of magic methods http://php.net/manual/en/language.oop5.magic.php in php - as mentioned above the __construct method is needed for your class to work. Below is an example from Peter Lavin's book Object Oriented PHP http://objectorientedphp.com/ in chapter 9.
class MySQLConnect {
// Data Members
private $connection;
private static $instances = 0;
// Constructor
public function __construct($hostname, $username, $password) {
if(MySQLConnect::$instances == 0) {
$this->connection = new mysqli($hostname, $username, $password);
// Check for Errors then report them
if ($this->connection->connect_error) {
die("Connect Error ($this->connection->connect_errno) $this->connection->connect_error");
}
// Set the Class variable $instances to 1
MySQLConnect::$instances = 1;
} else {
$msg = "There's another instance the MySQLConnect Class with a connect open already. Close it";
die($msg);
}
}
}
Try this:
$db = new DB;
$link = $db->connect()->getLink();
class DB {
public $connection = array();
public function __construct() {
return $this;
}
public function connect($host=null, $user=null, $pass=null, $database=null) {
$this->connection = new Connection($host, $user, $pass, $database);
$this->connection->connect();
$this->link = $this->connection->getLink();
if ($this->connection->ping()) {
if (!is_null($database)) {
if (!$this->connection->databaseConnect($database)) {
throw new\Exception('Unable to connect to the server.');
}
}
}else{
throw new \Exception('Unable to connect to the server.');
}
return $this;
}
public function getLink() {
return $this->link;
}
}
class Connection {
protected $chost='localhost';
protected $cuser='guest';
protected $cpass='password';
protected $cdatabase='PROFORDABLE';
function __construct($host=null, $user=null, $pass=null, $database=null) {
$host = !is_null($host) ? $host : $this->chost;
$user = !is_null($user) ? $user : $this->cuser;
$password = !is_null($pass) ? $pass : $this->cpass;
$database = !is_null($database) ? $database : $this->cdatabase;
$this->set('host', $host)->set('user', $user)->set('password', $password)->set('database', $database);
return $this;
}
public function connect() {
$link = mysqli_connect($this->host->getHost(), $this->user->getUser(), $this->password->getPassword());
if (!is_object($link)) {
throw new \Exception("An error has occurred while connecting to the server.");
}
$this->link = $link;
}
public function databaseConnect($database) {
if (!mysqli_select_db($this->getLink(), $database)) {
throw new \Exception("Unable to select the database.");
}
}
public function getLink() {
return $this->link;
}
public function ping() {
if (mysqli_ping($this->link)) {
return TRUE;
}
return FALSE;
}
public function set($name, $param) {
if (!isset($name) || !isset($param)) return $this;
$class = __NAMESPACE__.'\\'.ucwords($name);
$this->$name = new $class($param);
return $this;
}
public function get($name) {
$getfunc = 'get'.ucwords($name);
return $this->$name->$getFunc();
}
}
class Host {
public function __construct($host) {
$this->setHost($host);
}
public function setHost($host) {
$this->host = $host;
}
public function getHost() {
return $this->host;
}
}
class User {
public function __construct($user) {
$this->setUser($user);
}
public function setUser($user) {
$this->user = $user;
}
public function getUser() {
return $this->user;
}
}
class Password {
public function __construct($password) {
$this->setPassword($password);
}
public function setPassword($password) {
$this->password = $password;
}
public function getPassword() {
return $this->password;
}
public function sha($value) {
return sha1($value);
}
}
class guestPassword extends Password {
const PASSWORD='password';
public function __construct() {
return PASSWORD;
}
}
class Database {
public function __construct($database) {
$this->setDatabase($database);
}
public function setDatabase($database) {
$this->database = $database;
}
public function getDatabase() {
return $this->database;
}
}
class Query {
}
//Create mysql.php and paste following code
<?php
class MySQL {
private $set_host;
private $set_username;
private $set_password;
private $set_database;
public function __Construct($set_host, $set_username, $set_password) {
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$con = mysql_connect($this->host, $this->username, $this->password);
if (!$con) {
die("Couldn't connect to the server");
}
}
//end of __construct
//connect to database
public function Database($set_database) {
$this->database = $set_database;
mysql_query("set character_set_server='utf8'");
mysql_query("set names 'utf8'");
mysql_select_db($this->database) or die("Unable to select database");
}
//fetch data from any table
public function fetch_data($sql) {
$this->sql = $sql;
$query = mysql_query($this->sql);
$result = array();
while ($record = mysql_fetch_array($query)) {
$result[] = $record;
}
return $result;
}
//fetch all columns from any table to be used for INSERT INTO.
public function get_all_columns($table_name) {
$this->table_name = $table_name;
$sql = "SHOW COLUMNS FROM $this->table_name";
$result = mysql_query($sql);
while ($record = mysql_fetch_array($result)) {
$fields[] = $record['0'];
}
$val = '';
foreach ($fields as $value) {
$val .= $value . ',';
}
$vals = rtrim($val, ',');
return $vals;
}
//insert data to any table by $_POST or set of variables separated by ,
public function insert_data($tbl_name, $tbl_value) {
$this->tbl_name = $tbl_name;
$this->tbl_value = $tbl_value;
//use mysql_real_escape_string($tbl_value) to clean & insert data.
$this->tbl_col = $this->get_all_columns($this->tbl_name);
$sql = "INSERT INTO $this->tbl_name ($this->tbl_col) VALUES ($this->tbl_value)";
$query_result = mysql_query($sql);
}
//end of insert data
public function delete_data($del_id, $table_name) {
$this->del_id = $del_id;
$this->table_name = $table_name;
if (isset($this->del_id) && is_numeric($this->del_id) && !empty($this->del_id)) {
$sql = "DELETE FROM $this->table_name WHERE id=$this->del_id LIMIT 1";
$del_result = mysql_query($sql);
$aff_row = mysql_affected_rows();
return $aff_row;
}
}
}
// class ends here
//call class to connect to server and db as well.
$connect = new MySQL('localhost', 'root', '');
$connect->Database('db_name');
?>
//include file mysql.php and call your class object as :
//fetching data from any table use :
$variable = $connect->fetch_data("SELECT * FROM table_name");
for($i=0;$i<count($variable);$i++){
$result = $variable[$i]['col_name'];
}
//insert INTO values in any table
$result = $connect->insert_data($tbl_name, $tbl_value);
if($result)
echo 'inserted';
else{
echo 'failed';
}
//delete record from any table
$result = $connect->delete_data($del_id, $table_name)
You can use a wonderful class ezSQL