需要两次添加配置文件

This problem has been worrying me since 2 weeks.

Code :-

<?php
session_start();
include '../dbconnector.php';

function getRandUsername()
{
    include '../dbconnector.php';
    $u = rand(0,99999);
    //check if the number exists in the database already
    $query="SELECT * from admin where username = '" . $u . "'";
    $result=mysql_query($query,$db) or die (mysql_error($db));
    if(mysql_num_rows($result) > 0)
    {
        echo "Username Exists";
        getRandUsername();
        exit();
    }
    else
    {
        echo "Username Does not exist";
    }
}

getRandUsername();

?>

Problem :- The problem is, that I need to include this dbconnector.php file twice. If I don't include it within the function parentheses, it would throw an error. While if the file is include in the function block, everything works fine.

What's wrong in here?

Thanks.

Try the following:

require_once '../dbconnector.php';

function getRandUsername() {
    global $db;    // where I'm assuming that $db is defined in the external file

From what I can see in your code, you never define $db so I assume that it is defined in your dbconnector.php file. In this case, since you are setting it from outside a function, you can do one of two things:

  1. Set it as a global variable:

    <?php
    session_start();
    include '../dbconnector.php';
    $GLOBALS['db'] = $db; //Sets it as global
    
    function getRandUsername()
    {
        $db = $GLOBALS['db'] //Receives it as global
        include '../dbconnector.php';
        $u = rand(0,99999);
        //check if the number exists in the database already
        $query="SELECT * from admin where username = '" . $u . "'";
        $result=mysql_query($query,$db) or die (mysql_error($db));
        if(mysql_num_rows($result) > 0)
        {
            echo "Username Exists";
            getRandUsername();
            exit();
        }
        else
        {
            echo "Username Does not exist";
        }
    }
    
    getRandUsername();
    
    ?>
    
  2. Set it in the function call:

    <?php
    session_start();
    include '../dbconnector.php';
    
    function getRandUsername($db)
    {
        include '../dbconnector.php';
        $u = rand(0,99999);
        //check if the number exists in the database already
        $query="SELECT * from admin where username = '" . $u . "'";
        $result=mysql_query($query,$db) or die (mysql_error($db));
        if(mysql_num_rows($result) > 0)
        {
            echo "Username Exists";
            getRandUsername();
            exit();
        }
        else
        {
            echo "Username Does not exist";
        }
    }
    
    getRandUsername($db); //Passes the value to the function
    
    ?>