Fatal error: Call to undefined function - php

ERROR is : Fatal error: Call to undefined function Connect_DB() in
C:\wamp\www\movie\movies.php on line 12
config.php :
<?php
//error_reporting(0);
class Connection{
private $host = "localhost";
private $username = "root";
private $password = "";
private $db = "movies";
private $connect;
private $q;
function Conn(){
$this->connect = #mysql_connect($this->host, $this->username, $this->password);
return $this->connect;
}
function Select(){
mysql_unbuffered_query('SET NAMES utf8');
return mysql_select_db($this->db);
}
function Query($sql){
$this->q = mysql_query($sql);
return $this->q;
}
function Rows(){
return mysql_num_rows($this->q);
}
function Object(){
return mysql_fetch_object($this->q);
}
}
?>
movies.php:
<?php
class Movies{
function Connect_DB(){
$data = new Connection;
if(!($data->Conn())) header("Location: 404.php");
if(!($data->Select())) header("Location: 404.php");
return $data;
}
function getImdb(){
$q = "SELECT * FROM top250";
$data = Connect_DB();
$ch = $data->Query($q);
if($ch){
$i=0;
while($r = $data->Object()){
$result["name"][$i] = $r->name;
$result["genre"][$i] = $r->genre;
$result["imdb"][$i] = $r->imdb;
$result["year"][$i] = $r->year;
$result["releaseDate"][$i] = $r->releaseDate;
$result["country"][$i] = $r->country;
$result["imgPath"][$i] = $r->imgPath;
$i++;
}//while
return $q;
}else{
$result = false;
return $result;
}//else
}//getImdb
}
?>
Here is html file:
<?php
require "config.php";
require "movies.php";
$imdb = new Movies;
$result = $imdb->getImdb();
?>
<!DOCTYPE HTML>
<html>
<head>
.....
I couldn't find where error is ? I have 2 class (config.php and movies.php) Config.php has mysql connection settings and movies has getting a table from mysql and html file include 2 file and show table. Can someone help me ?

you are not calling CONNECT_DB correctly. In a class when you want to call another method we use $this->method(). So change the line $data = Connect_DB(); to $data = $this->Connect_DB();

Related

PDO throw error Undefined variable: pdo in

I have 3 files: dbconnect (here's declaration of $pdo), core.php (file with class to manage) and test.php.
I want to receive data from DB, but I have error:
Notice: Undefined variable: pdo in C:\xampp\htdocs\project\core.php on line 24
In dbconnect $pdo is in try catch, but before this I put: $pdo=null(to make variable accessible) but it doesn't work.
dbconnect ---> core.php(error here) ---> test.php;
//dbconnect.php
<?php
$mysql_host = 'localhost';
$username = 'root';
$password = '';
$database = 'db';
$pdo = null;
try {
$pdo = new PDO('mysql:host='.$mysql_host.';dbname='.$database.';charset=utf8', $username, $password );
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone.<br />';
}
?>
//core.php
require_once('cms/dbconnect.php');
class getCore{
public $link_allegro;
public $link_facebook;
function getLinks(){
$query= $pdo->query('SELECT `url` FROM `links` WHERE `title` = "facebook"');
$row = $query->fetch();
$this->link_facebook = $row["url"];
$query= $pdo->query('SELECT url FROM links WHERE title = "allegro"');
$row = $query->fetch();
$this->link_allegro = $row["url"];
$query->closeCursor();
}
}
//test.php
<?php
require_once('core.php');
$tmp = new getCore;
$tmp->getLinks();
echo $tmp->link_allegro;
echo $tmp->link_facebook;
?>
Anyone can solve this? Thanks.
This is a scoping problem. $pdo doesn't exists in your getCore class.
You can make a DatabaseConnect class to manage your db access.
You can use this basic class for your database connection :
<?php
class DatabaseConnect {
private $mysql_host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'db';
private $pdo = null;
public function getPdo(){
return $this->pdo;
}
public function __construct(){
try {
$this->pdo = new PDO('mysql:host='.$mysql_host.';dbname='.$database.';charset=utf8', $username, $password );
}
catch(PDOException $e) {
echo 'Połączenie nie mogło zostać utworzone.<br />';
}
}
}
?>
You can getting your PDO instance in an other class with calling DatabaseConnect object -> getPdo() :
- Instannciate a new DatabaseConnect.
- Get PDO instance with the methof of the class.
Like that :
$databaseConnect = new DatabaseConnect();
$pdo = $databaseConnect->getPdo();
You next code :
//core.php
require_once('cms/dbconnect.php');
class getCore{
public $link_allegro;
public $link_facebook;
function getLinks(){
$databaseConnect = new DatabaseConnect();
$pdo = $databaseConnect-getPdo();
$query= $pdo->query('SELECT `url` FROM `links` WHERE `title` = "facebook"');
$row = $query->fetch();
$this->link_facebook = $row["url"];
$query= $pdo->query('SELECT url FROM links WHERE title = "allegro"');
$row = $query->fetch();
$this->link_allegro = $row["url"];
$query->closeCursor();
}
}
//test.php
<?php
require_once('core.php');
$tmp = new getCore;
$tmp->getLinks();
echo $tmp->link_allegro;
echo $tmp->link_facebook;
You need to pass $pdo to the getLinks() function as an input to make it available for use. you could try getLinks($pdo)

Setting up a database connection class in PHP

I was recently introduced to the idea of classes in PHP, and after some research I've come to the conclusion that I need to store database related functions in a class to access later. It has worked for the most part, but some use cases I am still confused with. For example,
Below is an example of how I would normally connect to my database and display information from user id's in a table
dbcon.php:
<?php
$con = mysqli_connect("host","username","password","database") or die("Couldn't connect");
require_once("functions.php");
?>
functions.php
function getUserInfo($id) {
$query = mysqli_query($con, "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
}
Some random file:
require_once("dbcon.php");
$result = mysqli_query($con, "SELECT * FROM tablename");
while ($row = mysqli_fetch_assoc($result)) {
$userinfo = getUserInfo($row['userid']);
echo $userinfo['name'];
}
?>
I don't feel like this method of querying the database and displaying information is the neatest or most efficient way possible. I read this article about using classes to tamper with a database and call functions that I created in the class.
My first question is this: When I try to access $con in functions.php, it is undefined. How can I pass the variable from dbcon.php to functions.php over the require_once function?
I also would like to know what the best way to store my connection to the database is, and if there are any tutorials on how to set that up.
I hope you understood that lol.
You can do it like this way:-
Dbconnection.php:-
<?php
Class DbConnection{
function getdbconnect(){
$conn = mysqli_connect("host","username","password","database") or die("Couldn't connect");
return $conn;
}
}
?>
Function.php:-
<?php
require_once('Dbconnection.php');
Class WorkingExamples{
function getUserInfo($id) {
$Dbobj = new DbConnection();
$query = mysqli_query($Dbobj->getdbconnect(), "SELECT * FROM users WHERE id = '$id'");
return mysqli_fetch_array($query);
}
}
$data = new WorkingExamples();
echo "<pre/>";print_r($data->getUserInfo(3));
?>
Note:- this is an example, try it by changing values according to your requirement and get the result.
<?php
class DatabaseConnection
{
private $host = "127.0.0.1";
private $dbname = "online_english";
private $dbUsername = "root";
private $dbPass = "";
private $charset = 'utf8mb4';
private $dsn;
public function tryConnect(){
try{
$this->dsn = "mysql:host=$this->host;dbname=$this->dbname;charset=$this->charset";
$DBH = new PDO($this->dsn,$this->dbUsername,$this->dbPass);
$DBH->exec("set names utf8");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $DBH;
}
catch (PDOException $e){
$e->getMessage();
}
}
}
?>
<?php
class Database{
const DB_HOSTNAME = 'localhost';
const DB_USERNAME = 'root';
const DB_PASSWORD = 'root';
const DB_NAME = 'stockganesha';
public $_db_connect;
protected $_sql;
protected $_result;
protected $_row;
function db_connect(){
$this->_db_connect = mysqli_connect(self::DB_HOSTNAME,self::DB_USERNAME,self::DB_PASSWORD,self::DB_NAME) or die(mysql_error());
return $this->_db_connect;
}
function sql(){
$this->_sql = 'SELECT * FROM customers';
}
function query(){
$this->_result = mysqli_query($this->_db_connect,$this->_sql);
}
function fetch_array(){
while($this->_row = mysqli_fetch_array($this->_result)){
$username = $this->_row['first_name'];
echo "<ul>";
echo "<li>".$username."</li>";
echo "</ul>";
}
}
function db_close(){
mysqli_close($this->_db_connect);
}
}
and Import this in another class
<?php
require_once('../Config/Dbconnection.php');
include './model.php';
class CustomerDTO{
private $mysql;
function __construct() {
$database = new Database();
$this->mysql = $database->db_connect();
}
function create($customer){
$firstName = $customer->getFirstName();
$lastName = $customer->getLastName();
$emailId = $customer->getEmailId();
$mobileNumber = $customer->getMobileNumber();
$dateOfBirth = $customer->getDateOfBirth();
$phoneNumber = $customer->getPhoneNumber();
$termAndCondtion = $customer->getTermAndCondition();
$result = mysqli_query($this->mysql, "Insert into customers (first_name,last_name,email_id,mobile_number,date_of_birth,phone_number,term_and_condition)
values('$firstName','$lastName','$emailId','$mobileNumber','$dateOfBirth','$phoneNumber','$termAndCondtion')");
return $result;
}
function read(){
$result = mysqli_query( $this->mysql, "Select * from customers");
return $result;
}
function update($id, $customer){
$result = mysqli_query($this->mysql, "update customers set
first_name = ".$customer->getFirstName()."
last_name = ".$customer->getLastName()."
email_id = ".$customer->getEmailId()."
mobile_number = ".$customer->getMobileNumber()."
date_of_birth = ".$customer->getDateOfBirth()."
phone_number = ".$customer->getPhoneNumber()."
term_and_condition = ".$customer->getTermAndCondition()."
where id = ".$customer->getId());
return $result;
}
public function delete($id){
$result = mysqli_query($this->mysql, "delete from customers where id =".$id);
return $result;
}
}

DB class wont load

I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?

get record using if statment & pdo query in function php

i have problem with function pdo, when it will take 1 record from the database, the result is null;
connect.php
<?php
class dbConn{
protected static $db;
private function __construct() {
try {
self::$db = new PDO( 'mysql:host=localhost;dbname=item', 'root', '' );
self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e) {
echo "Connection Error " . $e->getMessage();
}
}
public static function getConnection() {
if (!self::$db) {
new dbConn();
}
return self::$db;
}
}
?>
function.php
<?php
include 'connect.php';
class ajax_table {
function detailitem($table){
$db = dbConn::getConnection();
$sql = "select * from ".$table."" or die(mysql_error());
$q = $db->query($sql) or die("failed!");
$res = $q->fetch(PDO::FETCH_ASSOC);
return $res;
//else echo "No records found";
}
}
?>
and to display
displayitem.php
<?php
$url = $_GET['url'];
$url=$url.'.html';
include 'connect.php';
include 'function.php';
$db = dbConn::getConnection();
$obj = new ajax_table();
$records = $obj->detailitem('product WHERE url = "$url"');
if($records){
echo $records['name'];
echo '<br>';
echo $records['type'];
}else{
echo 'no result';
} ?>
database is not empty, but result display
no error, and also does not display anything
If you see correctly on the following line :
$records = $obj->detailitem('product WHERE url = "$url"');
It passes the string as "$url" , not the value of $url variable.
So change it to :
$records = $obj->detailitem('product WHERE url = \''.$url.'\'');

Problems calling class function in another class function

I am trying to build my own little framework.
Now I am having problems calling class functions into another class function.
Users.php code
class User extends Connection{
public function __construct(Connection $conn, Log $log){
parent::__construct($log);
$this->conn = $conn;
}
public function generatePassword(){
$length = 12;
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$password = '';
for ($i = 0; $i < $length; $i++) {
$password .= $characters[rand(0, strlen($characters) - 1)];
}
return $password;
}
public function generateToken(){
$token = md5(uniqid(mt_rand(), true));
return $token;
}
public function checkUsername($prefix, $username){
echo "test";
}
}
$user = new User($conn, $log);
$conn = new Connection($log);
connection.php code
<?php
class Connection{
private $log;
private $db;
public function __construct(Log $log){
$this->log = $log;
$this->createConnection();
}
public function createConnection(){
$dataConnection = $this->getConnection();
$host = $dataConnection['localhost'];
$dbname = $dataConnection['dbname'];
$user = $dataConnection['user'];
$pass = $dataConnection['pass'];
try{
$this->db = new PDO('mysql:host='.$host.';dbname='.$dbname.'',$user,$pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->log->insertLog("installer","Trying to connect to database");
} catch(PDOException $e){
$this->errorHandling($e->getCode());
}
}
public function errorHandling($error){
switch ($error){
case 2002:
$this->log->insertLog("installer","Installer error code 2002: Host unknown");
return ('Host unkown');
break;
case 1049:
$this->log->insertLog("installer","Installer error code 1049: Database does not exist");
return ('Database does not exist');
break;
case 1045:
$this->log->insertLog("installer","Installer error code 1045: Could not connect to database");
return ('Could nog connect to database');
break;
}
}
public function getConnection(){
$xml = simplexml_load_file("config/config.xml");
$dataConnection = array();
$dataConnection['localhost'] = $xml->host;
$dataConnection['dbname'] = $xml->dbname;
$dataConnection['user'] = $xml->user;
$dataConnection['pass'] = $xml->pass;
return $dataConnection;
}
public function query($sql){
try {
$this->db->exec($sql);
} catch(PDOException $e) {
$this->errorHandling($e->getCode());
}
}
public function select($sql){
try{
$result = $this->db->prepare($sql);
$result->execute();
return $result->fetchAll();
} catch(PDOException $e){
$this->errorHandling($e->getCode());
}
}
}
$conn = new Connection($log);
$log = new Log();
Log.php code
<?php
class Log{
public function createLog($file){
$date = date("dmY");
$location = 'var/log/'.$file.'-'.$date.'.log';
if (!file_exists($location)){
$file = fopen($location, 'w');
$message = "/** LOG FILE CREATED **/\n";
file_put_contents($location,$message, FILE_APPEND);
fclose($file);
}
return $location;
}
public function insertLog($file,$message){
$date = date("d-m-Y H:i:s", time());
$location = $this->createLog($file);
$message = $date." - ".$message."\n";
file_put_contents($location, $message, FILE_APPEND);
}
}
$log = new Log();
Now when I am trying to call the function checkUsername on user.php (will be used to check if the username already exists in db) I get the error:
Notice: Undefined variable: log in
/opt/www/decocka2/web/www.anthonydecock.be/core/conn/connection.php on
line 77
Catchable fatal error: Argument 1 passed to Connection::__construct()
must be an instance of Log, null given, called in
/opt/www/decocka2/web/www.anthonydecock.be/core/conn/connection.php on
line 77 and defined in
/opt/www/decocka2/web/www.anthonydecock.be/core/conn/connection.php on
line 7
What am I doing wrong?
Try to create the connection and the log object before the user object.

Categories