Onur Onur - 2 months ago 5
MySQL Question

Fatal error: Uncaught Error: Call to undefined function_name() in var/www

Hi guys I am working on insert process after PDO connection using class. Everythings OK fot connection and displaying. But when I created new function in class and typed commands for insert process I've got this error line:


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


This function gives me error

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


I tried $this-> connection_db_link.... I wanted try to type function name instead of connection_db_link(function name for connect to mysql) But this is useless I think. So How do I fix this problem?

My source codes:

<?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();
?>

Answer

Edit:

In the add_member_to_table() function, change db_connection_function() to $this->db_connection_function()


Before you attempt to use the db_connection_function() function, you should verify that you were successfully connected to the database.

Your PDO connection statement is missing dbname= and should look like this instead:

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

After you're sure, the prepare statement works like this:

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