如何使用php调用单独的函数文件?

时间:2019-04-29 10:20:00

标签: php mysql database

好吧,所以我只是在学习使用php编程,似乎所有教程都没有提到有关拥有functions.php文件和单独的db_connect.php文件的内容。我需要帮助,因此我正在尝试建立学生管理系统。我进行了登录和注销,它们正常工作,并且个人资料页面显示了用户名。但是现在,例如,当我想查看所提供的所有课程时,如何从一个单独的文件中查看呢?并在profile.php文件中调用它。

functions.php类:

<?php


    class Functions{
            private $link;

            public function __construct(){
                //require_once dirname(__FILE__) returns the path of the current directory


                global $link;
                $this->link = $link;
            }

            public function viewAllCourses(){
             $stmt = $this->link->prepare("SELECT * FROM courses where active = 1");
                    $stmt->execute();
                    $stmt->fetch();


                $stmt->store_result(); 
                if($stmt->num_rows > 0){
                    while($row = $stmt->fetch_assoc()){
                        echo $row['course_num'] . "<br>";
                        echo $row['professor_teaching'] . "<br>";
                        echo $row['name'] . "<br>";
                    }
                }
            }
    }
?>

然后这是我在profile.php文件中称呼它的段:

<?php
    require('functions.php');
    $functions = new Functions();

    echo $functions->viewAllCourses();
?>

我希望它打印课程,但我排名第n。我在做什么错了?

2 个答案:

答案 0 :(得分:0)

通常,将数据库连接对象作为参数添加到Function类的构造函数中,而不是像您那样使用global调用,因此您可以像这样重写Functions类:

<?php

    class Functions{
        private $link;

        public function __construct( $link ){
            $this->link = $link;
        }

        public function viewAllCourses(){

            $sql='select * from `courses` where `active` = 1';
            $res = $this->link->query( $sql );

            if( $res ){
                while( $rs=$res->fetch_object() ){
                    printf(
                        '%s<br />%s<br />%s<br />',
                        $rs->course_num,
                        $rs->professor_teaching,
                        $rs->name
                    )
                }
                return true;
            }
            return false;
        }

    } //end class
?>

viewAllCourses方法不需要准备好的语句,因为没有使用用户提供的数据,因此在运行时无法篡改sql,因此简单的query就足够了。

打电话给班级

<?php
    /* include the necessary files */
    require 'db_connect.php';
    require 'functions.php';

    /* construct the db connection to supply as an argument to the Functions class */
    $db=new db_connect();

    /* invoke the functions class */
    $fn = new Functions( $db );

    /* the `viewAllCourses` method echoes the output */
    $fn->viewAllCourses();
?>

答案 1 :(得分:-1)

只需删除$ functions-> viewAllCourses();之前的回声即可

相关问题