0

I am trying to rewrite one of my old code to mysqli, because I am getting Allowed memory size exhausted errors. I read some tips to use mysqli_real_query, which will activate the query without loading all the records in RAM.

My old code:

<?
$sql = "SELECT * FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) WHERE p.status = 1";

$query   = $this->db->query($sql);
$results = $query->rows;

foreach ($results as $result) {
    print_r("$result");

    /* Output:
    Array
    (
        [product_id] => 17763
        [feed_product_id] => 0
        [import_id] => 0
        [name] => Name
        [model] => MODEL
        [sku] => 390348
        [upc] => 390348
        ...
    )  
    */  
}

?>

My new code so far:

<?

$db = mysqli_connect('localhost', 'username', 'pwd', 'db');

$sql = "SELECT * FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_description pd ON (p.product_id = pd.product_id) WHERE p.status = 1";

mysqli_real_query($db, $sql);
$result = mysqli_use_result($db);

while ($row = mysqli_fetch_row($result)) {
    print("Test: " . $row);

    /* Output:
    (
        [0] => 17763
        [1] => 0
        [2] => 0
        [3] => Name
        [4] => MODEL
        [5] => 390348
        [6] => 390348
    */    
}

?>

How can I get the same results in the new code? My new array keys are 0, 1, 2, 3... instead of column names.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Adrian
  • 2,576
  • 9
  • 49
  • 97
  • 1
    Just change `fetch_row` to [`fetch_assoc`](https://www.php.net/manual/en/mysqli-result.fetch-assoc.php) – Nick Jan 16 '21 at 22:26
  • You have to instruct it to get an [associative result](https://www.php.net/manual/en/mysqli-result.fetch-assoc). – El_Vanja Jan 16 '21 at 22:26
  • 3
    If you're exceeding the allowed memory size then either you have it set to a ridiculously low level, or your query is returning far too much data to be useful. I'd tackle those issues before rewriting the code. – Tangentially Perpendicular Jan 16 '21 at 22:26
  • This is not what `mysqli_real_query` is for. In fact forget about this function. If your code is exceeding the memory limit then fix the problem. Reduce the number of rows or investigate what is causing you to use up so much memory. – Dharman Jan 16 '21 at 23:33

0 Answers0