简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM