0

I have a problem. I am using this code:

$sql = "SELECT Id, FileName FROM Templates ORDER BY DateTimeUploaded DESC";

if($result = $conn->query($sql))
{
    if($result->num_rows >= 1) 
    {           
        while($row = $result->fetch_object())
        {
            $arrTotal["Templates"] = array($row);
        }

        $result->free();

    }

    $arrTotal["Source"] = "media/templates/";
    echo json_encode($arrTotal);
}

But when I print the json, the $arrTotal["Templates"] has only one row, but it has 17 rows. What am I doing wrong?

3
  • 1
    $arrTotal["Templates"][] = array($row); Use double squares to add an entry. This is the shortcut for array_push(). Commented Jan 4, 2020 at 14:39
  • Yes, like @MarkusZeller said, you overwrite the value. Also, is not neccesary array($row), just $row when you add the object to array. Commented Jan 4, 2020 at 14:44
  • You could simplify to if($result->num_rows). Because any number not 0 will end in true. Commented Jan 4, 2020 at 15:03

1 Answer 1

1

You repeatedly assign values to an array member, need add [] to avoid this situation:

while($row = $result->fetch_object())
{
    $arrTotal["Templates"][] = array($row);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Also it's redundant to cast object to array. fetch_assoc already fetches array.
@u_mulder This is no cast from object to array. It is wrapping an object in an array. Casting would look like (array) $row. But I agree, it should not be neccessary wrapping the object in an array. So $arrTotal["Templates"][] = $row; should be enough.

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.