我試圖用PHP實現活動記錄模式;我有以下代碼執行查詢INSERT INTO與活動記錄模式時出錯
<?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'=>'[email protected]'),'users');
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
?>
當我嘗試運行代碼,不過,我得到一個錯誤與以下行
$db->insert(array('firstname'=>'Sebas','lastname'=>'Guajardo','email'=>'[email protected]'),'users');
我沒有看到語法錯誤,和我直接從this頁面拿到了這個例子。我的數據庫的名稱(在MySQL上實現)是'pruebalabo',表名是'users'。
編輯:修正了錯誤指出。仍然出現錯誤。
您遇到的錯誤是什麼? – andrewsi
@andrewsi執行查詢INSERT INTO用戶(名,姓,電子郵件)時出錯VALUES(Sebas','Guajardo','[email protected]) –