0

i have some php to show result as JSON like this

$dp = $_GET['dp'];

$query = mysql_query("select trip_id, trip_desc from current_data where dispatcher='".$dp."'");

$json = array();    

while($row = mysql_fetch_assoc($query)){

    $tripdata["code"]=$row["trip_id"]." - ".$row["trip_code"];

    $json[] = $tripdata;

}

echo json_encode($json);

and result like this

[{"code":"S1.001 - UK"},{"code":"S1.002 - US"},{"code":"S1.003 - CA"}]

How to add value in First Result of my JSON, i want to result like this?

 [**{"code":"Select Country"}**,{"code":"S1.001 - UK"},{"code":"S1.002 - US"},{"code":"S1.003 - CA"}]

Thanks

mega6382
  • 9,211
  • 17
  • 48
  • 69
coco_nk4l
  • 21
  • 5
  • 2
    ***Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php).*** [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Nov 06 '17 at 13:29
  • 2
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Nov 06 '17 at 13:29
  • 2
    Push the first value to the array before the while loop. – Jay Blanchard Nov 06 '17 at 13:30
  • I know this method will risk with SQL Inject, but this Script only backend for Andorid APK. thanks for your response guys,,, ^_^ – coco_nk4l Nov 06 '17 at 13:48
  • What does that ^ mean? Are you saying it is OK to ignore the risk? – Jay Blanchard Nov 06 '17 at 13:52

1 Answers1

1

Push the first value to the array before the while loop:

$json[] = [
       'code' => 'Select Country',
     ];

while($row = mysql_fetch_assoc($query)){

    $tripdata["code"]=$row["trip_id"]." - ".$row["trip_code"];

    $json[] = $tripdata;

}

echo json_encode($json);

This will add a the desired value in the beginning of json.

Note:

mysql_* is deprecated as of and removed as of . So instead use mysqli_* or PDO.
Why shouldn't I use mysql_* functions in PHP?

Community
  • 1
  • 1
mega6382
  • 9,211
  • 17
  • 48
  • 69