I am working/learning how to mvc a project structure. I have a database connector, a registry class, a model and an application model. I have all these in one place to check it working. The problem is I get these three errors when I execute.
<?php
class db
{
protected $conn;
protected $host, $username, $password, $database;
public function __construct($host, $username, $password, $database)
{
$this->conn = new mysqli($host, $username, $password, $database)
OR die("There was a problem connecting to the database");
return true;
}
public function query($sql)
{
$result = $this->conn->query($sql);
if (!$result) {
die('Invalid query:');
}
return $result;
}
public function escape($value)
{
return $this->conn->real_escape_string($value);
}
public function countAffected()
{
return $this->conn->affected_rows;
}
public function getLastId()
{
return $this->conn->insert_id;
}
public function __destruct()
{
$this->conn->close()
OR die("Problem disconnecting from the database");
}
}
final class registry
{
private $data = array();
public function get($key)
{
return (isset($this->data[$key]) ? $this->data[$key] : null);
}
public function set($key, $value)
{
$this->data[$key] = $value;
}
public function has($key)
{
return isset($this->data[$key]);
}
}
abstract class Model
{
protected $registry;
public function __construct($registry)
{
$this->registry = $registry; // Undefined variable: registry
}
public function __get($key)
{
return $this->registry->get($key);
}
public function __set($key, $value)
{
$this->registry->set($key, $value);
}
}
class MemberModel extends Model
{
public function getMember()
{
$result = $this->query("SELECT * FROM members"); //Call to undefined method MemberModel::query()
return $result;
}
}
// DB
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'pcaframework');
$registry = new registry();
// Database
$db = new db(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);
$membermodel = new MemberModel(); //Missing argument 1 for Model::__construct()
$allMembers = $membermodel->getMember();
while ($row = mysqli_fetch_assoc($allMembers)) {
echo "First Name: " . $row['name'] . "<br />";
echo "Last Name: " . $row['email'] . "<br />";
echo "<hr />";
}
Missing argument 1 for Model::__construct(), called on $membermodel = new MemberModel();
Undefined variable: registry
Call to undefined method MemberModel::query()
I have commented the error in the code to mark exactly where the error occurs.
Solution to:
$result = $this->query("SELECT * FROM members"); //Call to undefined method MemberModel::query()
Replace with:
$result = $this->conn->query("SELECT * FROM members");
You just forget the "->conn->".
Solution to:
$this->registry = $registry; // Undefined variable: registry
And
$membermodel = new MemberModel(); //Missing argument 1 for Model::__construct()
Just replace this last with the $registry var as a parameter to the new class:
$membermodel = new MemberModel($registry);
You're calling the constructor, that needs a parameter, but you're not refering that parameter.
Related
Here is my config.php
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'xxxx');
define('DB_USER', 'xxxx');
define('DB_PASS', 'xxxx');
?>
And It is DB.php
<?php
include 'config.php';
class DB {
public static $pdo;
public static function connection(){
if (!isset(self::$pdo)) {
try {
self::$pdo = new PDO('mysql:host='.DB_HOST.'; dbname ='.DB_NAME,DB_USER, DB_PASS);
}catch(PDOException $e){
echo $e->getMessage();
}
}
return self::$pdo;
}
public static function prepareOwn($sql){
return self::connection()->prepare($sql);
}
}
?>
3rd file is Student.php
<?php
include 'DB.php';
class Student {
public $table = 'student_info';
public function readAll(){
$sql = "SELECT * FROM $this->table";
$stmt = DB::prepareOwn($sql);
$stmt->execute();
return $stmt->fetchAll();
}
}
?>
But When I try to access readAll() from index.php using spl_autoload_register() Then I can see Fatal error: Call to undefined method DB::prepareOwn()
Can anyone help me to solve the problem??
Many thanks.
Sahidul
i copied your code into mine and saw your error. but as i guessed, first you will get an error with this line inside db.php:
return self::$pdo->prepare($sql);
Fatal error: Call to a member function prepare() on null
where prepare function came from? $pdo is just a static property in this class and it doesn't have a function called prepare! fix this line
Updated
the problem is you forgot to call connection method inside your prepareOwn. so your new prepareOwn function should be:
public static function prepareOwn($sql) {
self::connection();
return self::$pdo->prepare($sql);
}
i hope this code will work for you
class MySQLDatabase {
// Class attributes
private $host_name = "localhost";
private $database_name = "XXXXXXX";
private $database_username = "XXXXXXX";
private $database_password = "XXXXXXX";
private $is_connected;
private $connection;
private $statement ;
// construct
public function __construct() {
$this->open_connection();
}// End of construct
// connection method
public function open_connection() {
try {
$this->is_connected = TRUE ;
// PDO Connection
$this->connection = new PDO("mysql:host=".$this->host_name.";dbname=".$this->database_name.";charset=utf8",$this->database_username,$this->database_password);
// Error reporting
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(PDO::ATTR_EMULATE_PREPARES,FALSE);
} catch(PDOException $errors) {
$this->is_connected = FALSE ;
self::catch_errors($errors);
}
}// End of open connection method
// Get connection method
public function connection(){
return $this->connection ;
}
// Close connection method
public function close_connection() {
$this->connection = null;
}// End of close connection method
private static function catch_errors($errors) {
echo("<h4><p>" . $errors -> getMessage() . "</p></h4>");
die();
}
// query method
public function query($sql){
return $this->statement = $this->connection->prepare($sql);
}
}// End of database class
$database = new MySQLDatabase();
class Student {
protected static $table = 'My_table';
public function readAll(){
global $database;
try{
$sql = "SELECT * FROM ". self::$table;
$stmt = $database->query($sql);
$stmt->execute();
return $stmt;
}catch(PDOException $error){
echo("<h4><p>" . $errors -> getMessage() . "</p></h4>");
die();
}
}
}
$c = new Student();
$s = $c->readAll();
$stmt = $s->fetchAll(PDO::FETCH_ASSOC);
foreach($s as $v){
var_dump($v);
}
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'm tryign to create an object orientated approach to a project I'm working on for fun, but I'm having trouble getting my head around the idea of a database class. I'm getting the following error.
Call to undefined method Database::prepare()
Database Class
class Database
{
protected $connection;
function __construct()
{
$this->createConnection();
}
private function createConnection()
{
$this->connection = new mysqli("localhost", "user", "password", "test");
if ($this->connection->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->connection->connect_errno . ") " . $this->connection->connect_error;
}
else
{
echo 'Connected to database.<br />';
}
}
}
$db = new Database();
UserActions Class
class userActions
{
protected $_db;
protected $_username;
protected $_password;
protected $_auth;
protected $tableName;
function __construct($db, $username, $password, $auth)
{
$this->_db = $db;
$this->_username = $username;
$this->_password = $password;
$this->_auth = $auth;
$this->checkUserExists();
}
private function checkUserExists()
{
$query= "SELECT COUNT(*) FROM '{$this->tableName}' WHERE username = ?";
$stmt = $this->_db->prepare($query);
$stmt->bind_param('s', $this->username);
$userNumber= $stmt->execute();
echo $userNumber;
}
}
What am I doing wrong, could I do anything to improve the way I'm going about this task?
You need to add the following method to your class:
public function prepare($query) {
return $this->connection->prepare($query);
}
You could define a magic method for your class that automatically passes any undefined method to the connection:
public function __call($name, $arguments) {
return call_user_func_array(array($this->connection, $name), $arguments);
}
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
I had 2 Class in PHP That i want to use with each other, but the Class in 2 different PHP Script like clothing_product.php and database.php. It look like this Below:
database.php:
require_once('config.php');
class MySqlDatabase
{
private $connection;
private $last_query;
private $magic_quotes_active;
private $real_escape_string_exist;
function __construct(){
$this->open_connection();
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exist = function_exists("mysql_real_escape_string");
}
private function open_connection()
{
$this->connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$this->connection){
die("Connection failed!". mysql_error());
}
else{
$db_select = mysql_select_db(DB_NAME);
if(!$db_select){
die("Select database failed". mysql_error());
}
}
}
public function query($sql){
$this->last_query = $sql;
$result = mysql_query($sql,$this->connection);
$this->confirm_query($result);
return $result;
}
public function confirm_query($result){
if(!$result){
$output = "Database query failed: " . mysql_error()."<br /><br />";
$output.= "Last query that fail is:" . $this->last_query;
die($output);
}
}
private function escape_value($value) {
if ($this->real_escape_string_exist) {
if($this->magic_quotes_active) {$value = stripslashes($value);}
$value = mysql_real_escape_string($value);
}
else {
if (!$this->magic_quotes_active) {$value = addslashes($value);}
}
return $value;
}
public function fect_array($result){
return mysql_fetch_array($result);
}
public function num_rows($result){
return mysql_num_rows($result);
}
public function last_id(){
return mysql_insert_id($this->connection);
}
public function affected_rows(){
return mysql_affected_rows($this->connection);
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
}
//$db = new MySqlDatabase();
clothing_product.php:
include('../database.php');
class Clothing_Product {
public $db = new MySqlDatabase();
public static function test(){
echo "Static call successfull";
return "Static call successfull";
}
}
The problem is when i try to USE 'Public $db = new MySqlDatabase();' in class clothing_product i get Error. I think the problem is maybe i got a wrong call. Please help me cuz m a noob thnk.
You can't initialize member variables to anything that is not static, and you're trying to create an object here:
public $db = new MySqlDatabase();
From the manual:
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 workaround is to set your variable in the constructor:
public $db;
public function __construct() {
$this->db = new MySqlDatabase();
}