Home  >  Article  >  php教程  >  改造mysql_query语句如何返回一个类对象

改造mysql_query语句如何返回一个类对象

WBOY
WBOYOriginal
2016-06-13 10:23:491264browse

这是简化SQL查询函数的一个方法,希望对您有所帮助
如果有更好的看法,请OICQ 86804 或 EMAIL: liboys@21cn.com 共同研究
# SQL查询
# 当count=true时,只计算记录数
function db_query($query, $rec = false) {

if($rec) {
$query = explode("from", $query); // 简单的截取
$query = "select count(*) from ". $query[1];
}

$result = mysql_query($query) or die(mysql_error());

if($rec) {
$rows = mysql_fetch_row($result);
$reccount = $rows[0];
}
else {
$reccount = mysql_num_rows($result);
}

if($reccount) {
$re->result = $result;
$re->reccount = $reccount;
}
else {
$re = false;
}
return $re; // 以后就可以用 $re->xx 的方法调用了
}

例如

......
# 只求记录数
$query = "select id,name,about from table where id > 10";
$re = db_query($query,true); //形如 select count(*) from table where id > 10
print $re->reccount; // 返回记录数

#求查询结果
$query = "select id,name,about from table where id > 10";


$re=db_query($query);
for($i=0; $ireccount; $i++) {
$rows = mysql_fetch_object($re->result);
print $rows->id;
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP3中文文档续4Next article:PHP3中文文档续3