php - 这个类为什么只能获取一条数据??
本文介绍了php - 这个类为什么只能获取一条数据??的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
class DB{
public $con;
public $res;
public $host;
public $username;
public $pw;
public $sql;
public function __construct($host,$username,$pw){
$this->host=$host;
$this->username=$username;
$this->pw=$pw;
$this->connect();
mysql_query("set names utf8");
mysql_select_db("t1");
}
public function connect(){
$this->con=@mysql_connect($this->host,$this->username,$this->pw);
return $this->con;
}
public function query($sql){
$this->res=mysql_query($sql,$this->con);
return $this->res;
}
public function fetch($sql){
$this->query($sql);
while($row=mysql_fetch_row($this->res)){
return $row;
}
}
}
$a=new DB("localhost","root","");
$res=$a->fetch("select * from user");
var_dump($res);
解决方案
循环体中,你的函数已经被 return
,所以只能返回第一次循环的内容,解决办法就是在循环中将内容放在数组中,循环结束再返回数组
如果在一个函数中调用 return 语句,将 立即结束 此函数的执行并将它的参数作为函数的值返回。return 也会终止 eval() 语句或者脚本文件的执行。
public function fetch($sql){
$this->query($sql);
$data = array();
while($row=mysql_fetch_row($this->res)){
$data[] = $row;
}
return $data;
}
代码没有测试,思路应该没问题
这篇关于php - 这个类为什么只能获取一条数据??的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文