I’m trying to implement the Active Record Pattern with PHP; I have the following code
<?php
// define 'MySQL' class
class users{
private $result;
public function __construct($host='localhost',$user='user',$password='password',$database='pruebalabo'){
// connect to MySQL and select database
if(!($conId = @mysql_connect("127.0.0.1","root",""))){
throw new Exception('Error connecting to the server');
}
if(!mysql_select_db("pruebalabo",$conId)){
throw new Exception('Error selecting database');
}
}
// run SQL query
public function query($query){
if(!$this->result=mysql_query($query)){
throw new Exception('Error performing query '.$query);
}
}
// fetch one row
public function fetchRow(){
while($row=mysql_fetch_array($this->result)){
return $row;
}
return false;
}
// fetch all rows
public function fetchAll($table='users'){
$this->query('SELECT * FROM '.$table);
$rows=array();
while($row=$this->fetchRow()){
$rows[]=$row;
}
return $rows;
}
// insert row
public function insert($params=array(),$table='default_table'){
$sql='INSERT INTO '.$table.' ('.implode(',', array_keys($params)).') VALUES ('.implode("','",array_values($params)).')';
$this->query($sql);
}
}
try{
// connect to MySQL and select a database
$db=new users("host","root","","pruebalabo");
$result=$db->fetchAll('users');
foreach($result as $row){
echo $row['firstname'].' '.$row['lastname'].' '.$row['email'].'<br />';
}
// connect to MySQL and select a database
$db=new users("127.0.0.1","root","","pruebalabo");
// insert new row into selected MySQL table
$db->insert(array('firstname'=>'Sebas','lastname'=>'Guajardo','email'=>'tururus@domain.com'),'users');
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
?>
When I try to run the code, though, I get an error with the following line
$db->insert(array('firstname'=>'Sebas','lastname'=>'Guajardo','email'=>'tururus@domain.com'),'users');
I don’t see an error in the syntax, and I took the example pretty much straight from this page. The name of my database (implemented on MySQL) is ‘pruebalabo’, and the name of the table is ‘users’.
EDIT: Fixed mistake pointed out. Still getting an error.
Change your insert function as below