嗨,大家好我正在使用類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();
?>
,是你的你的類中的方法,它的'$ this-> db_connection_function()'爲什麼不只是在構造函數中創建它,而只是用它作爲屬性而不是 – Ghost
當我需要爲sql過程做準備時,我總是使用函數進行連接。因爲我在準備命令之前調用了函數。但如果連接函數在另一個文件中,我使用構造函數。這是我知道的好方法。但它的PDO連接使用類,它真的強迫我。 – Onur
每次調用函數時都不應創建新的連接。你應該檢查'$ this-> connection_db_link'是否已經設置,然後返回該變量而不是打開一個新的連接。 – Barmar