自己寫的一個基本的資料庫操作類,本來以為應該輕車熟路的,結果發現了很多問題,突然想起了一句話:很多事情你知道怎麼做和你會做之間是有很大差異的;所有搞技術的童鞋,應該以我未戒,不要在覺得會上犯了錯誤,哈哈!
總結哈:
1.以後就把CSDN當成個人的一個技術日志了,沒事發發動态玩,順便寫寫生活!
2.突然覺得搞技術的很多同僚說話好直接,還是要學會控制脾氣,不輕易對别人發脾氣,待人和善,學會和人打交道,不做技術宅男,不死鑽技術!
3.每天要早起啊,這段時間放縱自己了,今天起個早床,感慨萬千:每天早起一個小時,一年你就比别人多活了半個月,半個月的時間你可能又碰到了很多别人想不到的機會,差距就是這麼産生的,居安思危!
4.聽我廢話這麼多,看看我寫的哈,菜鳥一枚,最好是私聊我給點建議,哈哈!說不定我們就成了朋友了。我在深圳,你在哪?
<?php
class Mysql{
private $conn; //資料庫連接配接資源
private $error; //錯誤資訊
private $dbtype; //所連接配接資料庫類型
private $host; //主機名
private $dbname; //資料庫名
private $port; //連接配接端口号
private $user; //連接配接使用者名
private $pwd; //密碼
private $charset; //設定連接配接所采用的字元集
function __construct(){
//載入配置檔案
include './include/config.php';
$this->dbtype=$cfg['dbtype'];
$this->host=$cfg['host'];
$this->dbname=$cfg['dbname'];
$this->port=$cfg['port'];
$this->user=$cfg['user'];
$this->pwd=$cfg['pwd'];
$this->charset=$cfg['charset'];
try{
$conn=new PDO("$this->dbtype:host=$this->host;port=$this->port;dbname=$this->dbname",$this->user,$this->pwd);
$this->conn=$conn;
}catch(PDOException $e){
$this->error="資料庫連接配接不成功!".$e->getMessage()."<br>";
}
$this->conn->query("set names $this->charset");
}
//查詢所有行資料
public function getAll($sql){
$stmt=$this->conn->prepare($sql);
$result=$stmt->execute();
if($result){
$lists=$stmt->fetchAll(PDO::FETCH_ASSOC);
return $lists;
}else{
return false;
}
}
//删除方法
public function delete($sql){
$stmt=$this->conn->prepare($sql);
$result=$stmt->execute();
//用受影響的行數來作為判斷是否執行成功的條件
if($stmt->rowCount()){
return true;
}else{
return false;
}
}
//擷取單行資料
public function getRow($sql){
$stmt=$this->conn->prepare($sql);
$result=$stmt->execute();
if($result){
return $info=$stmt->fetch(PDO::FETCH_ASSOC);
}else{
return false;
}
}
//更新資料
public function update($sql){
$stmt=$this->conn->prepare($sql);
$stmt->execute();
if($stmt->rowCount()){
return true;
}else{
return false;
}
}
//插入一行資料
public function add($sql){
$stmt=$this->conn->prepare($sql);
$result=$stmt->execute();
if($stmt->rowCount()){
return $result;
}else{
return false;
}
}
//擷取錯誤資訊
public function getError(){
return $this->error();
}
}
?>