致命错误:未捕获错误:调用未定义的函数名()var/www

问题描述:

嗨,大家好我正在使用类PDO连接后的插入过程。万物都可以连接和显示。但是,当我在课堂上创造了新的功能和类型的插入过程的命令,我得到这个错误行:致命错误:未捕获错误:调用未定义的函数名()var/www

Fatal error: Uncaught Error: Call to undefined function db_connection_function() in /var/www/html/test/index.php:29 Stack trace: #0 /var/www/html/test/index.php(48): connection->add_member_to_table() #1 {main} thrown in /var/www/html/test/index.php on line 29

此功能给了我错误

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"; 
    } 
} 

我试过$这个 - > 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(); 
    ?> 
+0

,是你的你的类中的方法,它的'$ this-> db_connection_function()'为什么不只是在构造函数中创建它,而只是用它作为属性而不是 – Ghost

+0

当我需要为sql过程做准备时,我总是使用函数进行连接。因为我在准备命令之前调用了函数。但如果连接函数在另一个文件中,我使用构造函数。这是我知道的好方法。但它的PDO连接使用类,它真的强迫我。 – Onur

+0

每次调用函数时都不应创建新的连接。你应该检查'$ this-> connection_db_link'是否已经设置,然后返回该变量而不是打开一个新的连接。 – Barmar

编辑:

在add_member_to_table()函数,改变db_connection_function()$this->db_connection_function()


在您尝试使用db_connection_function()功能,你应该确认你已经成功连接到t他数据库。

你PDO连接语句丢失dbname=和看起来应该是这样,而不是:

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

后你肯定的是,准备的语句是这样的:

$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(); 
+0

谢谢!这是怎么回事?我认为这只适用于post方法。我摆脱了这种无知。再次感谢。 – Onur