我正在尝试用 PHP 实现 Active Record 模式;我有以下代码
<?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();
}
?>
但是,当我尝试运行代码时,以下行出现错误
$db->insert(array('firstname'=>'Sebas','lastname'=>'Guajardo','email'=>'tururus@domain.com'),'users');
我没有看到语法错误,我几乎直接从这个页面中获取了这个例子。我的数据库(在 MySQL 上实现)的名称是“pruebalabo”,表的名称是“users”。
编辑:修正错误指出。仍然出现错误。