I keep getting a fatal error message “Fatal error: Call to a member function save() on a non-object”
Here is my code. If anyone can help me figure this out it would be great. I am new to OOP (its a harder transition from procedural than I thought it would be!)
[code=php]
<?php
define (“DB_USER” , “#######”); // Insert database username
define (“DB_PASSWORD” , “#######”); // Insert database password
define (“DB_HOST” , “localhost”); // Insert database host
define (“DB_NAME” , “#######”); // Insert database name
Class Contact extends AbstractModel {
protected $dbc;
protected $_user = array();
public function __construct() {
//Connect to the Database
@$dbc=new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$this->dbc = $dbc;
if(mysqli_connect_errno()) {
die(‘The connection to the database could not be established.’);
}
} // End of Constructor Function
public function load($id) { // Runs a SELECT Query and stores in array
$q = “SELECT id, name, email FROM contacts WHERE id=’$id'”;
$r = $this->dbc->query($q);
$user = $r->fetch_array(MYSQLI_ASSOC);
$this->_user = $user;
}
public function getData($key = false) { // Returns data
if ($key) {
return $this->_user[”.$key.”];
}else{
return $this->_user;
}
}
public function setData($arr, $value=false) { // UPDATES rows in the database
$temp =
if (is_array($arr)) {
$new = array_merge($this->_user, $arr);
$this->_user = $new;
}else{
$this->_user[$arr] = $arr[$value];
}
}
public function save() {
if ($this->_user[‘id’]) {
$q = “UPDATE contacts SET name=’$this->_user[‘name’]’, email=’$this->_user[’email’]’ WHERE id=$this->_user[‘id’]”;
$r = $this->dbc->query($q);
}else{
$q = “INSERT INTO contacts (name, email) VALUES (‘$this->_user[‘name’]’, ‘$this->_user[’email’])”;
$r = $this->dbc->query($q);
}
}
public function delete($id) {
}
}
and here is the code I am running:
[code=php]
$contact->setData(‘name’, ‘John Walker’)->save(); //Should run an UPDATE query
echo ‘<br/><br/>’;
print_r($contact->load(1)->getData());
//Should print
// id => 1,
// name => John Walker
// email => [email protected]
$contact->setData(array(
“id” => 1,
“name” => “John Doe the 2nd”,
“email” => “[email protected]”
))->save();
echo ‘<br/><br/>’;
print_r($contact->load(1)->getData());
//Should print
// id => 1,
// name => John Doe the 2nd
// email => [email protected]