Forum Stats

  • 3,875,324 Users
  • 2,266,901 Discussions


In PHP convert mySQL null to ""

achana Member Posts: 52

How do I convert null values to an empty string i.e. ""

MySQL query returns a range of values, one of which is a null. The values are loaded into a PHP array, the string array is encoded in JSON, and then sent off to a Java app which massages the data and displays the results.

Java threw this error:


Caused by: org.json.JSONException: JSONObject["ContactName"] not a string.

    at org.json.JSONObject.getString(


So, I just simply convert all null values in the array to empty i.e "", but PHP did not convert nulls to "". Something wrong with my PHP codes, I think...

I'd like to handle this at the source, i.e. mySQL+PHP, rather than at the target i.e. Java.


if (mysqli_num_rows($result) > 0) { 

    /* instantiate an array to hold the JSON name-value pair objects */

    $response = array();

    /* In the loop, put data into array's name-value pair */

    while($row=mysqli_fetch_array($result))  {

         array_push($response, array("Company_ID"=>$row[0], "CoyName"=>$row[1], "ContactName"=>$row[2]));


    /* loop thru array, replace null with empty */

    foreach ($response as $key => $value) {

        if (is_null($value)) {

             $response[$key] = "";



    /* encode the data inside a JSON-array */

    echo json_encode(array("db_response"=>$response));

} else {

    $response = array("Error", "Message");

    echo json_encode(array("db_response"=>$response));