剛剛接觸PHP面向對象,我將PHP連接數據庫封裝到一個CLASS類。。如下。
<?php
class conn{
private $host;
private $name;
private $pwd;
private $dBase;
private $conn;
private $result;
private $nums=0;
private $fields;
function __construct($host="",$name="",$pwd="",$dBase=""){
$this->host=$host;
$this->name=$name;
$this->pwd=$pwd;
$this->dBase=$dBase;
$this->init_conn();
}
function init_conn(){
$this->conn=mysql_connect($this->host,$this->name,$this->pwd);
mysql_select_db($this->dBase,$this->conn);
mysql_query("set names 'utf8'");
}
//執行SQL語句的方法
function mysql_query_rst($sql){
if($conn==""){
$this->init_conn();
}
$this->result=mysql_query($sql,$this->conn);
}
//返回結果集的記錄數
function mysql_nums($sql){
$this->mysql_query_rst($sql);
if(mysql_errno()==0){
$this->nums=mysql_num_rows($this->result);
return $this->nums;
}else{
return "mysql error!";
}
}
//將返回的結果集存放在數組中
function mysql_fields($sql){
$this->mysql_query_rst($sql);
if(mysql_errno()==0){
$this->fields=mysql_fetch_array($this->result,MYSQL_ASSOC);
return $this->fields;
}else{
return "mysql error!";
}
}
}
$p=new conn("localhost","root","","car");
?> 如果我的查詢語句查詢出的結果集中有多條記錄,那麼我怎麼循环輸出這多條記錄到頁面中。。
<?php
class conn{
private $host;
private $name;
private $pwd;
private $dBase;
private $conn;
private $result;
private $nums=0;
private $fields;
function __construct($host="",$name="",$pwd="",$dBase=""){
$this->host=$host;
$this->name=$name;
$this->pwd=$pwd;
$this->dBase=$dBase;
$this->init_conn();
}
function init_conn(){
$this->conn=mysql_connect($this->host,$this->name,$this->pwd);
mysql_select_db($this->dBase,$this->conn);
mysql_query("set names 'utf8'");
}
//執行SQL語句的方法
function mysql_query_rst($sql){
if($conn==""){
$this->init_conn();
}
$this->result=mysql_query($sql,$this->conn);
}
//返回結果集的記錄數
function mysql_nums($sql){
$this->mysql_query_rst($sql);
if(mysql_errno()==0){
$this->nums=mysql_num_rows($this->result);
return $this->nums;
}else{
return "mysql error!";
}
}
//將返回的結果集存放在數組中
function mysql_fields($sql){
$this->mysql_query_rst($sql);
if(mysql_errno()==0){
$this->fields=mysql_fetch_array($this->result,MYSQL_ASSOC);
return $this->fields;
}else{
return "mysql error!";
}
}
}
$p=new conn("localhost","root","","car");
?> 如果我的查詢語句查詢出的結果集中有多條記錄,那麼我怎麼循环輸出這多條記錄到頁面中。。
if(mysql_errno()==0){
$this->fields=mysql_fetch_array($this->result,MYSQL_ASSOC);
return $this->fields;
}这里只能返回第一条记录
function mysql_fields($sql=''){
if(! $this->result && $sql)
$this->mysql_query_rst($sql);
if(mysql_errno()==0){
$this->fields = mysql_fetch_array($this->result,MYSQL_ASSOC);
if(! $this->fields) $this->result = 0;
return $this->fields;
}
}这样调用
$p = new conn("localhost","root","","car");$row = $p->mysql_fields($sql);
do {
print_r($row);
}while($row = $p->mysql_fields());这样也行
while($row = $p->mysql_fields($sql)) {
print_r($row);
}
不过显得有点怪:怎么总是要有sql指令呢?