0

Throught an AJAX call I want to pick some data from DB and send back to client. $result is return value of SELECT QUERY

Case1:This works fine

$str = "[";
    while($row = mysqli_fetch_assoc($result)) {
          $str = $str ."{". 

                            '"Name":'. '"'. $row["Name"] . '"'  

                       . "},";
    }
}
$str = $str . "]";
echo str;

CASE2:This works fine too:

$str = "[";
    while($row = mysqli_fetch_assoc($result)) {
          $str = $str ."{". 

                            '"ID":'. '"'. $row["ID"] //SEE HERE

                       . "},";
    }
} else {
    echo "0 results";
}

$str = $str . "]";

echo $str;

CASE3: BUT FOLLOWING GIVES error with 500()

$str = "[";
    while($row = mysqli_fetch_assoc($result)) {
          $str = $str ."{". 

                            '"ID":'. '"'. $row["ID"] . '",'   //SEE HERE
                            '"Name":'. '"'. $row["Name"] . '"'


                       . "},";
    }
} else {
    echo "0 results";
}

$str = $str . "]";

echo $str;

I want to send echo str after making it in JSON format and parse it at client side using `JSON.parse(). Case1 and 2 work fine when I have only one key-value pair. But as soon as I put 2 key-value pairs I get error:

POST https://******************.php 500 ()
2
  • this isnt the best way my friend Commented Feb 5, 2017 at 13:23
  • 1
    @HBensiali I know. Can you tell me other way so that I can receive array of JS object on client side? Commented Feb 5, 2017 at 13:24

2 Answers 2

3

You really need to use the appropriate functions.

Get into good programming habits.

$rtn = []; //create array
while($row = mysqli_fetch_assoc($result)){
    //push result into array
    $rtn[] = ['ID'=> $row["ID"], 'Name'=> $row['Name']]; 
}

if($rtn)//if array has entries
    echo json_encode($rtn);//encodes result to json
else
    echo "0 results";
Sign up to request clarification or add additional context in comments.

Comments

1

It return 500, because you have error in your script. You can add below code and check where is the mistake.

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Probably in your code is missing dot. Check this:

$str = $str . "{" .

    '"ID":' . '"' . $row["ID"] . '",' .  
    '"Name":' . '"' . $row["Name"] . '"'

. "},";

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.