How to fix Fatal error: Cannot redeclare connectdb() - php

I am new for PHP and MYSQL. I have tried some learnings using xampp. when I try to connect database with the script it shows below error.. this showing on index.php
Fatal error: Cannot redeclare connectdb() (previously declared in
C:\xampp1\htdocs\core.php:18) in C:\xampp1\htdocs\core.php on line 24
I have a search on google and try to fix this. but it's not worked...
core.php line 18th to 24 th codes as follows.
function connectdb()
{
global $dbname, $dbuser, $dbhost, $dbpass;`
$conms = #mysql_connect($dbhost,$dbuser,$dbpass); //connect mysql`
if(!$conms) return false;`
$condb = #mysql_select_db($dbname);`
if(!$condb) return false;`
return true;`
}
config.php codes as follows
$dbname = "aw"; //change to your mysql database name
$dbhost = "localhost"; //database host name
$dbuser = "sam";
$dbpass = "1234";
$max_buds=100; //maximum number of buds
$topic_af = 120; //topic antiflood
$post_af = 45; //post antiflood
$onver = true; //isonline versoion
$timeadjust = (0 * 60 * 60); // 4 hours
putenv("TZ=Africa/Johannesburg");

It's called "include guard":
if(!function_exists('connectdb')) {
function connectdb() {
}
}

I think the issue that connectdb function already loaded.
Try use include_once instead of include.
example:
include_once 'Functions.php';
The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included just once.
https://www.php.net/manual/en/function.include-once.php

Try replacing your connectdb function with the following code:
if (!function_exists('connectdb')) {
function connectdb()
{
global $dbname, $dbuser, $dbhost, $dbpass;
$conms = #mysql_connect($dbhost,$dbuser,$dbpass); //connect mysql
if (!$conms) return false;
$condb = #mysql_select_db($dbname);
if (!$condb) return false;
return true;
}
}
It will only create the function if it does not exist.

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
}

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

Should objects be created chronologically as class defined?

I am having a strange error while creating objects. While I create an objects in chronological orders as classed defined, it is going on good. But when I change the order or object creation, it gives error.
The classes I am using are as follows:
<?php
class dbClass{
private $dbHost, $dbUser, $dbPass, $dbName, $connection;
function __construct(){
require_once("system/configuration.php");
$this->dbHost = $database_host;
$this->dbUser = $database_username;
$this->dbPass = $database_password;
$this->dbName = $database_name;
}
function __destruct(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
function mysqlConnect(){
$this->connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass) or die("MySQL connection failed!");
mysql_select_db($this->dbName,$this->connection);
}
function mysqlClose(){
if(!$this->connection){
} else{
mysql_close($this->connection);
}
}
}
class siteInfo{
private $wTitle, $wName, $wUrl;
function __construct(){
require_once("system/configuration.php");
$this->wTitle = $website_title;
$this->wName = $website_name;
$this->wUrl = $website_url;
}
function __destruct(){
}
function showInfo($keyword){
if($keyword=="wTitle"){
return $this->wTitle;
}
if($keyword=="wName"){
return $this->wName;
}
if($keyword=="wUrl"){
return $this->wUrl;
}
}
}
?>
The problem is when I create objects in the following order, it is working perfectly:
include("system/systemClass.php");
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
$siteInfo = new siteInfo();
But if I change the order to following
include("system/systemClass.php");
$siteInfo = new siteInfo();
$dbConnection = new dbClass();
$dbConnection -> mysqlConnect();
It gives error!
Warning: mysql_connect() [function.mysql-connect]: Access denied for user '#####'#'localhost' (using password: NO) in /home/#####/public_html/#####/system/systemClass.php on line 19
MySQL connection failed!
Your problem comes from the unconventional use of a configuration file that is read ONCE, but should be used in all classes.
When you instantiate the dbclass first, the configuration is read, probably variables get assigned, and you use these in the constructor.
After that, instantiating siteinfo will not read that file again, which is less harmful, because you only end up with an empty object that does return a lot of null, but does work.
The other way round, you get a siteinfo object with all the info, but a nonworking dbclass.
My advice: Don't use a configuration file that way.
First step: Remove the require_once - you need that file to be read multiple times.
Second step: Don't read the file in the constructor. Add one or more parameters to the constructor function and pass the values you want to be used from the outside.
Info: You can use PHP code files that configure stuff, but you shouldn't define variables in them that get used outside. This will work equally well:
// configuration.php
return array(
'database_host' => "127.0.0.1",
'database_user' => "root",
// ...
);
// using it:
$config = require('configuration.php'); // the variable now has the returned array

DB connections. SQL retrieve error

I define all my connections on an external file called db_config.php
This enables my class files to use db_config.php file for connections.
However, I am wondering if someone could shed some light on the following error.
SQL Retrieve Error: No database selected
This is referring to this line of code on db_config.php.
return array("host"=>"x", "username"=>"x", "password"=>"x", "dbname"=>"x" );
This is the function that makes the call
function openDB() {
$config = include_once("assets/configs/db_config.php");
$conn = mysqli_connect(
$config["host"] , $config["username"],
$config["password"], $config["dbname"]);
$this->conn = $conn;
return true;
}
What am I missing?
First of all make sure the variables in the config file are correct. If they are correct the try changing the include_once to include.
if that is not working, then change the code to :
function openDB() {
$config = array("host"=>"x", "username"=>"x", "password"=>"x", "dbname"=>"x" );
$conn = mysqli_connect(
$config["host"] , $config["username"],
$config["password"], $config["dbname"]);
$this->conn = $conn;
return true;
}
See if this works my way. If it does then your won't need the db.php file.
Please dump the $config variable and check what is going wrong ,
<?php
var_dump($config);
?>
So you can find $config is returning an array or not !

Trouble connecting to MySQL database using PHP

I have a 3 file:
class.database.php
config.php
test.php
In class.database.php i using:
<?php
class Database {
private $db_connect;
function __construct($config) {
$this->connect($config);
}
function connect($config) {
$this->db_connect = #mysql_connect($config['hostname'], $config['dbuser'], $config['dbpass']) or die("Can't connect to mysql server");
#mysql_select_db($config['dbname'], $this->db_connect) or die("Can't select database mysql server");
$this->query('set names utf8');
}
function disconnect() {
mysql_close($this->db_connect);
}
}
?>
in config.php i using:
<?php
include_once 'class.database.php';
$config['hostname'] = 'localhost';
$config['dbuser'] = 'root';
$config['dbpass'] = '';
$config['dbname'] = 'test';
$db = new Database($config);
?>
And test.php i using:
<?php
include 'config.php';
include 'class.database.php';
when to run test.php in wampserver is host alert error is Fatal error: Cannot redeclare class Database in class.database.php on line 2
How to fix it ?
You're includeing the class.database.php file twice, which gives this error. Use include_once for it always, not include.

Categories