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);
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
循环体中,你的函数已经被
return,所以只能返回第一次循环的内容,解决办法就是在循环中将内容放在数组中,循环结束再返回数组php手册 Return
代码没有测试,思路应该没问题
每次fetch出来的只有一行数据,不能直接return,得拼接起来,再全部return
mysql_fetch_row()这个函数获取的不是全部的结果,而是获得查询结果中当前行的数据信息,在被引用后,自动滑动至下一行。
你的代码中,刚获取了第一行就return了,没有继续操作下一行。改成mysql_fetch_array()试试。
mysql_fetch_row — 从结果集中取得一行作为枚举数组.循环第一条就return,所以就打印一条.
while里面放return。。。循环一次函数就结束了。。所以就出来第一条枚举数据了。while里面先存数组里,while循环体外再return这个数组