How can I pass the mySQL Result in Class to an external function?

291 Views Asked by At

I use a framework for MySQL queries. In the framework, I would like to call a separate function for tracking and logging. How can I pass the result array of MySQL Query to this function?

/* MySQL class: */
public function query($query, $map = [], $cleanQuery = '')  {           
    $raw = $this->raw($query, $map);
    $query = $this->buildRaw($raw, $map);
    return $this->exec($query, $map, $cleanQuery);
}

public function exec($query, $map = [], $cleanQuery = '')   {
    $this->logs = [[$query, $map]];     
    $statement = $this->pdo->prepare($query);

    if ($statement)     {
        foreach ($map as $key => $value)    {
            $statement->bindValue($key, $value[ 0 ], $value[ 1 ]);
        }

        $statement->execute();
        $affectedRows = $statement->rowCount();
        $errorinfos = $statement->errorInfo();

        my_own_tracking_function(.....???HOW CAN I PASS THE RESULT FROM MYSQL QUERY TO THESE FUNCTION????....);

        $this->statement = $statement;
        return $statement;
    }       
    return false;
}

/* Regular MySQL query in my code: */
$regular_result = $db->query($query)->fetchAll();

/* my own tracking function */
function my_own_tracking_function(...) { ... }
1

There are 1 best solutions below

7
George Dryser On

In our DB layer we use __destruct to close all connections and write log file like so:

public function __destruct() {
    // in debug mode write log file
    if (self::$DebugMode) self::_write_log_file();
    // close all active connections
    foreach (self::$CONNECTIONS as $connection) {
        if (is_object($connection)) {
            $connection->close();
        }
    }
}

or using custom parameter

    //add to top of your class
public $DataTracking = [];

in your method update the parameter

public function exec($query, $map = [], $cleanQuery = '')   {
$this->logs = [[$query, $map]];     
$statement = $this->pdo->prepare($query);

if ($statement)     {
    foreach ($map as $key => $value)    {
        $statement->bindValue($key, $value[ 0 ], $value[ 1 ]);
    }

    $statement->execute();
    $affectedRows = $statement->rowCount();
    $errorinfos = $statement->errorInfo();

    $this->DataTracking[] = 'Anything you need to log';

    $this->statement = $statement;
    return $statement;
}       
return false;

}

and pass it to your function like so - outside the class

$regular_result = $db->query($query)->fetchAll();   
my_own_tracking_function($db->DataTracking);