phpmysql封裝類(php函數封裝)

本文目錄一覽:

info’>php中有mysqli類,是嗎?$mysqli->info

本文所述的是一個在PHP中以mysqli方式連接資料庫的一個資料庫類實例,該資料庫類是從一個PHP的CMS中整理出來的,可實現PHP連接資料庫類,MySQLi版,兼容PHP4,對於有針對性需要的朋友可根據此代碼進行優化和修改。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

?php

#==================================================================================================

# Filename: /db/db_mysqli.php

# Note : 連接資料庫類,MySQLi版

#==================================================================================================

#[類庫sql]

class db_mysqli

{

var $query_count = 0;

var $host;

var $user;

var $pass;

var $data;

var $conn;

var $result;

var $prefix = “qingga

PHP訪問MYSQL資料庫封裝類(附函數說明)

複製代碼

代碼如下:

?php

/*

MYSQL

資料庫訪問封裝類

MYSQL

數據訪問方式,php4支持以mysql_開頭的過程訪問方式,php5開始支持以mysqli_開頭的過程和mysqli面向對象

訪問方式,本封裝類以mysql_封裝

數據訪問的一般流程:

1,連接資料庫

mysql_connect

or

mysql_pconnect

2,選擇資料庫

mysql_select_db

3,執行SQL查詢

mysql_query

4,處理返回的數據

mysql_fetch_array

mysql_num_rows

mysql_fetch_assoc

mysql_fetch_row

etc

*/

class

db_mysql

{

var

$querynum

=

;

//當前頁面進程查詢資料庫的次數

var

$dblink

;

//資料庫連接資源

//鏈接資料庫

function

connect($dbhost,$dbuser,$dbpw,$dbname=”,$dbcharset=’utf-8′,$pconnect=0

,

$halt=true)

{

$func

=

empty($pconnect)

?

‘mysql_connect’

:

‘mysql_pconnect’

;

$this-dblink

=

@$func($dbhost,$dbuser,$dbpw)

;

if

($halt

!$this-dblink)

{

$this-halt(“無法鏈接資料庫!”);

}

//設置查詢字符集

mysql_query(“SET

character_set_connection={$dbcharset},character_set_results={$dbcharset},character_set_client=binary”,$this-dblink)

;

//選擇資料庫

$dbname

@mysql_select_db($dbname,$this-dblink)

;

}

//選擇資料庫

function

select_db($dbname)

{

return

mysql_select_db($dbname,$this-dblink);

}

//執行SQL查詢

function

query($sql)

{

$this-querynum++

;

return

mysql_query($sql,$this-dblink)

;

}

//返回最近一次與連接句柄關聯的INSERT,UPDATE

或DELETE

查詢所影響的記錄行數

function

affected_rows()

{

return

mysql_affected_rows($this-dblink)

;

}

//取得結果集中行的數目,只對select查詢的結果集有效

function

num_rows($result)

{

return

mysql_num_rows($result)

;

}

//獲得單格的查詢結果

function

result($result,$row=0)

{

return

mysql_result($result,$row)

;

}

//取得上一步

INSERT

操作產生的

ID,只對錶有AUTO_INCREMENT

ID的操作有效

function

insert_id()

{

return

($id

=

mysql_insert_id($this-dblink))

=

?

$id

:

$this-result($this-query(“SELECT

last_insert_id()”),

0);

}

//從結果集提取當前行,以數字為key表示的關聯數組形式返回

function

fetch_row($result)

{

return

mysql_fetch_row($result)

;

}

//從結果集提取當前行,以欄位名為key表示的關聯數組形式返回

function

fetch_assoc($result)

{

return

mysql_fetch_assoc($result);

}

//從結果集提取當前行,以欄位名和數字為key表示的關聯數組形式返回

function

fetch_array($result)

{

return

mysql_fetch_array($result);

}

//關閉鏈接

function

close()

{

return

mysql_close($this-dblink)

;

}

//輸出簡單的錯誤html提示信息並終止程序

function

halt($msg)

{

$message

=

“html\nhead\n”

;

$message

.=

“meta

content=’text/html;charset=gb2312’\n”

;

$message

.=

“/head\n”

;

$message

.=

“body\n”

;

$message

.=

“資料庫出錯:”.htmlspecialchars($msg).”\n”

;

$message

.=

“/body\n”

;

$message

.=

“/html”

;

echo

$message

;

exit

;

}

}

?

php查找MySQL中某張表的數據,如何封裝為json數組?

$sql

=

“SELECT*

FROM

table1

“;//查詢表table1

$result

=

mysqli_query($conn,$sql);//將表與資料庫連接

$output

=

[];

//用於盛放查詢到的商品

while(($row=mysqli_fetch_assoc($result))!==null){

$output[]

=

$row;

}

echo

json_encode($output);//輸出查詢到的數據

php使用mysqli和pdo擴展,測試對比mysql資料庫的執行效率完整示例

本文實例講述了php使用mysqli和pdo擴展,測試對比mysql資料庫的執行效率。分享給大家供大家參考,具體如下:

?php

/**

*

測試pdo和mysqli的執行效率

*/

header(“Content-type:text/html;charset=utf-8”);

//通過pdo鏈接資料庫

$pdo_startTime

=

microtime(true);

$pdo

=

new

PDO(“mysql:host=localhost;dbname=test”,”root”,”1234″,array(PDO::MYSQL_ATTR_INIT_COMMAND

=

“SET

NAMES’utf8′;”));

for($i=1;$i=100;$i++){

$title

=

“pdo標題”.$i;

$content

=

“pdo內容”.$i;

$addtime

=

time();

$user_id

=

$i;

$pdo_sql

=

“INSERT

INTO

`article`(`title`,`content`,`addtime`,`user_id`)

VALUES(:title,:content,:addtime,:user_id)”;

$sth

=

$pdo-prepare($pdo_sql);

$sth-bindParam(‘:title’,$title);

$sth-bindParam(‘:content’,$content);

$sth-bindParam(‘:addtime’,$addtime);

$sth-bindParam(‘:user_id’,$user_id);

$sth-execute();

}

$pdo_endTime

=

microtime(true);

$pdo_time

=

$pdo_endTime

$pdo_startTime;

echo

$pdo_time;

echo

“hr/”;

//通過mysql鏈接資料庫

$mysqli_startTime

=

microtime(true);

$mysqli

=

mysqli_connect(“localhost”,”root”,”1234″,”test”)

or

die(“數據連接失敗”);

mysqli_query($mysqli,”set

names

utf8″);

for($i=1;$i=100;$i++){

$title

=

“mysqli標題”.$i;

$content

=

“mysqli內容”.$i;

$addtime

=

time();

$user_id

=

$i;

$sql

=

“INSERT

INTO

`article`(`title`,`content`,`addtime`,`user_id`)

VALUES(‘”.$title.”‘,'”.$content.”‘,”.$addtime.”,”.$user_id.”)”;

mysqli_query($mysqli,$sql);

}

$mysqli_endTime

=

microtime(true);

$mysqli_time

=

$mysqli_endTime

$mysqli_startTime;

echo

$mysqli_time;

echo

“hr/”;

if($pdo_time

$mysqli_time){

echo

“pdo的執行時間是mysqli的”.round($pdo_time/$mysqli_time).”倍”;

}else{

echo

“mysqli的執行時間是pdo的”.round($mysqli_time/$pdo_time).”倍”;

}

測試結果:其實經過多次測試,pdo和mysqli的執行效率差不多。

更多關於PHP相關內容感興趣的讀者可查看本站專題:《PHP基於pdo操作資料庫技巧總結》、《php+mysqli資料庫程序設計技巧總結》、《php面向對象程序設計入門教程》、《php字元串(string)用法總結》、《php+mysql資料庫操作入門教程》及《php常見資料庫操作技巧匯總》

希望本文所述對大家PHP程序設計有所幫助。

您可能感興趣的文章:php使用mysqli和pdo擴展,測試對比連接mysql資料庫的效率完整示例php中資料庫連接方式pdo和mysqli對比分析php中關於mysqli和mysql區別的一些知識點分析php操作mysqli(示例代碼)php封裝的mysqli類完整實例PHP以mysqli方式連接類完整代碼實例php簡單解析mysqli查詢結果的方法(2種方法)php中mysql連接方式PDO使用詳解Php中用PDO查詢Mysql來避免SQL注入風險的方法php

mysql

PDO

查詢操作的實例詳解PHP實現PDO的mysql資料庫操作類

php封裝一個class類實現mysql資料庫的增刪該查

?php

class db{

private $db;

const MYSQL_OPT_READ_TIMEOUT = 11;

const MYSQL_OPT_WRITE_TIMEOUT = 12;

private $tbl_name;

private $where;

private $sort;

private $fields;

private $limit;

public static $_instance = null;

function __construct(){

$cfg = loadConfig(‘db’);

$db = mysqli_init();

$db-options(self::MYSQL_OPT_READ_TIMEOUT, 3);

$db-options(self::MYSQL_OPT_WRITE_TIMEOUT, 1);

@$db-real_connect($cfg[‘host’],$cfg[‘user’],$cfg[‘pwd’],$cfg[‘db’]);

if ($db-connect_error) {

$this-crash($db-errno,$db-error);

}

$db-set_charset(“utf8”);

$this-db = $db;

//echo $this-db-stat;

}

public static function getInstance(){

if(!(self::$_instance instanceof self)){

self::$_instance = new self();

}

return self::$_instance;

}

private function __clone() {} //覆蓋__clone()方法,禁止克隆

public function find($conditions = null){

if($conditions) $this-where($conditions);

return $this-getArray($this-buildSql(),1);

}

public function findAll($conditions = null){

if($conditions) $this-where($conditions);

return $this-getArray($this-buildSql());

}

//表

public function t($table){ $this-tbl_name = $table; return $this;}

//條件

public function where($conditions){

$where = ”;

if(is_array($conditions)){

$join = array();

foreach( $conditions as $key = $condition ){

$condition = $this-db-real_escape_string($condition);

$join[] = “`{$key}` = ‘{$condition}'”;

}

$where = “WHERE “.join(” AND “,$join);

}else{

if(null != $conditions) $where = “WHERE “.$conditions;

}

$this-where = $where;

return $this;

}

//排序

public function sort($sort){

if(null != $sort) $sort = “ORDER BY {$sort}”;

$this-sort = $sort;

return $this;

}

//欄位

public function fields($fields){ $this-fields = $fields; return $this; }

public function limit($limit){$this-limit = $limit; return $this;}

private function buildSql(){

$this-fields = empty($this-fields) ? “*” : $this-fields;

$sql = “SELECT {$this-fields} FROM {$this-tbl_name} {$this-where} {$this-sort}”;

accessLog(‘db_access’,$sql);

if(null != $this-limit)$sql .= ” limit {$this-limit}”;

return $sql;

}

/**

* 返回查詢數據

* @param $sql

* @param bool $hasOne

* @return array|bool|mixed

*/

private function getArray($sql,$hasOne = false){

if($this-db-real_query($sql) ){

if ($result = $this-db-use_result()) {

$row = array();

if($hasOne){

$row = $result-fetch_assoc();

}else{

while($d = $result-fetch_assoc()) $row[] = $d;

}

$result-close();

$this-fields = “*”;

return $row;

}else{

return false;

}

}else{

if($this-db-error){

$this-crash($this-db-errno,$this-db-error,$sql);

}

}

}

public function findSql($sql,$hasOne = false){

accessLog(‘db_access’,$sql);

if($this-db-real_query($sql) ){

if ($result = $this-db-use_result()) {

$row = array();

if($hasOne){

$row = $result-fetch_assoc();

}else{

while($d = $result-fetch_assoc()) $row[] = $d;

}

$result-close();

$this-fields = “*”;

return $row;

}else{

return false;

}

}else{

if($this-db-error){

$this-crash($this-db-errno,$this-db-error,$sql);

}

}

}

public function create($row){

if(!is_array($row))return FALSE;

$row = $this-prepera_format($row);

if(empty($row))return FALSE;

foreach($row as $key = $value){

$cols[] = ‘`’.$key.’`’;

$vals[] = “‘”.$this-db-real_escape_string($value).”‘”;

}

$col = implode(‘,’, $cols);

$val = implode(‘,’, $vals);

$sql = “INSERT INTO `{$this-tbl_name}` ({$col}) VALUES ({$val})”;

accessLog(‘db_access’,$sql);

if( FALSE != $this-db-query($sql) ){ // 獲取當前新增的ID

if($this-db-insert_id){

return $this-db-insert_id;

}

if($this-db-affected_rows){

return true;

}

}

return FALSE;

}

//直接執行sql

public function runSql($sql){

accessLog(‘db_access’,$sql);

if( FALSE != $this-db-query($sql) ){ // 獲取當前新增的ID

return true;

}else{

return false;

}

}

public function update($row){

$where = “”;

$row = $this-prepera_format($row);

if(empty($row))return FALSE;

foreach($row as $key = $value){

$value = $this-db-real_escape_string($value);

$vals[] = “`{$key}` = ‘{$value}'”;

}

$values = join(“, “,$vals);

$sql = “UPDATE {$this-tbl_name} SET {$values} {$this-where}”;

accessLog(‘db_access’,$sql);

if( FALSE != $this-db-query($sql) ){ // 獲取當前新增的ID

if( $this-db-affected_rows){

return true;

}

}

return false;

}

function delete(){

$sql = “DELETE FROM {$this-tbl_name} {$this-where}”;

if( FALSE != $this-db-query($sql) ){ // 獲取當前新增的ID

if( $this-db-affected_rows){

return true;

}

}

return FALSE;

}

private function prepera_format($rows){

$columns = $this-getArray(“DESCRIBE {$this-tbl_name}”);

$newcol = array();

foreach( $columns as $col ){

$newcol[$col[‘Field’]] = $col[‘Field’];

}

return array_intersect_key($rows,$newcol);

}

//崩潰信息

private function crash($number,$message,$sql=”){

$msg = ‘Db Error ‘.$number.’:’.$message ;

if(empty($sql)){

echo t(‘db_crash’);

}else{

$msg .= ” SQL:”.$sql;

echo t(‘db_query_err’);

}

accessLog(‘db_error’,$msg);

exit;

}

}

php實現mysql封裝類示例

php封裝mysql類

複製代碼

代碼如下:

?php

class

Mysql

{

private

$host;

private

$user;

private

$pwd;

private

$dbName;

private

$charset;

private

$conn

=

null;

public

function

__construct()

{

$this-host

=

‘localhost’;

$this-user

=

‘root’;

$this-pwd

=

‘root’;

$this-dbName

=

‘test’;

$this-connect($this-host,$this-user,$this-pwd);

$this-switchDb($this-dbName);

$this-setChar($this-charset);

}

//負責鏈接

private

function

connect($h,$u,$p)

{

$conn

=

mysql_connect($h,$u,$p);

$this-conn

=

$conn;

}

//負責切換資料庫

public

function

switchDb($db)

{

$sql

=

‘use’

.

$db;

$this-query($sql);

}

//負責設置字符集

public

function

setChar($char)

{

$sql

=

‘set

names’

.

$char;

$this-query($sql);

}

//負責發送sql查詢

public

function

query($sql)

{

return

mysql_query($sql,$this-conn);

}

//負責獲取多行多列的select結果

public

function

getAll($sql)

{

$list

=

array();

$rs

=

$this-query($sql);

if

(!$rs)

{

return

false;

}

while

($row

=

mysql_fetch_assoc($rs))

{

$list[]

=

$row;

}

return

$list;

}

public

function

getRow($sql)

{

$rs

=

$this-query($sql);

if(!$rs)

{

return

false;

}

return

mysql_fetch_assoc($rs);

}

public

function

getOne($sql)

{

$rs

=

$this-query($sql);

if

(!$rs)

{

return

false;

}

return

mysql_fetch_assoc($rs);

return

$row[0];

}

public

function

close()

{

mysql_close($this-conn);

}

}

echo

‘pre’;

$mysql

=

new

Mysql();

print_r($mysql);

$sql

=

“insert

into

stu

values

(4,’wangwu’,’99998′)”;

if($mysql-query($sql)){

echo

“query成功”;

}else

{

echo

“失敗”;

}

echo

“br

/”;

$sql

=

“select

*

from

stu”;

$arr

=

$mysql-getAll($sql);

print_r($arr);

?

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

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

相關推薦

  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • PHP和Python哪個好找工作?

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

    編程 2025-04-29
  • Python中capitalize函數的使用

    在Python的字元串操作中,capitalize函數常常被用到,這個函數可以使字元串中的第一個單詞首字母大寫,其餘字母小寫。在本文中,我們將從以下幾個方面對capitalize函…

    編程 2025-04-29
  • Python中set函數的作用

    Python中set函數是一個有用的數據類型,可以被用於許多編程場景中。在這篇文章中,我們將學習Python中set函數的多個方面,從而深入了解這個函數在Python中的用途。 一…

    編程 2025-04-29
  • 三角函數用英語怎麼說

    三角函數,即三角比函數,是指在一個銳角三角形中某一角的對邊、鄰邊之比。在數學中,三角函數包括正弦、餘弦、正切等,它們在數學、物理、工程和計算機等領域都得到了廣泛的應用。 一、正弦函…

    編程 2025-04-29
  • 單片機列印函數

    單片機列印是指通過串口或並口將一些數據列印到終端設備上。在單片機應用中,列印非常重要。正確的列印數據可以讓我們知道單片機運行的狀態,方便我們進行調試;錯誤的列印數據可以幫助我們快速…

    編程 2025-04-29
  • Python3定義函數參數類型

    Python是一門動態類型語言,不需要在定義變數時顯示的指定變數類型,但是Python3中提供了函數參數類型的聲明功能,在函數定義時明確定義參數類型。在函數的形參後面加上冒號(:)…

    編程 2025-04-29
  • Python實現計算階乘的函數

    本文將介紹如何使用Python定義函數fact(n),計算n的階乘。 一、什麼是階乘 階乘指從1乘到指定數之間所有整數的乘積。如:5! = 5 * 4 * 3 * 2 * 1 = …

    編程 2025-04-29
  • Python定義函數判斷奇偶數

    本文將從多個方面詳細闡述Python定義函數判斷奇偶數的方法,並提供完整的代碼示例。 一、初步了解Python函數 在介紹Python如何定義函數判斷奇偶數之前,我們先來了解一下P…

    編程 2025-04-29
  • 分段函數Python

    本文將從以下幾個方面詳細闡述Python中的分段函數,包括函數基本定義、調用示例、圖像繪製、函數優化和應用實例。 一、函數基本定義 分段函數又稱為條件函數,指一條直線段或曲線段,由…

    編程 2025-04-29

發表回復

登錄後才能評論