php数据库查询封装 php7查询数据库( 二 )


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查询的多条数据封装成数组 并且转为json的数据格式正常来说,循环赋值是没问题的,你需要看下,你的sql在数据库中能查出几条结果,
最好数组还是这样定义$arr
=
array();而不是$arr[]
=
array();
简单的测试你数据是否只有一条的方法是在while里边打印个东西
echo
$sql;//打印下你的sql语句,用phpmyadmin执行下看结果
$cnt=1;
while($row
=
$db
-
fetchassoc($result))
{
$cnt++;
echo
$cnt;
}
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}'";

推荐阅读