Postingan lainnya
Error metode insert oop php
Saya mengikuti yang ada di video php oop bagian membuat metode insert, namun mendapatkan error:
Fatal error: Uncaught Error: Call to a member function insert() on null in C:\MAMP\htdocs\auth\classes\User.php:14 Stack trace: #0 C:\MAMP\htdocs\auth\register.php(9): User->register_user(Array) #1 {main} thrown in C:\MAMP\htdocs\auth\classes\User.php on line 14
<?php
class User{
private $_db;
public function __construct()
{
$this->_db = Database::getInstance();
}
public function register_user($fields = array()){
var_dump($fields);
if($this->_db->insert('users', $fields)) return true;
else return false;
}
}
?>
public function insert($table, $fields = array()){
//mengambil kolom
$column = implode(",", array_keys($fields));
//mengambil nilai
$valueArrays = array();
$i = 0;
foreach ($fields as $key => $value) {
if(is_int($value)){
$valueArrays[$i] = $value;
}
else{
$valueArrays[$i] = "'" . $value . "'";
}
$i++;
}
$values = implode(",", $valueArrays);
$query = "INSERT INTO $table ($column) VALUES ($values)";
if($this->mysqli->query($query)) return true;
else return false;
}
Tanggapan
coba var_dump $this->_db nya pastikan nilainya sudah benar
terimakasih bang, solved
1 Jawaban:
Jawaban Terpilih
Bagi yang mengalami hal serupa, pastikan $this->_db nya sudah benar, ternyata saya lupa memberi tanda seru (!) sebelum isset dan lupa me-return self::INSTANCE;
Sebelum: <pre> public static function getInstance(){ if(isset(self::$INSTANCE)){ self::$INSTANCE = new Database(); } } </pre>
Sesudah: <pre> public static function getInstance(){ if(!isset(self::$INSTANCE)){ self::$INSTANCE = new Database(); } return self::$INSTANCE; } </pre>
Tanggapan
terima kasih sudah sharing jawabannya