Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i've been searching all over and can't get any solution to work... this is my code, the problematic area is how to create 1 large array of per-sql-row array: (the commented-out line is the one causing the error).

$result = mysqli_query($con, "SELECT * FROM  `Orders` WHERE  `userID` = " . $objData->userid . " ORDER BY  `recievedDate` DESC LIMIT 10");
        $resArray = array();    
        if ($result->num_rows > 0) {
            while($row = $result->fetch_row())
            {
                $tempArr = array("orderid" => $row[0], "orderdate" => $row[2], "orderstatus" => $row[4]);
                //$resArray = array_push((array)$resArray, (array)$tempArr);  <== problematic line commented out
            }
            echo json_encode($resArray);        
        } else {                
            echo "";    
        }

thanks!

share|improve this question
1  
When using mysqli you should be using parameterized queries and bind_param to add user data to your query. Never use string interpolation to accomplish this. A simple mistake can have disastrous consequences. –  tadman Nov 15 '13 at 15:54
 
OK i will look into it. but this is not the problem here. –  tarkil Nov 15 '13 at 15:58
add comment

2 Answers

up vote 2 down vote accepted

The simple answer is to push your $temparr array to $resArray like this:

$resArray[] = $tempArr;

Note you could also use array_push() if you really wanted to.

Not sure what all your query is returning, but did you know you could also just get your query results as an array to begin with?

$resArray = $result->fetch_array(MYSQLI_ASSOC);

If your query is returning more than you need in your array, just limit the query:

$result = mysqli_query($con, "SELECT orderid, orderdate, orderstatus FROM  `Orders` ...");
$resArray = $result->fetch_array(MYSQLI_ASSOC);

Done!

share|improve this answer
 
thanks! really helpful. i didnt know the fetch_array was useful when more then 1 row was returned. –  tarkil Nov 15 '13 at 16:09
add comment

Beside other important aspect you are assigning the result of array_push $resArray = array_push((array)$resArray, (array)$tempArr), so the json_encode($resArray) gets a number and not the array you need.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.