0

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:

enter image description here

4
  • Did you mean to write while($row = $sentencia->fetch())? Because right now you're not changing $row anywhere. Commented Jan 26, 2022 at 21:20
  • I think this is due to the way bind_results() binds to references. I'm not sure why this is happening, since array_push() should make a copy of $row. Commented Jan 26, 2022 at 21:22
  • @TimRoberts He's changing it with bind_result(). Commented Jan 26, 2022 at 21:22
  • @TimRoberts like Barmar commented, I'm binding the results into the $row array with bind_results, and then in the while looping throgh the result length to access every row Commented Jan 26, 2022 at 21:24

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, this works! I don't know what is the issue with the other way, but this solution works just fine :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.