方法名称必须是字符串致命错误类

时间:2016-01-03 18:59:46

标签: php mysql class web mysqli

如何修复此代码?当我运行check.php时出现此错误:

  

Erorr:致命错误:方法名称必须是第46行的C:\ AppServ \ www \ Weboo \ cms \ check.php中的字符串

<?php
    ob_start();
    session_start();
    class mysql {


        private $localhost = "localhost";
        private $db_user = "root";
        private $db_pass = "root";
        private $db_name ="webocms";


        function __construct(){

        mysql_connect($this-> localhost,$this->db_user,$this->db_pass);
        mysql_select_db($this->db_name);
        }

    }

    function sql(){

        $username = $_POST ['username'];
        $password = $_POST['password'];

        $sql = "SELECT * from users WHERE username='$username'
         AND password='$password'";

         $query = mysql_query($sql);

         $num = mysql_num_rows($query);

         if ($num > 1){

            $_SESSION['username'] = "username";
            $_SESSION['password'] = "password";

            header("Location: admin/admin.php");
         }else {

            echo "<h2><b> No Users </h2></b>";
         }
    }

    $use=new mysql;
    $use->$sql();
    ob_end_flush();
    ?>

2 个答案:

答案 0 :(得分:0)

我认为你在mysql课程的结束时犯了一个错误。 sql()是一个函数,而不是mysql类的方法。你也使用了一个我觉得无意中的变量。

相反,它应该是$use->sql();,但是在你将sql()放入课堂之前,这将无效。

答案 1 :(得分:0)

正如马克在评论中所说,我认为应该更像这样:

<?php
    ob_start();
    session_start();
    class mysql {

        private $localhost = "localhost";
        private $db_user = "root";
        private $db_pass = "root";
        private $db_name ="webocms";

        function __construct(){
            mysql_connect($this-> localhost,$this->db_user,$this->db_pass);
            mysql_select_db($this->db_name);
        }

        function sql(){

            $username = $_POST ['username'];
            $password = $_POST['password'];

            $sql = "SELECT * from users WHERE username='$username'
                AND password='$password'";

            $query = mysql_query($sql);

            $num = mysql_num_rows($query);

            if ($num > 1){

                $_SESSION['username'] = "username";
                $_SESSION['password'] = "password";

                header("Location: admin/admin.php");
            } else {

                echo "<h2><b> No Users </h2></b>";
            }
        }
    }


    $use=new mysql;
    $use->sql();
    ob_end_flush();
?>

注意,sql()函数现在在您的类中,而倒数第二行是$use->sql()而不是$use->$sql()

希望这有帮助。