大家好,本人初轉php,想建立一個pdo串連的資料庫操作類,但是不知道php的調用方法,請大家指點下。
類檔案coon.php內容:
query("SET NAMES UTF8");$dbh->exec("SET NAMES UTF8");}catch(Exception $e) { echo 'data error: '.$e->getMessage(); }}//關閉資料庫連接public function sql_close(){$dbh=null;}//查詢資料庫public function my_query($sql){$this->sql_open();//$this->sth = $this->dbh->query($sql); //$result = $this->sth->fetchAll(); //return $result; 這裡面怎麼寫才能返回資料?}}?>
頁面調用代碼:
my_query('SELECT * FROM user_type order by user_id') as $row){//這裡迴圈輸出查詢內容}$mysql->sql_close();?>
望詳細指點下,實在弄不明白,用asp或asp.net的函數調用方法全不行,我想寫一個查詢,插入,更新和刪除資料的通用函數,外部只要帶入sql語句就可以執行的那種。
回複討論(解決方案)
1樓圍觀。等大神解答!
$this->dbh = new PDO($dsn, $user, $pass);
你的my_query看上去沒錯,將注釋的那幾行開啟。先試試看。
終於搞定了,看了網上眾多代碼,測試失敗了無數次,結果是弄出來了,插入,刪除,更新的通用類,請大神指點下這樣做有沒有什麼弊端,會不會影響效能等。下一步研究下那個參數化,據說可以防止sql注入。
conn.php內容:
dsn, $this->user,$this->pass);$dbh->query("SET NAMES UTF8"); return $dbh->query($sql); $dbh=null;}catch(Exception $e) { echo 'error: '.$e->getMessage(); }}//操作單條資料(更新/刪除/插入),無返回結果public function sql_one($sql){try{$dbh = new PDO($this->dsn, $this->user,$this->pass);$dbh->exec("SET NAMES UTF8"); $dbh->exec($sql); $dbh=null;}catch(Exception $e) { echo 'error: '.$e->getMessage(); }}//操作多條資料(更新/刪除),無返回結果public function sql_more($sql,$str){try{$dbh = new PDO($this->dsn, $this->user,$this->pass);$dbh->exec("SET NAMES UTF8"); foreach($str as $arrs) { $dbh->exec($sql.$arrs); }$dbh=null;}catch(Exception $e) { echo 'error: '.$e->getMessage(); }}}?>
頁面調用函數:
include 'conn.php';$mysql = new my_sql;//操作單挑資料$mysql->sql_one("DELETE FROM `user_type` WHERE `user_id` = ".$_REQUEST['id']."");//讀取內容$aa=$mysql->sql_select('SELECT * FROM user_type order by user_id'); foreach ($aa as $row) {//輸出內容echo '';echo ''.$row['user_id'].''.$row['user_name'].''.$row['user_real_name'].''.$row['user_sex'].''.$row['user_tel'].''.$row['user_qq'].''.$row['user_address'].''.$row['user_email'].'刪除';echo '';}//操作多條資料$id=$_POST['delAll'];if(isset($id)){$mysql->sql_more("DELETE FROM `user_type` WHERE `user_id` = ",$id);}
上面的操作方法和思路還是沿襲了asp.net開發的習慣,不知道在php開發上實用不,望大神指點一下。
你現在這個不能防注入,防注入需要用PDO::prepare
prepare('SELECT name, colour, calories FROM fruit WHERE calories < ? AND colour = ?');$sth->execute(array(150, 'red'));$red = $sth->fetchAll();$sth->execute(array(175, 'yellow'));$yellow = $sth->fetchAll();?>
你現在這個不能防注入,防注入需要用PDO::prepare
prepare('SELECT name, colour, calories FROM fruit WHERE calories < ? AND colour = ?');$sth->execute(array(150, 'red'));$red = $sth->fetchAll();$sth->execute(array(175, 'yellow'));$yellow = $sth->fetchAll();?>
你說的這個方法我已經會弄了,參數化查詢