欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

PHP中使用匿名函数操作数据库的例子

程序员文章站 2022-04-27 21:20:48
...

这篇文章主要介绍了PHP中使用匿名函数操作数据库的例子,本文直接给出类的代码、使用例子、继承例子,需要的朋友可以参考下

复制代码 代码如下:


Base dao class illustrating the usefulness of closures.
* Handles opening and closing of connections.
* Adds slashes sql
* Type checking of sql parameters and casts as appropriate
* Provides hook for processing of result set and emitting one or more objects.
* Provides hook for accessing underlying link and result objects.

define("userName","root");
define("password","root");
define("dbName","ahcdb");
define("hostName","localhost");

class BaseDao {

function getConnection() {
$link = mysql_connect(hostName, userName, password);
if (!$link)
die("Could not connect: " . mysql_error());
if (!mysql_select_db(dbName))
die("Could not select database: " . mysql_error());
return $link;
}

function setParams(& $sql, $params) {
if($params != null)
$sql = vsprintf($sql, array_map(function($n) {
if(is_int($n))
return (int)$n;
if(is_float($n))
return (float)$n;
if(is_string($n))
return "'".mysql_real_escape_string($n)."'";
return mysql_real_escape_string($n);
}, $params));
}

function executeQuery($sql, $params, $callback = null) {
$link = $this->getConnection();
$this->setParams($sql, $params);
$return = null;
if(($result = mysql_query($sql, $link)) != null)
if($callback != null)
$return = $callback($result, $link);
if($link != null)
mysql_close($link);
if(!$result)
die("Fatal Error: Invalid query '$sql' : " . mysql_error());
return $return;
}

function getList($sql, $params, $callback) {
return $this->executeQuery($sql, $params, function($result, $link) use ($callback) {
$idx = 0;
$list = array();
while ($row = mysql_fetch_assoc($result))
if($callback != null)
$list[$idx] = $callback($idx++, $row);
return $list;
});
}

function getSingle($sql, $params, $callback) {
return $this->executeQuery($sql, $params, function($result, $link) use ($callback) {
if ($row = mysql_fetch_assoc($result))
$obj = $callback($row);
return $obj;
});
}
}