php搜索數(shù)據(jù)庫接口寫法,php數(shù)據(jù)庫api接口

php中怎么把數(shù)據(jù)庫連接寫成一個接口

我自己封裝的一個

在連城等地區(qū),都構建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務理念,為客戶提供網(wǎng)站制作、網(wǎng)站設計 網(wǎng)站設計制作按需搭建網(wǎng)站,公司網(wǎng)站建設,企業(yè)網(wǎng)站建設,品牌網(wǎng)站制作,營銷型網(wǎng)站,外貿(mào)營銷網(wǎng)站建設,連城網(wǎng)站建設費用合理。

?php

class AppConfig{

public static $dbParam = array(

'dbHost' = 'localhost',

'dbUser' = 'root',

'dbPassword' ='',

'dbName' = '數(shù)據(jù)庫名',

'dbCharset' = 'utf8',

'dbPort' = 3306,

'dbPrefix' = 'test_',

'dbPconnect' = 0,

'dbDebug' = true,

);

}

class Model {

private $version = ''; //mysql版本

private $config = array(); //數(shù)據(jù)庫配置數(shù)組

private $class; //當前類名

public $tablepre = 'ts_'; //表前綴

public $db = ''; //庫名

public $table = ''; //表名

private static $link; //數(shù)據(jù)庫鏈接句柄

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

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

private $fields = array(); //字段信息

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

public $primaryKey = 'id'; //表主鍵

//構造函數(shù)初始化

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

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

$this-connect();

$this-init();

}

//鏈接數(shù)據(jù)庫

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;

}

//插入數(shù)據(jù)

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();

}

//更新數(shù)據(jù)

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();

}

//刪除數(shù)據(jù)

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();

}

//查詢數(shù)據(jù)

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));

}

//查詢一條數(shù)據(jù)

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

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

if($data) {

return $data[0];

}

return array();

}

//查詢多條數(shù)據(jù)

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

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

return $data;

}

//結果數(shù)量

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;

}

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

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);

}

//清空操作數(shù)據(jù)

$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 等返回一個資源標識符的語句得到返回結果數(shù)組

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

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

}

// 使用call函數(shù)處理同類型函數(shù)

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);

}

//返回受影響行數(shù)

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?。?!');

}

//獲取時間微妙數(shù)

private function microtime_float()

{

list($usec, $sec) = explode(" ", microtime());

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

}

//析構函數(shù)

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();

//---------------------------------------插入數(shù)據(jù)方法一-----------------------------------------

//模擬ActiveRecord模式 插入數(shù)據(jù)

$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";

}

//---------------------------------------插入數(shù)據(jù)方法二-----------------------------------------

//直接數(shù)組做參數(shù)插入數(shù)據(jù)

$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";

}

//---------------------------------------更新數(shù)據(jù)方法一----------------------------------------

$userObj-username = 'h111oho';

$userObj-passwd = '1478511122';

$userObj-email = 'qsf111ia@163.com';

$userObj-sex = 1;

$userObj-desc = '清潔工';

$affectedRows1 = $userObj-update(89);

if ($affectedRows1 0) {

echo "影響行數(shù)為:{$affectedRows1}BR";

}

//---------------------------------------更新數(shù)據(jù)方法二----------------------------------------

//更新記錄(傳遞參數(shù)的方式和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 "影響行數(shù)為:{$affectedRows}BR";

}

//----------------------------------------查詢數(shù)據(jù)----------------------------------------------

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

//print_r($userRs0);

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

//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);

//----------------------------------------刪除數(shù)據(jù)-----------------------------------------------

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

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

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

$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); //獲取特殊查詢的結果,第二個參數(shù)代表返回一條結果還是所有的結果

PHP中寫一個數(shù)據(jù)庫查詢的類的方法代碼要如何寫

?php

if(!defined("INCLUDE_MYSQL_OK")) {

define("INCLUDE_MYSQL_OK","");

class MySQL_class {

var $debug = true;

var $db,

$id,

$result, /* 查詢結果指針 */

$rows, /* 查詢結果行數(shù) */

$fields, /* 查詢結果列數(shù) */

$data, /* 數(shù)據(jù)結果 */

$arows, /* 發(fā)生作用的紀錄行數(shù)目 */

$iid; /* 上次插入操作后,可能存在的"AUTO_INCREMENT"屬性字段的值,如果為"0",則為空 */

var $user, $pass, $host, $charset;

/*

* 請注意用戶名和密碼是否正確

*/

function Setup ($host, $user, $pass, $charset='utf8') {

$this-host = $host;

$this-user = $user;

$this-pass = $pass;

$this-charset = $charset;

}

function Connect ($db = "") {

global $CFG_MYSQL_INFO;

if (!$this-host) {

$this-host = $CFG_MYSQL_INFO["host"];

}

if (!$this-user) {

$this-user = $CFG_MYSQL_INFO["user"]; /* 在這里作修改 */

}

if (!$this-pass) {

$this-pass = $CFG_MYSQL_INFO["passwd"]; /* 在這里作修改 */

}

if (!$this-charset) {

$this-charset = "utf8"; /* 在這里作修改 */

}

if (empty($db))

$this-db = $CFG_MYSQL_INFO["database"];

else

$this-db = $db;

$this-id = @mysql_connect($this-host, $this-user, $this-pass);

if (!$this-id)

return false;

$this-SelectDB($this-db); /* 定位到指定數(shù)據(jù)庫 */

$this-Query("SET NAMES '".$this-charset."'");

return true;

}

function Close(){

@mysql_close($this-id);

}

function SelectDB ($db) {

if(!@mysql_select_db($db, $this-id))

return false;

else

return true;

}

function Begin () {

$this-result = @mysql_query("START TRANSACTION WITH CONSISTENT SNAPSHOT", $this-id);

if (!$this-result)

return false;

return true;

}

function Commit () {

$this-result = @mysql_query("COMMIT", $this-id);

if (!$this-result)

return false;

return true;

}

function Rollback () {

$this-result = @mysql_query("ROLLBACK", $this-id);

if (!$this-result)

return false;

return true;

}

function Escape ($str) {

$escstr = mysql_escape_string($str);

return $escstr;

}

# 普通查詢功能,主要用于返回結果是多條記錄的情況

# 請使用 Fetch 方法取得每條記錄信息

function Query ($query) {

$this-result = @mysql_query($query, $this-id);

if (!$this-result)

{

if ($this-debug)

MySQL_ErrorMsg ("不能執(zhí)行查詢(query): $query");

else

return false;

}

$this-rows = @mysql_num_rows($this-result);

$this-fields = @mysql_num_fields($this-result);

if (!$this-rows) return false;

return true;

}

function QuerySql ($query) {

$ret = @mysql_query($query, $this-id);

if ($ret === false)

{

if ($this-debug)

MySQL_ErrorMsg ("不能執(zhí)行查詢(query): $query");

else

return false;

}

$this-result = $ret;

$this-rows = @mysql_num_rows($this-result);

$this-fields = @mysql_num_fields($this-result);

return true;

}

# 如果查詢結果為單條記錄時使用,返回結果存儲于數(shù)組 data 中

function QueryRow ($query) {

$this-result = @mysql_query($query, $this-id);

if (!$this-result)

{

if ($this-debug)

MySQL_ErrorMsg ("不能執(zhí)行查詢(query): $query");

else

return false;

}

$this-rows = @mysql_num_rows($this-result);

$this-data = @mysql_fetch_array($this-result, MYSQL_ASSOC);

//MySQL_ErrorMsg ("不能從查詢結果中取得數(shù)據(jù) $query");

if (!$this-result || !$this-rows)

return false;

return true;

}

# 移動到指定記錄行,將該行結果儲存于數(shù)組 data 中

function Fetch ($row) {

if(!@mysql_data_seek($this-result, $row))

//MySQL_ErrorMsg ("不能定位到指定數(shù)據(jù)行 $row");

return false;

$this-data = @mysql_fetch_array($this-result, MYSQL_ASSOC);

//MySQL_ErrorMsg ("不能提取指定數(shù)據(jù)行數(shù)據(jù) $row");

if (!$this-data)

return false;

return true;

}

/* 以下方法將作用于 arows */

/* 此方法將作用于 iid */

function Insert ($query) {

$this-result = @mysql_query($query, $this-id);

if (!$this-result)

{

if ($this-debug)

MySQL_ErrorMsg ("不能執(zhí)行查詢(query): $query");

else

return false;

}

$this-arows = @mysql_affected_rows($this-id);

$this-iid = @mysql_insert_id($this-id);

return true;

}

function Update ($query) {

$this-result = @mysql_query($query, $this-id);

if (!$this-result)

{

if ($this-debug)

MySQL_ErrorMsg ("不能執(zhí)行查詢(query): $query");

else

return false;

}

$this-arows = @mysql_affected_rows($this-id);

if (!$this-arows || $this-arows == -1)

return false;

return true;

}

function Delete ($query) {

$this-result = @mysql_query($query, $this-id);

if (!$this-result)

{

if ($this-debug)

MySQL_ErrorMsg ("不能執(zhí)行查詢(query): $query");

else

return false;

}

$this-arows = @mysql_affected_rows($this-id);

return true;

}

function Error (){

return mysql_error()."(".mysql_errno().")";

}

function Errno (){

return mysql_errno();

}

}

/*

* MySQL_ErrorMsg

* 輸出錯誤信息

*/

function MySQL_ErrorMsg ($msg) {

# 關閉可能影響字符顯示的HTML代碼

echo("/ul/dl/ol\n");

echo("/table/script\n");

# 錯誤信息

$text = "font color=\"#000000\" style=\"font-size: 9pt; line-height: 12pt\"p系統(tǒng)提示:".$msg."br";

$text .= "錯誤信息:";

$text .= mysql_error()."br";

$text .= "錯誤代碼:".mysql_errno()."brbr";

$text .= "請稍候再試,如果問題仍然存在,請與 a href=\"mailto:wuqiong@igenus.org\"系統(tǒng)管理員/a 聯(lián)系!";

$text .= "/font\n";

die($text);

}

}

?

一些細節(jié)的地方自己修改吧 主要是我在別的文件專門定義了全局變量,你看一遍,把應改的地方改一下就好了

PHP文本數(shù)據(jù)庫的搜索方法

PHP文本數(shù)據(jù)庫的搜索方法

searchstr=("/".preg_quote($searchstr)."/");

//$searchstr是查找的關鍵字

$records=file($file);//獲取所有的記錄數(shù)

//$file是查找的數(shù)據(jù)文件

$search_reocrds=preg_grep

($searchstr,

$records);//開始查找記錄

//$search_reocrds為查找到的記錄數(shù)

unset($records);

if($search_records){

//開始顯示記錄,寫下你自己的處理程序********************

while

(list

($key,

$val)

=

each

(

$search_records))

{

echo

"$val

";

}

//****************************************************

}

網(wǎng)頁名稱:php搜索數(shù)據(jù)庫接口寫法,php數(shù)據(jù)庫api接口
當前URL:http://muchs.cn/article20/hcjjco.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供建站公司響應式網(wǎng)站、自適應網(wǎng)站網(wǎng)站策劃、網(wǎng)站維護、網(wǎng)站建設

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

h5響應式網(wǎng)站建設