<?php 
/*
编写人:王志强
日     期:2012.11.9
ConDB数据库连接类
AdminDB数据库管理类
SePage分页类
 */
class ConnDB
{
public  $dbtype;
public  $host;
public  $user;
public  $pwd;
public  $dbname;
function __construct($dbtype,$host,$user,$pwd,$dbname)//构造方法
{
  $this->dbtype=$dbtype;
  $this->host=$host;
  $this->user=$user;
  $this->pwd=$pwd;
  $this->dbname=$dbname;
}
function GetConnId()  //实现数据库连接并返回连接对象
{
if($this->dbtype=="mysql"||$this->dbtype=="mssql")
{
$dsn="$this->dbtype:host=$this->host;dbname=$this->dbname";
}else 
{
$dsn="$this->dbtype:dbnme=$this->dbname";
}
try
{
 //初始化PDO对象,就是创建数据库连接对象$pdo
 $conn=new PDO($dsn,$this->user, $this->pwd);
 $conn->query("set names utf8");
 return  $conn;
}catch (PDOException $e)
{
die("Error!:".$e->getMessage()."<br/>");
}
}
         
}
//数据库管理类
class AdminDB
{
   function  ExecSQL($sqlstr,$conn)
{
$sqltype=strtolower(substr(trim($sqlstr),0,6));
//$sqltype=strtolower(substr(trim($sqlstr),0,6));
$rs=$conn->prepare($sqlstr);//准备查询语句
$rs->execute();//执行查询语句,并返回结果集
if($sqltype=="select")
{
$array=$rs->fetchAll(PDO::FETCH_ASSOC); //获取结果集中所有数据

if(count($array==0||$rs=false))

return  false;
else 
return  $array;

}elseif ($sqltype=="update"||$sqltype=="insert"||$sqltype="delete")
{
if($rs)
return  true;
else 
return false;
}
}
}
$connobje=new ConnDB("mysql","localhost","root","","db_business");
$conn=$connobje->GetConnId();
$admindb=new AdminDB();
$sql="SELECT * FROM `tb_class` LIMIT 0 , 30";
$rst=$admindb->ExecSQL($sql, $conn);
if($rst) echo "ys";
else 
echo "no";?>这段代码返回是no,好像是没有获取数据库内容?还有怎样在类外遍历数据库字段?

解决方案 »

  1.   

    if(count($array==0||$rs=false))
    这段代码真的没一点可取的地方
      

  2.   

    本帖最后由 xuzuning 于 2012-11-10 13:31:16 编辑
      

  3.   

    怎样在方法外遍历数据库字段呢?
    $connobje=new ConnDB("mysql","localhost","root","","db_business"); $conn=$connobje->GetConnId(); $admindb=new AdminDB(); $sql="SELECT * FROM `tb_class` LIMIT 0 , 30"; $rst=$admindb->ExecSQL($sql, $conn); 
    echo $rst[id]; 不知道可以这样写嘛?
      

  4.   

    一般我会写成while($rst=$admindb->ExecSQL($sql, $conn);)
    {
    echo $rst[id];
    }