需要两次添加配置文件

时间:2014-02-08 21:33:53

标签: php

这个问题自2周以来一直令我担忧。

代码: -

<?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();

?>

问题: - 问题是,我需要两次包含此 dbconnector.php 文件。如果我不在函数括号中包含它,则会抛出错误。如果文件包含在功能块中,则一切正常。

这里有什么问题?

感谢。

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

require_once '../dbconnector.php';

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

答案 1 :(得分:0)

从我在代码中看到的内容,您永远不会定义$db所以我认为它是在dbconnector.php文件中定义的。在这种情况下,由于您是从function之外设置的,因此您可以执行以下两项操作之一:

  1. 将其设置为全局变量:

    <?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. 在函数调用中设置它:

    <?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
    
    ?>