Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP array_push overwriting the pushed data

I seeing a rare behavior of the array_push php function. It’s like when I’m looping through the result rows of the query and pushing the complete array of data into a ‘parent’ array ($rdo), the values are beeing modified with the ones of the last row added.

This is my code:

$rdo = array();

if($sentencia = $general_con->prepare("SELECT monthly_price, name FROM subscription_plan WHERE deleted=0"))
{
    $sentencia->execute();

    $sentencia->store_result();
    $num_of_rows = $sentencia->num_rows;

    $sentencia->bind_result($row['monthly_price'], $row['name']);

    while($sentencia->fetch())
    {
        array_push($rdo, $row);

        echo print_r($rdo,1).'<br/><br/>';
    }
    $sentencia->close();
    die();
}

And this is the result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

It looks like this is an artifact of the way bind_result() uses references to the array elements. When you push $row onto $rdo, this is updating all those array elements.

I recommend you move away from using bind_result() and use fetch_assoc().

if($sentencia = $general_con->prepare("SELECT monthly_price, name FROM subscription_plan WHERE deleted=0"))
{
    $sentencia->execute();

    $result = $sentencia->get_result();
    
    while($row = $result->fetch_assoc())
    {
        array_push($rdo, $row);
        echo print_r($rdo,1).'<br/><br/>';
    }
    $sentencia->close();
    die();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading