Can't call the function in PHP - php

I am having a problem with my index.php. Whenever I go to http://localhost/blog/admin/index.php I get an error:
Fatal error: Call to undefined function Blog\DB\connect() in C:\xampp\htdocs\blog\blog.php on line 6.
In the admin folder all I am requiring is my blog.php which is working fine in other files when I required them. I am stuck with this and can not understand why this is happening.
index.php in admin folder
My admin/index.php:
<?php
require '../blog.php';
My blog.php. It is requiring the db.php in which we have called the connect function.
<?php
require 'db.php';
$conn = \App\DB\connect($config);
if(!$conn)
die('Could not connect to db');
My db.php. It is just trying to establish a connection:
<?php namespace App\DB;
require 'config.php';
function connect($config)
{
try
{
$conn = new \PDO("mysql:host=localhost;dbname=blogs",
$config['DB_USERNAME'],
$config['DB_PASSWORD']);
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $conn;
}
catch(PDOException $e)
{
return false;
}
}

Related

PHP 7.2 - Include file cannot access another include file

I am having an issue with an include file accessing another include file (my db connection)
I have a site with the following layout ::
root/conn.php :: db connection file
root/site/file1.php :: regular page
root/site/include/func.inc :: file with functions in it
Each file is listed below with appropriate code...
conn.php ::
<?php
$host = 'localhost';
$db = 'mydb';
$user = 'myuser';
$pass = 'mypass';
$charset = 'utf8mb4';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$conn = new mysqli($host, $user, $pass, $db);
$conn->set_charset($charset);
} catch (\mysqli_sql_exception $e) {
throw new \mysqli_sql_exception($e->getMessage(), $e->getCode());
}
unset($host, $db, $user, $pass, $charset);
?>
file1.php ::
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
include_once ("{$_SERVER['DOCUMENT_ROOT']}/site/include/func.inc");
{ code that calls functions in func.php }
func.inc ::
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
{ various functions }
When I browse to /file1.php, I get the following error ::
PHP Notice: Undefined variable: conn in C:\inetpub\root\site\include\func.inc on line 231
PHP Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\inetpub\root\site\include\func.inc:231
my func.inc file cannot seem to find the conn.php file. I have also tried removing the include function from func.inc. There are other files in the /include folder that can access the conn.php file with the same include function.
The issue relates to something called the variable scope (https://www.php.net/manual/en/language.variables.scope.php)
==> Please read that to get detailed information
The second example describes your problem
func.inc
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
// to illustrate the issue, the include can be simplified to
// $conn = "something"; // => global scope variable
function myFunc(){
echo $conn; //no output - $conn exists ONLY in the local scope --> not available inside thisfunction
}
Solution 1:
func.inc
<?php
function myFunc($conn){
echo $conn; //outputs $conn
}
file1.php
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
include_once ("{$_SERVER['DOCUMENT_ROOT']}/site/include/func.inc");
//call function and pass the $conn, it's available here in the global scope
myFunc($conn);
Solution 2
but keep in mind global is considered as bad practice
func.inc
<?php
include_once ("{$_SERVER['DOCUMENT_ROOT']}/conn.php");
function myFunc(){
global $conn; //$conn is declared global in the local scope of this function
echo $conn; //outputs $conn from conn.php if you call myFunc from anywhere
}

PHP - Create PDO Connection using namespace

I have a project folder name utilities.
The list of directory is:
- utilities
- tli
- database
Connection.php
index.php
The Connection.php is PDOConnection.
The code is:
<?php
namespace app\tli\database;
use PDO;
use PDOException;
Class Connection
{
private $server = "mysql:host=localhost;dbname=ytsurumaru_hanwa_coil_v.2";
private $user = "root";
private $pass = "";
private $options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,);
protected $con;
public function openConnection()
{
try {
$this->con = new PDO($this->server, $this->user, $this->pass, $this->options);
return $this->con;
} catch (PDOException $e) {
return "There is some problem in connection: " . $e->getMessage();
}
}
public function closeConnection()
{
$this->con = null;
}
}
UPDATED SOURCE
Now, I need this Connection instance in index.php
<?php
namespace app;
use app\tli\database\Connection;
use PDOException as PDOEx;
require('tli/database/Connection.php');
try {
$connection = new Connection(); // not found
$connection->openConnection();
} catch (PDOEx $e) {
echo $e->getMessage();
}
When I run it,
D:\wamp64\www\utilities\tli>php index.php
Warning: require(tli/database/Connection.php): failed to open stream: No such file or directory in D:\wamp64\www\utilities\tli\index.php on line 8
Fatal error: require(): Failed opening required 'tli/database/Connection.php' (include_path='.;C:\php\pear') in D:\wamp64\www\utilities\tli\index.php on line 8
How to solved this, is my namepace have a problem ?
Isn't this enough to access your database connection?
require 'tli/database/Connection.php';
Then, since you are in a different name space and you are not aliasing, in your 'try catch block' you should instead of:
$connection = new Connection(); // not found
Do something like:
$connection = new \tli\database\Connection();
Make sure to set your paths right.
OR
You can alias to a different name like so:
namespace app;
require 'tli/database/Connection.php';
use tli\database\Connection as MyConnection;
$connection = new MyConnection();
You need to use one of these:
include('tli/database/Connection.php')
include_once('tli/database/Connection.php')
require('tli/database/Connection.php')
require_once('tli/database/Connection.php')
or if you want some more automation use autoloader.
You may want to look at this SO question and all the linked things.

php/mysql - PHP function cannot detect mysql connection, when fixing the error becomes too many connection

I have function.php
function functionname() {
include_once ("connection.php");
// Do Something
return $variable
}
And a connection.php that goes as follows
<?php
try{
$db = new PDO ('mysql:host=localhost;dbname=project', 'root', '');
}
catch (PDOException $ex){
echo "Error!:" . $ex -> getMessage() . " Cannot Connect";
}
?>
I've been trying to run a php function but it's can't detect the MySql connection. If I try making include_once into just include inside the function.php the error becomes too many connection.
The connection works except when use inside a function. I've been trying to run the function.php into a seperate thirdPHPpage.php through the following code
include_once ("connection.php");
include_once ("functions.php");
$string = functionname();
echo $string;

why am i getting a php fatal error for calling the same function twice?

https://plnkr.co/edit/ZNlAyky7TzT4jknpnoDJ?p=preview
here is a link to a plnkr with all my code written so far. I keep getting an
Fatal error: Cannot redeclare connect_to_db() (previously declared in
/var/www/html/News/config/dbconnect.php:5) in
/var/www/html/News/config/dbconnect.php on line 5
the plunkr wont have the folder structure because i could not figure out how to add folders however here is my code for dbconnect.php
<?php
$pdo = null;
function connect_to_db()
{
$dbengine = 'mysql';
$dbhost = 'localhost';
$dbuser = 'root';
$dbpassword = 'password';
$dbname = 'news';
try{
$pdo = new PDO("".$dbengine.":host=$dbhost; dbname=$dbname", $dbuser,$dbpassword);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
return $pdo;
}
catch (PDOException $e){
$e->getMessage();
}
}
line 5 does not have a call to db connect so i dont know what is going on
You are using
require __DIR__.'/dbconnect.php'
In both your Index.php and your functions.php, while requiring your functions.php in Index.php.
Therefore connect_to_db() is being defined twice. Use require_once instead to prevent this:
require_once __DIR__.'/dbconnect.php'
http://php.net/manual/en/function.require-once.php

Cannot redeclare class in PHP error

new to PHP. Using the SLIM framework and the routing has been tested and is working fine. Have two files index.php and API.php. index.php is:
<?php
require 'vendor/autoload.php';
require_once 'API.php';
//Turn on error checking
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
//Create a new SLIM app
$app = new \Slim\Slim();
$app->response->headers->set('Content-Type', 'application/json');
$app->get('/', function() use($app) {
$app->response->setStatus(200);
echo "InstaAPI\n";
});
$app->run();
?>
API is:
<?php
class DbHandler{
protected static $conn;
function __construct() {
//Static self notation is different
if(!isset(self::$conn)) {
//same as self.connect
$this->connect();
}
}
function __destruct(){
if(isset(self::$conn)){
self::$conn->close();
}
}
function connect(){
$config = parse_ini_file('../../config2.ini');
// Try and connect to the database
self::$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(self::$conn===FALSE) {
header("HTTP/1.1 500 Internal Server Error");
header("Content-Type: application/json");
$response = array("Response"=>"Failed to connect to the database");
echo json_encode($response);
die();
}
else{
echo "Fine!!";
}
}//end connect
}//end class
?>
I am getting the error: PHP Fatal error: Cannot redeclare class DbHandler in ../API.php on line 62. Not sure why this is happening. I am using require_once and still getting the same error. Could someone give me some pointers to what I might be doing wrong please?
the code of Api.php is less than 62 lines. looks like there is extra code below it. consider deleting extra lines

Categories