php的資料庫介面(php的資料庫介面框架)

本文目錄一覽:

pdo是什麼意思?

PDO(PHP Data Objects)是一種在PHP里連接資料庫的使用介面。PDO與mysqli曾經被建議用來取代原本PHP在用的mysql相關函數,基於資料庫使用的安全性,因為後者欠缺對於SQL注入的防護。

PHP 數據對象(PDO) 擴展為PHP訪問資料庫定義了一個輕量級的一致介面。實現 PDO 介面的每個資料庫驅動可以公開具體資料庫的特性作為標準擴展功能。 注意利用 PDO 擴展自身並不能實現任何資料庫功能;必須使用一個具體資料庫的 PDO 驅動來訪問資料庫服務。

相關信息:

PDO 提供了一個數據訪問抽象層,這意味著,不管使用哪種資料庫,都可以用相同的函數(方法)來查詢和獲取數據。 PDO不提供資料庫抽象層;它不會重寫 SQL,也不會模擬缺失的特性。如果需要的話,應該使用一個成熟的抽象層。

從 PHP 5.1開始附帶了 PDO,在 PHP 5.0 中是作為一個 PECL 擴展使用。 PDO 需要PHP 5核心的新OO特性,因此不能在較早版本的 PHP 上運行。

php中怎麼把資料庫連接寫成一個介面

我自己封裝的一個

?php

class AppConfig{

public static $dbParam = array(

‘dbHost’ = ‘localhost’,

‘dbUser’ = ‘root’,

‘dbPassword’ =”,

‘dbName’ = ‘資料庫名’,

‘dbCharset’ = ‘utf8’,

‘dbPort’ = 3306,

‘dbPrefix’ = ‘test_’,

‘dbPconnect’ = 0,

‘dbDebug’ = true,

);

}

class Model {

private $version = ”; //mysql版本

private $config = array(); //資料庫配置數組

private $class; //當前類名

public $tablepre = ‘ts_’; //表前綴

public $db = ”; //庫名

public $table = ”; //表名

private static $link; //資料庫鏈接句柄

private $data = array(); //中間數據容器

private $condition = ”; //查詢條件

private $fields = array(); //欄位信息

private $sql = array(); //sql集合,調試用

public $primaryKey = ‘id’; //表主鍵

//構造函數初始化

public function __construct($dbParam = array()) {

$this-config = (is_array($dbParam) !empty($dbParam)) ? $dbParam : AppConfig::$dbParam;

$this-connect();

$this-init();

}

//鏈接資料庫

private function connect() {

if($this-config[‘dbPconnect’]) {

self::$link = @mysql_pconnect($this-config[‘dbHost’], $this-config[‘dbUser’], $this-config[‘dbPassword’]);

}else{

self::$link = @mysql_connect($this-config[‘dbHost’], $this-config[‘dbUser’], $this-config[‘dbPassword’], true);

}

mysql_errno(self::$link) != 0 $this-errdie(‘Could not connect Mysql: ‘);

$this-db= !empty($this-db) ? $this-db : $this-config[‘dbName’];

$serverinfo = $this-version();

if ($serverinfo ‘4.1’ $this-config[‘dbCharset’]) {

mysql_query(“SET character_set_connection=”.$this-config[‘dbCharset’].”,character_set_results=”.$this-config[‘dbCharset’].”,character_set_client=binary”, self::$link);

}

if ($serverinfo ‘5.0’) {

mysql_query(“SET sql_mode=””, self::$link);

}

@mysql_select_db($this-db, self::$link) or $this-errdie(‘Cannot use database’);

return self::$link;

}

//表基本信息初始化

protected function init() {

$this-class = get_class($this);

$this-table = !empty($this-table) ? $this-table : strtolower($this-class);

$this-table = $this-tablepre . $this-table;

return $this;

}

//設置屬性值

public function __set($name, $value) {

//exit($value);

$this-data[‘fields’][$name] = $value;

}

//獲取屬性值

public function __get($name) {

if(isset($this-data[‘fields’][$name])) {

return($this-data[‘fields’][$name]);

}else {

return NULL;

}

}

//欄位信息處理

private function implodefields($data) {

if (!is_array($data)) {

$data = array();

}

$this-fields = !empty($this-data[‘fields’]) ? array_merge($this-data[‘fields’], $data) : $data;

foreach($this-fields as $key = $value) {

$fieldsNameValueStr[] = “`$key`=’$value'”;

$fieldsNameStr[] = “`$key`”;

$fieldsValueStr[] = “‘$value'”;

}

return array($fieldsNameValueStr, $fieldsNameStr, $fieldsValueStr);

}

//條件判斷組裝

private function condition($where = NULL) {

if (is_numeric($where)) {

$where = “WHERE `{$this-primaryKey}`='{$where}’ LIMIT 1”;

}elseif (is_array($where)){

$where = “WHERE `{$this-primaryKey}` in (“.implode(‘,’,$where).”)”;

}elseif(!empty($this-data[‘condition’])){

//’預留WHERE’, ‘order’, ‘group’, ‘limit’ …………等條件關鍵詞處理介面

$where = $where ? “WHERE {$where}” : “WHERE 1”;

isset($this-data[‘condition’][‘where’]) $where .= ‘ AND ‘.$this-data[‘condition’][‘where’];

isset($this-data[‘condition’][‘group’]) $where .= ‘ GROUP BY ‘.$this-data[‘condition’][‘group’];

isset($this-data[‘condition’][‘order’]) $where .= ‘ ORDER BY ‘.$this-data[‘condition’][‘order’];

isset($this-data[‘condition’][‘limit’]) $where .= ‘ LIMIT ‘.$this-data[‘condition’][‘limit’];

}else{

$where = “WHERE {$where}”;

}

$this-condition = $where;

return $this;

}

//插入數據

public function insert($data = array(), $replace = false) {

$fields = $this-implodefields($data);

$insert = $replace ? ‘REPLACE’ : ‘INSERT’;

$sql = “{$insert} INTO `{$this-db}`.`{$this-table}` (“.implode(‘, ‘,$fields[1]).”) values (“.implode(‘, ‘,$fields[2]).”)”;

$this-query($sql);

return $this-getInsertId();

}

//更新數據

public function update($data = array() ,$where = ”) {

$numargs = func_num_args();

if ($numargs == 1) {

$where = $data;

$data = array();

}

$fields = $this-implodefields($data);

$this-condition($where);

$sql = “UPDATE `{$this-db}`.`{$this-table}` SET “.implode(‘, ‘,$fields[0]).” {$this-condition}”;

$this-query($sql);

return $this-getAffectedRows();

}

//刪除數據

public function delete($where = NULL) {

if(!is_array($where) strtolower(substr(trim($where), 0, 6)) == ‘delete’){

$sql = $where;

}else{

$this-condition($where);

$sql = “DELETE FROM `{$this-db}`.`{$this-table}` {$this-condition}”;

}

$this-query($sql);

return $this-getAffectedRows();

}

//查詢數據

public function select($where = NULL, $fields = ‘*’) {

if(!is_array($where) strtolower(substr(trim($where), 0, 6)) == ‘select’){

$sql = $where;

}else{

$this-condition($where);

$sql = “SELECT {$fields} FROM `{$this-db}`.`{$this-table}` {$this-condition}”;

}

return $this-fetch($this-query($sql));

}

//查詢一條數據

public function getOne($where, $fields = ‘*’) {

$data = $this-select($where, $fields = ‘*’);

if($data) {

return $data[0];

}

return array();

}

//查詢多條數據

public function getAll($where, $fields = ‘*’) {

$data = $this-select($where, $fields = ‘*’);

return $data;

}

//結果數量

public function getCount($where = ”, $fields = ‘*’) {

$this-condition($where);

$sql = “SELECT count({$fields}) as count FROM `{$this-db}`.`{$this-table}` {$this-condition}”;

$data = $this-query($sql);

if($data){

return @mysql_result($data,0);

}

return 0;

}

//執行sql語句(flag為0返回mysql_query查詢後的結果,為1返回lastid,其他返回影響行數,默認為2返回影響行數)

public function query($sql, $flag = ‘0’, $type = ”) {

if ($this-config[‘dbDebug’]) {

$startime = $this-microtime_float();

}

//查詢

if ($type == ‘UNBUFFERED’ function_exists(‘mysql_unbuffered_query’)) {

$result = @mysql_unbuffered_query($sql, self::$link);

} else {

//exit($sql);

$result = @mysql_query($sql, self::$link);

}

//重試

if (in_array(mysql_errno(self::$link), array(2006,2013)) empty($result) $this-config[‘dbPconnect’]==0 !defined(‘RETRY’)) {

define(‘RETRY’,true); @mysql_close(self::$link); sleep(2);

$this-connect();

$result = $this-query($sql);

}

if ($result === false) {

$this-errdie($sql);

}

if ($this-config[‘dbDebug’]) {

$endtime = $this-microtime_float();

$this-sql[] = array($sql,$endtime-$startime);

}

//清空操作數據

$this-data = array();

return $flag == ‘0’ ? $result : ($flag == ‘1’ ? $this-getInsertId() : $this-getAffectedRows());

}

//返回結果$onlyone為true返回一條否則返回所有,$type有MYSQL_ASSOC,MYSQL_NUM,MYSQL_BOTH

public function fetch($result, $onlyone = false, $type = MYSQL_ASSOC) {

if($result){

if ($onlyone) {

$row = @mysql_fetch_array($result, $type);

return $row;

}else{

$rowsRs = array();

while($row=@mysql_fetch_array($result, $type)) {

$rowsRs[] = $row;

}

return $rowsRs;

}

}

return array();

}

//可以運行SELECT,SHOW,EXPLAIN 或 DESCRIBE 等返回一個資源標識符的語句得到返回結果數組

public function show($sql, $onlyone = false) {

return $this-fetch($this-query($sql), $onlyone);

}

// 使用call函數處理同類型函數

private function __call($name, $arguments) {

$callArr = array(‘on’, ‘where’, ‘order’, ‘between’, ‘group’, ‘limit’);

if (in_array($name, $callArr)) {

$this-data[‘condition’][$name] = $arguments[0];

}else{

$this-errdie(“function error: function {$name} is not in ($this-class) class exist”);

}

return $this;

}

//返回最後一次插入ID

public function getInsertId() {

return @mysql_insert_id(self::$link);

}

//返回受影響行數

public function getAffectedRows() {

return @mysql_affected_rows(self::$link);

}

//獲取錯誤信息

private function error() {

return ((self::$link) ? @mysql_error(self::$link) : @mysql_error());

}

//獲取錯誤信息ID

private function errno() {

return ((self::$link) ? @mysql_errno(self::$link) : @mysql_errno());

}

//獲取版本信息

function version() {

if(empty($this-version)) {

$this-version = mysql_get_server_info(self::$link);

}

return $this-version;

}

//列印錯誤信息

private function errdie($sql = ”) {

if ($this-config[‘dbDebug’]) {

die(‘/BRBMySQL ERROR/B/BR

SQL:’.$sql.’/BR

ERRNO:’.$this-errno().’/BR

ERROR:’.$this-error().’/BR’);

}

die(‘DB ERROR!!!’);

}

//獲取時間微妙數

private function microtime_float()

{

list($usec, $sec) = explode(” “, microtime());

return ((float)$usec + (float)$sec);

}

//析構函數

public function __destruct() {

echo ‘hr’;

$this-config[‘dbDebug’] print_r($this-sql);

//unset($this-result);

//unset($this-condition);

//unset($this-data);

}

}

class user extends Model {

//public $db = ‘qsf_mvc’;

//public $table = ‘user’;

public $primaryKey = ‘uid’;

}

$userObj = new user();

//—————————————插入數據方法一—————————————–

//模擬ActiveRecord模式 插入數據

$userObj-username = ‘hoho’;

$userObj-passwd = ‘1478522’;

$userObj-email = ‘qsf.z11@163.com’;

$userObj-sex = 1;

$userObj-desc = ‘清潔工’;

$insetId = $userObj-insert();

if ($insetId 0) {

echo “插入ID為:{$insetId}BR”;

}

//—————————————插入數據方法二—————————————–

//直接數組做參數插入數據

$userArr = array(

‘username’ = ‘hoho’,

‘passwd’ = ‘1478522’,

’email’ = ‘qsf.z2121ia@163.com’,

‘sex’ = ‘1’,

‘desc’ = ‘廚師’,

);

$insetId = $userObj-insert($userArr);

if ($insetId 0) {

echo “插入ID為:{$insetId}BR”;

}

//—————————————更新數據方法一—————————————-

$userObj-username = ‘h111oho’;

$userObj-passwd = ‘1478511122’;

$userObj-email = ‘qsf111ia@163.com’;

$userObj-sex = 1;

$userObj-desc = ‘清潔工’;

$affectedRows1 = $userObj-update(89);

if ($affectedRows1 0) {

echo “影響行數為:{$affectedRows1}BR”;

}

//—————————————更新數據方法二—————————————-

//更新記錄(傳遞參數的方式和insert操作一樣)

$userArr = array(

‘username’ = ‘hohoho’,

‘passwd’ = ‘1474rr4448522’,

’email’ = ‘qsf.rrza@165.com’,

‘sex’ = ‘0’,

‘desc’ = ‘廚師qq’,

);

$affectedRows = $userObj-update($userArr, $insetId);

if ($affectedRows 0) {

echo “影響行數為:{$affectedRows}BR”;

}

//—————————————-查詢數據———————————————-

$userRs0 = $userObj-select(8); //單個主鍵值

//print_r($userRs0);

$userRs1 = $userObj-select(array(1,5,8)); //多個主鍵值的數組

//print_r($userRs1);

$userRs2 = $userObj-select(‘select count(*) as count from user where uid 20’); //直接完整sql語句

//print_r($userRs2);

$userRs3 = $userObj-select(“`uid` 0”); //where條件

//print_r($userRs3);

$userRs4 = $userObj-getOne(“`uid` 0”); //獲取單條記錄

//print_r($userRs4);

$usersRs5 = $userObj-getAll(“`uid` 0”); ////獲取所有記錄

//print_r($usersRs5);

$usersRs6 = $userObj-limit(‘0,10’)-where(‘uid 100’)-order(‘uid DESC’)-group(‘username’)-select();

//print_r($usersRs6);

//—————————————-刪除數據———————————————–

//刪除操作傳遞參數的方式和select操作一樣

$userObj-delete(60); //單個主鍵值

$userObj-delete(array(1,5,8)); //多個主鍵值的數組

$userObj-delete(‘delete from user where uid 100’); //直接完整sql語句

$userObj-delete(“`uid` 100”); //where條件

$userObj-limit(‘5’)-where(‘uid 80’)-delete();

//—————————————-特殊查詢———————————————–

$userShowRs = $userObj-show(‘show create table user’, true); //獲取特殊查詢的結果,第二個參數代表返回一條結果還是所有的結果

php 怎麼訪問介面

統一的數據訪問介面PDO

PDO(PHP Data Objects) 擴展為 PHP 訪問資料庫定義了一個輕量級的、一致性的介面,它提供了一個數據訪問抽象層,這樣,無論使用什麼資料庫,用戶都可以通過統一的函數執行來查詢和獲取數據。注意,你並不能使用 PDO 擴展本身執行任何資料庫操作,必須使用一個 database-specific PDO driver (針對特定資料庫的 PDO 驅動)訪問資料庫伺服器。

js如何用php去接收資料庫中的數據

要用javascript調用php獲取資料庫介面,是一個很常見的前後端交互操作

通過javascript發送http請求php的API介面,php連接資料庫並查詢結果,最後返回出來

這樣javascript就能獲取到資料庫的數據

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/258065.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-15 12:48
下一篇 2024-12-15 12:48

相關推薦

  • PHP和Python哪個好找工作?

    PHP和Python都是非常流行的編程語言,它們被廣泛應用於不同領域的開發中。但是,在考慮擇業方向的時候,很多人都會有一個問題:PHP和Python哪個好找工作?這篇文章將從多個方…

    編程 2025-04-29
  • Ojlat:一款快速開發Web應用程序的框架

    Ojlat是一款用於快速開發Web應用程序的框架。它的主要特點是高效、易用、可擴展且功能齊全。通過Ojlat,開發人員可以輕鬆地構建出高質量的Web應用程序。本文將從多個方面對Oj…

    編程 2025-04-29
  • Zlios——一個多功能的開發框架

    你是否在開發過程中常常遇到同樣的問題,需要不斷去尋找解決方案?你是否想要一個多功能、易於使用的開發框架來解決這些問題?那麼,Zlios就是你需要的框架。 一、簡介 Zlios是一個…

    編程 2025-04-29
  • Python 常用資料庫有哪些?

    在Python編程中,資料庫是不可或缺的一部分。隨著互聯網應用的不斷擴大,處理海量數據已成為一種趨勢。Python有許多成熟的資料庫管理系統,接下來我們將從多個方面介紹Python…

    編程 2025-04-29
  • openeuler安裝資料庫方案

    本文將介紹在openeuler操作系統中安裝資料庫的方案,並提供代碼示例。 一、安裝MariaDB 下面介紹如何在openeuler中安裝MariaDB。 1、更新軟體源 sudo…

    編程 2025-04-29
  • agavi開發框架

    Agavi是一個基於MVC模式的Web應用程序開發框架,以REST和面向資源的設計為核心思想。本文章將從Agavi的概念、優點、使用方法和實例等方面進行詳細介紹。 一、概念 Aga…

    編程 2025-04-29
  • Python unittest框架用法介紹

    Python unittest框架是Python自帶的一種測試框架,可以用來編寫並運行測試用例。在本文中,我們將從以下幾個方面詳細介紹Python unittest框架的使用方法和…

    編程 2025-04-29
  • com.alipay.sofa.bolt框架

    com.alipay.sofa.bolt框架是一款高性能、輕量級、可擴展的RPC框架。其廣泛被應用於阿里集團內部服務以及阿里雲上的服務。該框架通過NIO支持高並發,同時還內置了多種…

    編程 2025-04-29
  • PHP怎麼接幣

    想要在自己的網站或應用中接受比特幣等加密貨幣的支付,就需要對該加密貨幣擁有一定的了解,並使用對應的API進行開發。本文將從多個方面詳細闡述如何使用PHP接受加密貨幣的支付。 一、環…

    編程 2025-04-29
  • 資料庫第三範式會有刪除插入異常

    如果沒有正確設計資料庫,第三範式可能導致刪除和插入異常。以下是詳細解釋: 一、什麼是第三範式和範式理論? 範式理論是關係資料庫中的一個規範化過程。第三範式是範式理論中的一種常見形式…

    編程 2025-04-29

發表回復

登錄後才能評論