dpsr1670
dpsr1670
2016-05-16 02:01

php oop从数据库中选择数据

已采纳

I'm trying to display some data stored into the database and i have this function but i don't know how it works :

public function resultToArray($result){

        if(is_a($result, 'mysqli_result') && $result->num_rows > 0) {

            $myArrayResult = array ();
            while ($row = $result->fetch_assoc()) {

                $myArrayResult[] = $row;
            }

            return ($myArrayResult);
        }

        else {

            return ("Invalid Formart or Empty Result");
        }
    }

How can i use this in my fron-end? I've tried this method but it failed...

$listar = new classes_DbManager;
$result ="Select * FROM jobs_offers";
$query = $listar->resultToArray($result);

if(mysqli_affected_rows>0){
    echo $row['username'];
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dsarttv037029 dsarttv037029 5年前

    without looking at the rest of your custom class, I can only guess that you are needing to execute the statement before retrieving the results. From your resultToArray function, it looks like it's making a call to mysqli_result which requires a result set to work.

    search for something inside the classes_DbManager class that executes a query function first, it might contain code that looks something like $result = $mysqli->query("$sql_query")

    my best guess would be its usage requiring something like this:

    $listar = new classes_DbManager;
    $query = "Select * FROM jobs_offers";
    $result = $listar->executeQuery($query);
    $query = $listar->resultToArray($result);
    
    if(mysqli_affected_rows>0){
        echo $row['username'];
    }
    
    点赞 评论 复制链接分享
  • duangu8264 duangu8264 5年前

    This method (resultToArray) dont run the query, this only return the associative array from a result. This Class should have a runQuery method.

    点赞 评论 复制链接分享
  • drwu24647 drwu24647 5年前

    I don't know what ORM/Database manager this is, but you're almost there. What you need to do is actually run the query first. Then you pass that result to the function.

    It would look something like this:

    $result = $listar->RUN_THE_QUERY("Select * FROM jobs_offers");
    $result_set = $listar->resultToArray($result);
    

    Replace RUN_THE_QUERY with the method that actually runs/executes the query.


    After that, you'll be able to run through the $result_set and echo it out:

    if(is_array($result_set)) {
        foreach($result_set as $_result) {
            echo $result['username'];
        }
    }
    
    点赞 评论 复制链接分享

相关推荐