0

I want to give some data from a MySQL database to a Android App via JSON.

So far i have written this php script to give me the JSON object:

$result = mysqli_query($con,"SELECT * FROM job");

$row = mysqli_fetch_assoc($result); 

while($row = mysqli_fetch_assoc($result)){
  $output[] = $row;
}

print(json_encode($output));

I have found out by accident that when I dont add the line "$row = mysqli_fetch_assoc($result);" before the while-loop it doesn`t return anything. But when I do add this line like in the example the JSON object doesnt contain the first element.

I believe its because of this line where $row already contains the first line.

Hopefully you can help me :)

4
  • How many rows is it returing? Insert this after the query : echo mysqli_num_rows($result);. You have to remove the line $row=mysqli_fetch_assoc($result);. Commented Oct 20, 2016 at 20:58
  • not possible. PHP doesn't care where/how you do the fetch call. whether it's inside the while or just before it, you'll STILL be fetching a row from the db. all you're doing is throwing away that first row, unless you ALSO have $output[] = $row; before the while starts. Commented Oct 20, 2016 at 21:01
  • when I dont add the line before the while-loop it doesn`t return anything Unpossible..... Commented Oct 20, 2016 at 21:04
  • what's the value of $row you get before the while loop? Commented Oct 21, 2016 at 8:23

1 Answer 1

1

With purpose to figure out what wrong with your query you have to do something like this:

if ($result = mysqli_query($db, $sql)) {
    // Here you can see and check count of rows in your result set.
    $numRows = mysqli_num_rows($result);
    // ...
} else {
    // Here you can see and check and understand error.
    var_export(mysqli_error($db));
}

with purpose to traverse all your rows from result set you have to do:

while ($row = mysqli_fetch_assoc($result)) {
    var_export($row);
}

and you must not have $row = mysqli_fetch_assoc($result) before while loop.

Sign up to request clarification or add additional context in comments.

Comments

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.