从另一个文件调用自定义php函数的正确方法

时间:2015-02-01 10:15:59

标签: php function

我想使用自定义函数,这些函数都位于一个名为functions.php的文件中,该文件位于includes文件夹中。

在functions.php中的自定义函数如下所示,当我删除函数nos_check () {}并单独加载functions.php时它似乎正在工作。

function nos_check() {
    require_once ('config.php');
    mysql_connect($hostname,$dbusername,$dbpassword);
    @mysql_select_db($dbname) or die ("Unable to select database");
    $sql = mysql_query("SELECT number_of_sites FROM sites WHERE user = '$currentUsername' ");
    $row = mysql_fetch_array($sql);
    // Assign how many sites the user has into a variable
    $how_many = $row['number_of_sites'];
    mysql_close();
        if ($how_many == 0) {
            echo 'You have no sites yet';
        } else {
            echo 'You have more than one site';
            }
    }

文件account.php将调用该函数:

include "includes/functions.php";
nos_check();

我想我可能错误地调用了函数,或者我可能包含函数文件错误了?

SOLUTION:

经过几个小时的讨论并阅读更多有关mysqli等的内容后,我意识到我实际遇到的唯一问题是脚本不知道$currentUsername是什么,因为它是global variable并且函数是不在php中自动包含它们。

通过将global $currentUsername;置于函数nos_check()

中,可以轻松修复错误

下面是一个重写并希望更好看的代码:

function nos_check() {
    require 'config.php';
    $con = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
    global $currentUsername;
    $query = "SELECT number_of_sites FROM sites WHERE user = '$currentUsername' ";
    $result = mysqli_query($con, $query);
    $row = mysqli_fetch_array($result, MYSQLI_NUM);
    mysqli_free_result($result);
    mysqli_close($con);

    if ($row[0] == 0) {
        echo 'You have no sites yet';
        } else {
            echo 'You have more than one site';
            }
    }

0 个答案:

没有答案