【问题标题】:How to get multiple rows from mysql & PHP with this function如何使用此函数从 mysql 和 PHP 获取多行
【发布时间】:2016-07-15 09:52:07
【问题描述】:

我有这个只返回一行的函数,我该如何修改该函数使其返回多行?

public function getVisitors($UserID)
{   
$returnValue = array();
$sql = "select * from udtVisitors WHERE UserID = '".$UserID. "'";

$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}

【问题讨论】:

  • 固定数量的行还是所有选定的行?
  • 所有选定的行,我尝试使用@HankyPanky 之前发送给我的行,但它检索到数组中的 1 行

标签: php mysql mysqli


【解决方案1】:

mysqli 中有一个函数,叫做 fetch_all(),所以,从字面上回答你的问题,它会是

public function getVisitors($UserID)
{   
    $sql = "select * from udtVisitors WHERE UserID = ".intval($UserID);
    return $this->conn->query($sql)->fetch_all();
}

但是,这是不对的,因为您没有使用准备好的语句。所以正确的功能应该是

public function getVisitors($UserID)
{   
    $sql = "select * from udtVisitors WHERE UserID = ?";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("s", $UserID);
    $stmt->execute();
    $res = $stmt->get_result();
    return $res->fetch_all();
}

【讨论】:

    【解决方案2】:

    我建议将它们存储在关联数组中:

    $returnValue = array();
    
    while($row = mysqli_fetch_array($result)){
    
        $returnValue[] = array('column1' => $row['column1'], 'column2' => $row['column2']); /* JUST REPLACE NECESSARY COLUMN NAME AND PREFERRED NAME FOR ITS ASSOCIATION WITH THE VALUE */
    
    } /* END OF LOOP */
    
    return $returnValue;
    

    当你调用返回值时,你可以这样做:

    echo $returnValue[0]['column1']; /* CALL THE column1 ON THE FIRST SET OF ARRAY */
    echo $returnValue[3]['column2']; /* CALL THE column2 ON THE FOURTH SET OF ARRAY */
    

    您仍然可以使用循环调用所有值。

    $counter = count($returnValue);
    
    for($x = 0; $x < $counter; $x++){
        echo '<br>'.$rowy[$x]['column1'].' - '.$rowy[$x]['column2'];
    }
    

    【讨论】:

    • 这是我见过的已经存在的关联数组创建关联数组最没用的方法。
    猜你喜欢
    • 1970-01-01
    • 2017-01-10
    • 2014-09-19
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    相关资源
    最近更新 更多