0

For some reason my php while loop is printing out the data twice and I cannot seem to figure why this is. Here is my code:

<?php
$json = '[';
$query  = "SELECT user_id, first_name, last_name, phone, phone_two, email FROM customers LIMIT 20";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
    $json .= "{ num: \"{$row['user_id']}\" },{ num: \"{$row['first_name']}\" },{ num: \"{$row['last_name']}\" },{ num: \"{$row['phone']}\" },{ num: \"{$row['phone_two']}\" },{ num: \"{$row['email']}\" },";
}

//Remove the last trailing comma
$json .= substr($json, 0, -1);

$json .= ']';

echo $json;
?>

When I echo the results out to the web browser, instead of having 20 customers, I have 40. However, it is the first 20 customers listed twice. I have no clue what could be causing this to happen.

2
  • 1
    Why are you doing all of that? Just build a PHP array in your loop and then use json_encode. Commented Aug 16, 2014 at 16:32
  • i agree with using the standard json_encode method. likewise it would be better to use rtrim($json, ',') just in case there isn't a trailing , (like when no users are returned) Commented Aug 16, 2014 at 17:09

1 Answer 1

1

Drop the .= for =

So, your statement

$json .= substr($json, 0, -1);

becomes

$json = substr($json, 0, -1);

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.