致命错误:未捕获错误:在var / www中调用未定义的function_name()

时间:2016-09-21 23:05:11

标签: php mysql pdo

大家好我正在使用类进行PDO连接后的插入过程。 Everythings OK fot连接和显示。但是当我在类中创建新函数并为插入过程输入类型命令时,我得到了这个错误行:

  

致命错误:未捕获错误:在/var/www/html/test/index.php:29中调用未定义函数db_connection_function()堆栈跟踪:#0 /var/www/html/test/index.php(48 ):在第29行的/var/www/html/test/index.php中抛出了connection-> add_member_to_table()#1 {main}

这个函数给我错误

public function add_member_to_table() {
    $this->query = db_connection_function()->prepare("INSERT INTO users(username, password) VALUES('onur', 'turali')");
    $this->query->execute();

    if($this->query == true) {
        echo "Member registered";
    } else {
        echo "Error";
    }
}

我试过$ this-> connection_db_link ....我想尝试输入函数名而不是connection_db_link(连接到mysql的函数名)但是我认为这是无用的。那么我该如何解决这个问题呢?

我的源代码:

<?php
    class connection{
        public $connection_db_link;
        public $db_host = "localhost";
        public $db_user = "root";
        public $db_pass = "Antalya07Ragnar";
        public $db_name = "test";

        public function db_connection_function(){
            try{
                $this -> connection_db_link = new PDO("mysql:host=$this->db_host;$this->db_name", $this->db_user, $this->db_pass);
                $this->connection_db_link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                return $this->connection_db_link;
            }catch(PDOException $e){
                echo "Error: ".$e->getMessage();
            }
        }

        public $query;

        public function add_member_to_table(){
            $this->query = db_connection_function()->prepare("INSERT INTO users(username, password) VALUES('onur', 'turali')");
            $this->query->execute();
            if($this->query == true){
                echo "Member registered";
            }else{
                echo "Error";
            }
        }

        public function display_connection(){
            if($this->connection_db_link == true){
                echo "Connection success";
            }
        }
    }

    $user = new connection;
    $user->db_connection_function();
    $user->display_connection();
    $user->add_member_to_table();
    ?>

1 个答案:

答案 0 :(得分:3)

修改

在add_member_to_table()函数中,将db_connection_function()更改为$this->db_connection_function()

在尝试使用db_connection_function()函数之前,应验证您是否已成功连接到数据库。

您的PDO连接语句缺失dbname=,应该是这样的:

$this->connection_db_link = new PDO('mysql:host=$this->db_host;dbname=$this->db_name', $this->db_user, $this->db_pass);

在您确定之后,prepare语句的工作方式如下:

$stmt = $dbh->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);

// insert one row
$name = 'onur';
$value = 'turali';
$stmt->execute();