Hello I've made a quick code to insert name into a database.
This is the class for database connection:
(I hide the passwords etc, basically i define them in the top)
class Database
{
private $pdo;
private $query;
public function __construct()
{
try
{
$this->pdo = new PDO('mysql:host='.MYSQL_HOST.';dbname=oop', MYSQL_USER, MYSQL_PASSWORD);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Sucessfully connected to MySQL server!';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function query($name)
{
$this->query = $this->pdo->prepare("INSERT INTO user (name) VALUES (:name)");
$this->query->bindValue(":name", $name);
$this->query->execute();
echo 'Sucessfully send!';
}
}
This is the class that I basically use the queries and process them from :
class System
{
private $Database;
public function __construct(Database $Database = null)
{
$this->Database = $Database;
}
public function insertName($name)
{
if ($this->db != null)
{
$this->db->query($name);
}
}
}
This is config.php
include("system.class.php");
include("db.class.php");
$system = new System($Database);
$db = new Database();
And this is index.php
<?php
include("config.php");
?>
<html>
<form action="" method="post">
<input type="text" name="name">
<input type="submit">
</form>
<?php
if (isset($_POST) && !empty($_POST['name']))
{
$Database->insertName($_POST['name']);
echo 'Scessfuly inserted!';
}
?>
</html>
Problem:
When sending the data (after submiting the form) I get the following error:
Fatal error: Call to a member function insertName() on a non-object in C:\xampp\htdocs\oop\index.php on line 17
What did I do wrong? This is line 17:
$Database->insertName($_POST['name']);
How can I fix this and what is the problem?
Thnaks.
After changing it from $db to the actual name of the class I get this:
Call to undefined method Database::insertName() in C:\xampp\htdocs\oop\index.php on line 17
EDIT:
if (isset($_POST) && !empty($_POST['name']))
{
$system->insertName($_POST['name']);
echo 'Scessfuly inserted!';
}
class System
{
private $Database;
public function __construct(Database $Database = null)
{
$this->Database = $Database;
}
public function insertName($name)
{
if ($this->Database != null)
{
$this->Database->query($name);
}
}
}