>我有这个函数
public function select($table, $rows = '*', $join = null, $where = null, $order = null, $limit = null){
$q = 'SELECT '.$rows.' FROM '.$table;
if($join != null){
$q .= ' JOIN '.$join;
}
if($where != null){
$q .= ' WHERE '.$where;
}
if($order != null){
$q .= ' ORDER BY '.$order;
}
if($limit != null){
$q .= ' LIMIT '.$limit;
}
if($this->tableExists($table)){
$query = @mysql_query($q);
if($query){
$this->numResults = mysql_num_rows($query);
for($i = 0; $i < $this->numResults; $i++){
$r = mysql_fetch_array($query);
$key = array_keys($r);
for($x = 0; $x < count($key); $x++){
if(!is_int($key[$x])){
if(mysql_num_rows($query) > 1){
$this->result[$i][$key[$x]] = $r[$key[$x]];
}else if(mysql_num_rows($query) < 1){
$this->result = null;
}else{
$this->result[$key[$x]] = $r[$key[$x]];
}
}
}
}
return true;
}else{
array_push($this->result,mysql_error());
return false; // No rows where returned
}
}else{
return false;
}
}
如果我使用此函数并且我的数据库为空,我的数组如下所示
Array( )
这很好!
如果我的数据库有 1 个条目,它看起来像这样:
Array
(
[id] => 1
[a] => 0
[b] => 0
)
这不好,因为如果它的条目数超过 1,则如下所示:
Array
(
[0] => Array
(
[id] => 1
[a] => 0
[b] => 0
)
[1] => Array
(
[id] => 2
[a] => 1
[b] => 1
)
)
我想要的是,带有一个条目的输出如下所示:
Array
(
[0] => Array
(
[id] => 1
[a] => 0
[b] => 0
)
)
如何更改函数才能获得此输出?
更改
if(mysql_num_rows($query) > 1){
$this->result[$i][$key[$x]] = $r[$key[$x]];
}else if(mysql_num_rows($query) < 1){
$this->result = null;
}else{
$this->result[$key[$x]] = $r[$key[$x]];
}
跟
if(mysql_num_rows($query) >= 1){
$this->result[$i][$key[$x]] = $r[$key[$x]];
}else{
$this->result = null;
}
您的错误在以下行:
if(mysql_num_rows($query) > 1){
你必须考虑到第一行,所以"> 1"变成"> 0"
整个函数应如下所示:
public function select($table, $rows = '*', $join = null, $where = null, $order = null, $limit = null){
$q = 'SELECT '.$rows.' FROM '.$table;
if($join != null){
$q .= ' JOIN '.$join;
}
if($where != null){
$q .= ' WHERE '.$where;
}
if($order != null){
$q .= ' ORDER BY '.$order;
}
if($limit != null){
$q .= ' LIMIT '.$limit;
}
if($this->tableExists($table)){
$query = @mysql_query($q);
if($query){
$this->numResults = mysql_num_rows($query);
for($i = 0; $i < $this->numResults; $i++){
$r = mysql_fetch_array($query);
$key = array_keys($r);
for($x = 0; $x < count($key); $x++){
if(!is_int($key[$x])){
if(mysql_num_rows($query) > 0)
$this->result[$i][$key[$x]] = $r[$key[$x]];
else
$this->result = null;
}
}
}
return true;
}else{
array_push($this->result,mysql_error());
return false; // No rows where returned
}
}else{
return false;
}
}