Maison php教程 PHP源码 PHP PDO操作MYSQL封装类

PHP PDO操作MYSQL封装类

May 23, 2016 pm 04:41 PM

php代码

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

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

<?php

/**

 * auther soulence

 * 调用数据类文件

 * modify 2015/06/12

 */

class DBConnect

{

    private $dbname = null;

    private $pdo = null;

    private $persistent = false;

    private $statement = null;

    private $lastInsID = null;

    private static $_instance = [];

  

    private function __construct($dbname,$attr)

    {

        $this->dbname = $dbname;

        $this->persistent = $attr;

    }

  

    public static function db($flag=&#39;r&#39;,$persistent=false)

    {

        if(!isset($flag)){

            $flag = &#39;r&#39;;

        }

          

        if (!class_exists(&#39;PDO&#39;))

        {

            throw new Exception(&#39;not found PDO&#39;);

            return false;

        }

        $mysql_server = Yaf_Registry::get(&#39;mysql&#39;);

        if(!isset($mysql_server[$flag])){

            return false;

        }

      

        $options_arr = array(PDO::MYSQL_ATTR_INIT_COMMAND => &#39;SET NAMES &#39;.$mysql_server[$flag][&#39;charset&#39;],PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC);

        if($persistent === true){

            $options_arr[PDO::ATTR_PERSISTENT] = true;

        }

          

        try {

            $pdo = new PDO($mysql_server[$flag][&#39;connectionString&#39;],$mysql_server[$flag][&#39;username&#39;],$mysql_server[$flag][&#39;password&#39;],$options_arr);

        } catch (PDOException $e) { 

            throw new Exception($e->getMessage());

            //exit(&#39;连接失败:&#39;.$e->getMessage());

            return false;

        }

  

        if(!$pdo) {

            throw new Exception(&#39;PDO CONNECT ERROR&#39;);

            return false;

        }

  

        return $pdo;

    }

  

    /**

     * 得到操作数据库对象

     * @param string $dbname 对应的数据库是谁

     * @param bool $attr  是否长连接

     * return false说明给定的数据库不存在

     */

    public static function getInstance($dbname = &#39;r&#39;,$attr = false)

    {

        $mysql_server = Yaf_Registry::get(&#39;mysql&#39;);

        if(!isset($mysql_server[$dbname])){

            return false;

        }

        $key = md5(md5($dbname.$attr,true));

        if (!isset(self::$_instance[$key]) || !is_object(self::$_instance[$key]))

            self::$_instance[$key] = new self($dbname,$attr);

        return self::$_instance[$key];

    }

  

    private function getConnect(){

        $this->pdo = self::db($this->dbname,$this->persistent);

    }

  

    /**

     * 查询操作

     * @param string $sql   执行查询的sql语句

     * @param array $data  查询的条件  格式为[&#39;:id&#39;=>$id,&#39;:name&#39;=>$name](推荐)或者为[1=>$id,2=>$name]

     * @param bool $one   是否返回一条内容  默认为否

     */

    public function query($sql, $data = [], $one = false)

    {

        if (!is_array($data) || empty($sql) || !is_string($sql))

            return false;

  

        $this->free();

  

        return $this->queryCommon($data,$sql,$one);

    }

  

    /**

     * 内部查询的共用方法

     */

    private function queryCommon($data,$sql,$one)

    {

        $this->pdoExec($data,$sql);

  

        if ($one){

            return $this->statement->fetch(PDO::FETCH_ASSOC);

        }else{

            return $this->statement->fetchAll(PDO::FETCH_ASSOC);

        }

    }

  

    /**

     * 多条SQL语句的查询操作

     * @param array $arr_sql   执行查询的sql语句数组 格式为[$sql1,$sql2]

     * @param array $arr_data  查询与$arr_sql对应的条件  格式为[[&#39;:id&#39;=>$id,&#39;:name&#39;=>$name],[&#39;:id&#39;=>$id,&#39;:name&#39;=>$name]](推荐)或者为[[1=>$id,2=>$name],[1=>$id,2=>$name]]

     * @param bool $one   是否返回一条内容  默认为否  这里如果设置为true那么每一条sql都只返回一条数据

     */

    public function queryes($arr_sql, $arr_data = [], $one = false)

    {

        if(!is_array($arr_sql) || empty($arr_sql) || !is_array($arr_data))

            return false;

  

        $this->free();

  

        $res = [];$i = 0;

        foreach ($arr_sql as $val) {

            if(!isset($arr_data[$i]))

                $arr_data[$i] = [];

            elseif(!is_array($arr_data[$i]))

                throw new Exception(&#39;Error where queryes sql:&#39;.$val.&#39; where:&#39;.$arr_data[$i]);

                  

            $res[] = $this->queryCommon($arr_data[$i],$val,$one);

            $i++;

        }

        return $res;

    }

  

    /**

     * 分页封装

     *

     * @param string $sql

     * @param int $page  表示从第几页开始取

     * @param int $pageSize 表示每页多少条

     * @param array $data 查询的条件

     */

    public function limitQuery($sql, $page=0, $pageSize=20, $data = [])

    {

        $page = intval($page);

        if ($page < 0) {

            return [];

        }

        $pageSize = intval($pageSize);

        if ($pageSize > 0) { // pageSize 为0时表示取所有数据

            $sql .= &#39; LIMIT &#39; . $pageSize;

            if ($page > 0) {

                $start_limit = ($page - 1) * $pageSize;

                $sql .= &#39; OFFSET &#39; . $start_limit;

            }

        }

        return $this->query($sql, $data);

    }

  

    /**

     * 这个是用来进行添加 删除  修改操作  使用事务操作

     * @param string $sql   执行查询的sql语句

     * @param array $data  查询的条件  格式为[&#39;:id&#39;=>$id,&#39;:name&#39;=>$name](推荐)或者为[1=>$id,2=>$name]

     * @param bool $Transaction  是否事务操作  默认为否

     */

    public function executeDDL($sql, $data = [],$Transaction = false){

        if (!is_array($data) || !is_string($sql))

            return false;

  

        $this->free();

  

        if($Transaction)

            $this->pdo->beginTransaction();//开启事务

        try{

            $this->execRes($data,$sql);

            if($Transaction)

                $this->pdo->commit();//事务提交

            return $this->lastInsID;

        } catch (Exception $e) {

            if($Transaction)

                $this->pdo->rollBack();//事务回滚

            throw new Exception(&#39;Error DDLExecute <=====>&#39;.$e->getMessage());

            return false;

        }

    }

  

    /**

     * 这个是用来进行添加 删除  修改操作  使用事务操作

     * 它是执行多条的

     * @param array $arr_sql  需要执行操作的SQL语句数组

     * @param array $arr_data  与数组对应SQL语句的条件

     * @param bool $Transaction  是否事务操作  默认为否

     */

    public function executeDDLes($arr_sql, $arr_data = [],$Transaction = false){

  

        if(!is_array($arr_sql) || empty($arr_sql) || !is_array($arr_data))

            return false;

  

        $res = [];

  

        $this->free();

  

        if($Transaction)

            $this->pdo->beginTransaction();//开启事务

        try{

            $i = 0;

            foreach($arr_sql as $val){

                if(!isset($arr_data[$i]))

                    $arr_data[$i] = [];

                elseif(!is_array($arr_data[$i])){

                    if($Transaction)

                        $this->pdo->rollBack();//事务回滚

                    throw new Exception(&#39;Error where DDLExecutees sql:&#39;.$val.&#39; where:&#39;.$arr_data[$i]);

                }

  

                $this->execRes($arr_data[$i],$val);

                $res[] = $this->lastInsID;

                $i++;

            }

  

            if($Transaction)

                $this->pdo->commit();//事务提交

  

            return $res;

        } catch (Exception $e) {

            if($Transaction)

                $this->pdo->rollBack();//事务回滚

            throw new Exception(&#39;Error DDLExecutees array_sql:&#39;.json_encode($arr_sql).&#39; <=====>&#39;.$e->getMessage());

            return false;

        }

        return $res;

    }

  

    /**

     * 此方法是用来计算查询返回的条数   注意 它只支持SELECT COUNT(*) FROM TABLE...或者SELECT COUNT(0) FROM TABLE...方式

     * @param string $sql  查询的sql语句

     * @param array $data  SQL语句的条件

     */

    public function countRows($sql,$data = []){

        if (!is_array($data) || empty($sql) || !is_string($sql))

            return false;

        $this->free();

  

        $res = $this->pdoExec($data,$sql);

  

        if($res == false)

            return false;

  

        return $this->statement->fetchColumn();

    }

  

    /**

     * 此方法是用来计算查询返回的条数   它是执行多条SQL

     * @param string $sql  查询的sql语句

     * @param array $data  SQL语句的条件

     */

    public function countRowses($arr_sql,$arr_data = []){

  

        if(!is_array($arr_sql) || empty($arr_sql) || !is_array($arr_data))

            return false;

  

        $res = [];

  

        $this->free();

        $i = 0;

        foreach ($arr_sql as $val) {

            if(!isset($arr_data[$i]))

                $arr_data[$i] = [];

            elseif(!is_array($arr_data[$i]))

                throw new Exception(&#39;Error where CountRowses sql:&#39;.$val.&#39; where:&#39;.$arr_data[$i]);

  

            $res1 = $this->pdoExec($arr_data[$i],$val);

  

            if($res1 == false)

                $res[] = false;

            else

                $res[] = $this->statement->fetchColumn();

        }

  

        return $res;

    }

  

    /**

     * 这里再提供一个方法   由于项目中会有很多需要提供开启事务  然后再进行操作  最后提交

     * @param bool $Transaction  是否事务操作  默认为否

     */

    public function getDB($Transaction=false)

    {

        $this->Transaction = $Transaction;

        $this->getConnect();

        if($Transaction === true)

            $this->pdo->beginTransaction();//开启事务

        return $this;

    }

  

    /**

     * 此方法可以执行多次  它是执行DDL语句的

     * 注意  它是需要配合getDB和sQCommit一起使用  不能单独使用哦

     * 如果没有开启事务  sQCommit方法可以不调用

     * @param string $sql  查询的sql语句

     * @param array $data  SQL语句的条件

     */

    public function execSq($sql,$data = [])

    {

        if($this->checkParams($sql,$data) === false)

            return false;

  

        try{

            $this->execRes($data,$sql);

            return $this->lastInsID;

        } catch (Exception $e) {

            if(isset($this->Transaction) && $this->Transaction === true)

                $this->pdo->rollBack();//事务回滚

            throw new Exception(&#39;Error execSq<=====>&#39;.$e->getMessage());

            return false;

        } finally {

            if (!empty($this->statement))

            {

                $this->statement->closeCursor();

                unset($this->statement);

            }

        }

    }

  

    /**

     * 执行查询的方法  它需要传一个连接数据库对象

     * @param string $sql   执行查询的sql语句

     * @param array $data  查询的条件  格式为[&#39;:id&#39;=>$id,&#39;:name&#39;=>$name](推荐)或者为[1=>$id,2=>$name]

     * @param bool $one   是否返回一条内容  默认为否

     */

    public function querySq($sql,$data = [],$one = false)

    {

        if($this->checkParams($sql,$data) === false)

            return false;

  

        return $this->pdoExecSq($sql,$data,[1,$one]);

    }

  

    /**

     * 分页封装

     *

     * @param string $sql

     * @param int $page  表示从第几页开始取

     * @param int $pageSize 表示每页多少条

     * @param array $data 查询的条件

     */

    public function limitQuerySq($sql, $page=0, $pageSize=20, $data = [])

    {

        $page = intval($page);

        if ($page < 0) {

            return [];

        }

        $pageSize = intval($pageSize);

        if ($pageSize > 0) { // pageSize 为0时表示取所有数据

            $sql .= &#39; LIMIT &#39; . $pageSize;

            if ($page > 0) {

                $start_limit = ($page - 1) * $pageSize;

                $sql .= &#39; OFFSET &#39; . $start_limit;

            }

        }

        return $this->querySq($sql, $data);

    }

  

    /**

     * 此方法是用来计算查询返回的条数   注意 它只支持SELECT COUNT(*) FROM TABLE...或者SELECT COUNT(0) FROM TABLE...方式

     * @param string $sql  查询的sql语句

     * @param array $data  SQL语句的条件

     */

    public function countRowsSq($sql,$data = []){

        if($this->checkParams($sql,$data) === false)

            return false;

        return $this->pdoExecSq($sql,$data,[2]);

    }

  

    /**

     * 这里再提供一个方法 这是最后提交操作 如果没有开启事务  此方法最后可以不调用的

     */

    public function sQCommit()

    {

        if(empty($this->pdo) || !is_object($this->pdo))

            return false;

        if(isset($this->Transaction) && $this->Transaction === true)

            $this->pdo->commit();//提交事务

        unset($this->pdo);

    }

  

    /**

     * 内部调用方法 

     */

    public function checkParams($sql,$data)

    {

        if (empty($this->pdo) || !is_object($this->pdo) || !is_array($data) || empty($sql) || !is_string($sql))

            return false;

          

        return true;

    }

  

    /**

     * 内部调用方法 

     */

    private function pdoExecSq($sql,$data,$select = []){

        try{

            $res = $this->pdoExec($data,$sql);

            if(empty($select))

                return $res;

            else{

                if($select[0] === 1){

                    if($select[1] === true)

                        return $this->statement->fetch(PDO::FETCH_ASSOC);

                    else

                        return $this->statement->fetchAll(PDO::FETCH_ASSOC);

                }elseif($select[0] === 2)

                    return $this->statement->fetchColumn();

                else

                    return false;

            }

        } catch (Exception $e) {

            throw new Exception($e->getMessage());

            return false;

        } finally {

            if (!empty($this->statement))

            {

                $this->statement->closeCursor();

                unset($this->statement);

            }

        }

    }

  

    /**

     * 内部调用方法 

     */

    private function execRes($data,$sql){

  

        $res = $this->pdoExec($data,$sql);

          

        $in_id = $this->pdo->lastInsertId();

  

        if (preg_match("/^\s*(INSERT\s+INTO|REPLACE\s+INTO)\s+/i", $sql) && !empty($in_id))

            $this->lastInsID = $in_id;

        else

            $this->lastInsID = $res;

    }

  

    /**

     * 内部调用方法  用来直接执行SQL语句的方法

     */

    private function pdoExec($data,$sql){

        $this->statement = $this->pdo->prepare($sql);

        if (false === $this->statement)

            return false;

        if (!empty($data))

        {

            foreach ($data as $k => $v)

            {

                $this->statement->bindValue($k, $v);

            }

        }

        $res = $this->statement->execute();

        if (!$res)

        {

            throw new Exception(&#39;sql:&#39;.$sql.&#39;<====>where:&#39;.json_encode($data).&#39;<====>error:&#39;.json_encode($this->statement->errorInfo()));

        }else{

            return $res;

        }

    }

      

    /**

     * 内部调用方法  用来释放的

     */

    private function free()

    {

        if (is_null($this->pdo))

            $this->getConnect();

  

        if (!empty($this->statement))

        {

            $this->statement->closeCursor();

            $this->statement = null;

        }

    }

}

?>

Copier après la connexion
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
2 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Repo: Comment relancer ses coéquipiers
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)