资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

php连接数据库写接口 php建立数据库连接的代码

php连接access数据库代码

php教程

创新互联建站从2013年成立,是专业互联网技术服务公司,拥有项目成都做网站、网站制作、成都外贸网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元蒙阴做网站,已为上家服务,为蒙阴各地企业和个人服务,联系电话:18982081108

连接access数据库教程代码

下面提供三种php连接access数据库方法,一种是利用php的pdo,一种是odbc,com接口来与access数据库连接哦。

*/

//利用pdo与access数据库连接

$path

="f:font";

$conn

=

new

pdo("sqlite:$path");

if(

$conn

)

{

echo

('connection

pdo

success');

}

else

{

echo

('cnnection

pdo

fail

,plase

check

database

server!');

}

//利用

odbc_connect连接数据库

$conn

=

odbc_connect("dbdsn","admin","123");

//连接数据源

$doquery=odbc_exec($conn,"select

*

from

表名

where

条件");//执行查询

//利用com接口连接access数据库

$conn=new

com("adodb.connection");

$dsn="driver={microsoft

access

driver

(*.mdb)};dbq=".realpath("path/db1.mdb");

$conn-open($dsn);

PHP网站怎么连接到数据库?

常规方式

常规方式就是按部就班的读取文件了。其余的话和上述方案一致。

// 读取配置文件内容

$handle = fopen("filepath", "r");            $content = fread($handle, filesize("filepath"));123

PHP解析XML

上述两种读取文件,其实都是为了PHP解析XML来做准备的。关于PHP解析XML的方式的博客有很多。方式也有很多,像simplexml,XMLReader,DOM啦等等。但是对于比较小型的xml配置文件,simplexml就足够了。

配置文件

?xml version="1.0" encoding="UTF-8" ?mysql

!-- 为防止出现意外,请按照此标准顺序书写.其实也无所谓了 --

hostlocalhost/host

userroot/user

password123456/password

dbtest/db

port3306/port/mysql12345678910

解析

?php/**

* 作为解析XML配置文件必备工具

*/class XMLUtil {

public static $dbconfigpath = "./db.config.xml";    public static function getDBConfiguration() {

$dbconfig = array ();        try {            // 读取配置文件内容

$handle = fopen(self::$dbconfigpath, "r");            $content = fread($handle, filesize(self::$dbconfigpath));            // 获取xml文档根节点,进而获取相关的数据库信息

$mysql = simplexml_load_string($content);            // 将获取到的xml节点信息赋值给关联数组,方便接下来的方法调用

$dbconfig['host'] = $mysql-host;            $dbconfig['user'] = $mysql-user;            $dbconfig['password'] = $mysql-password;            $dbconfig['db'] = $mysql-db;            $dbconfig['port'] = $mysql-port;            // 将配置信息以关联数组的形式返回

return $dbconfig;

} catch ( Exception $e ) {            throw new RuntimeException ( "mark读取数据库配置文件信息出错!/markbr /" );

}        return $dbconfig;

}

}1234567891011121314151617181920212223242526272829

数据库连接池

对于PHP程序而言,优化永无止境。而数据库连接池就在一定程度上起到了优化的作用。其使得对用户的每一个请求而言,无需每次都像数据库申请链接资源。而是通过已存在的数据库连接池中的链接来返回,从时间上,效率上,都是一个大大的提升。

于是,这里简单的模拟了一下数据库连接池的实现。核心在于维护一个“池”。

从池子中取,用毕,归还给池子。

?php/**x

*  PHP中的数据库 工具类设计

*  郭璞

*  2016年12月23日

*

**/class DbHelper {    private $dbconfig;    private $dbpool;    public $poolsize;    public function __construct($poolsize = 20) {        if (! file_exists ( "./utils.php" )) {            throw new RuntimeException ( "markutils.php文件丢失,无法进行配置文件的初始化操作!/markbr /" );

}else {

require './utils.php';

}        // 初始化 配置文件信息

$this-dbconfig = XMLUtil::getDBConfiguration ();        // 准备好数据库连接池“伪队列”

$this-poolsize = $poolsize;

$this-dbpool = array ();        for($index = 1; $index = $this-poolsize; $index ++) {

$conn = mysqli_connect ( $this-dbconfig ['host'], $this-dbconfig ['user'], $this-dbconfig ['password'], $this-dbconfig ['db'] ) or die ( "mark连接数据库失败!/markbr /" );

array_push ( $this-dbpool, $conn );

}

}    /**

* 从数据库连接池中获取一个数据库链接资源

*

* @throws ErrorException

* @return mixed

*/

public function getConn() {        if (count ( $this-dbpool ) = 0) {            throw new ErrorException ( "mark数据库连接池中已无链接资源,请稍后重试!/mark" );

} else {            return array_pop ( $this-dbpool );

}

}    /**

* 将用完的数据库链接资源放回到数据库连接池

*

* @param unknown $conn

* @throws ErrorException

*/

public function release($conn) {        if (count ( $this-dbpool ) = $this-poolsize) {            throw new ErrorException ( "mark数据库连接池已满/markbr /" );

} else {

array_push ( $this-dbpool, $conn );

}

}

}

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连接mysql为什么要用接口

php中连接MySQL数据库用到的接口定义如下:

?php

/*

* 建立连接, mysql_connect,打开一个到MySQL服务器的连接,

* 失败返回false,

* 成功返回一个MySQL连接标识

*/

$db = mysql_connect("127.0.0.1","root","root123");

if(!$db){

die('连接建立错误: ' . mysql_error());

}

if(!mysql_select_db("php")){//选择数据库,成功返回true,失败返回false

die('数据库选择错误: ' . mysql_error());

}

$insertSQL = "insert into php values(4,'phpinsert')";//插入语句

$updateSQL = "update php set name='updatephp' where id = 4";//修改语句

$deleteSQL = "delete from php where id = 2";

/*

* 发送一条MySQL查询,仅对SELECT,SHOW,EXPLAIN,DESCRIBE语句返回一个资源标识符,查询不正确则返回false,

* 对于其它类型的SQL语句,mysql_query()执行成功时返回true,出错时返回false。

* 非false的返回值代表查询时合法的并且能被服务器执行,但并不表示影响到的行数或返回的行数,

* 因为一条查询有可能执行成功了但并不返回或者影响到任何行。

*/

$insertresult = mysql_query($insertSQL);

if($insertresult != false){//查询成功

/*

* 取得最近一次与 link_identifier 关联的 INSERT,UPDATE 或 DELETE 查询所影响的记录行数。

* 执行成功则返回受影响的行的数目,如果最近一次查询失败的话,函数返回 -1。

*/

$number = mysql_affected_rows();

echo "插入影响行数:".$number."br /";

/*

* 取得上一步 INSERT 操作产生的 ID ,返回上一步 INSERT 查询中产生的 AUTO_INCREMENT 的 ID 号,

* 如果上一查询没有产生 AUTO_INCREMENT 的值,则 mysql_insert_id() 返回 0。

* 如果需要保存该值以后使用,要确保在产生了值的查询之后立即调用 mysql_insert_id()。

* 此处由于没有 AUTO_INCREMENT,所以返回0。

*/

echo mysql_insert_id()."br /";

}

$updateresult = mysql_query($updateSQL);

if($updateresult !=FALSE){//更新操作

$number = mysql_affected_rows();//大于0则成功

echo "更新影响行数:".$number."br /";

}

$deleteresult = mysql_query($deleteSQL);

if($deleteresult !=FALSE){//更新操作

$number = mysql_affected_rows(); //大于0则成功

echo "删除影响行数:".$number."br /";

}

mysql_close($db);//关闭连接,成功返回true,失败返回false。

?


网站标题:php连接数据库写接口 php建立数据库连接的代码
文章源于:http://cdkjz.cn/article/hhhchi.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220