简体   繁体   中英

php oop select data from database

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'];
}

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'];
    }
}

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'];
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM