1

I have a database with a tabled named options. In this table I have 3 fields

  1. id of type int autoincrement
  2. option_name of type varchar
  3. option_value of type varchar

Assume I have the following to records inserted already

  1. '1','homepage_title','Home'
  2. '2','index_page_title','Index Page'

I have a php script as follows

<?php
header("Access-Control-Allow-Origin: *");
//set timezone becuase some servers are jsut wrong
define('TIMEZONE', 'Europe/Athens');
date_default_timezone_set(TIMEZONE);

//Connect & Select Database
mysql_connect("somehost","simeuser","somepass") or die("could not connect server");
mysql_select_db("somedbdb") or die("could not connect database");

function getOptions(){
    $sqldata = mysql_query("SELECT * FROM `options`");
    $rows = array();
    while($r = mysql_fetch_array($sqldata)) {
        $rows[$r['option_name']][$r['option_value']][]=$r['option_value'];
    }

    echo json_encode($rows);
}
getOptions();
?>

It works because the script returns something like this

{"homepage_title":{"Home":["Home"]},"index_page_title":{"index page":["index page"]}}

I am sure the line that is incorrect is this one

$rows[$r['option_name']][$r['option_value']][]=$r['option_value'];

I just can't figure out what I need to fix. My intensions is to call javascript as follows

$.get("http://localhost/test-app/get_app_settings.php",function(data){
    var json = JSON.parse(data);
    console.log(JSON.stringify(json));
    alert("homepage title was "+json['homepage_title']);
    alert("index page title was "+json['index_page_title']);
});

I get Object object instead of Homepage which I expected in homepage_title and Index page which I expect in index_page_title.

I am sure it something really stupid but I just can see it.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
George Nicolaou
  • 75
  • 2
  • 13
  • 1
    Please dont use [the `mysql_` database extension](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), it is deprecated (gone for ever in PHP7) Specially if you are just learning PHP, spend your energies learning the `PDO` database extensions. [Start here](http://php.net/manual/en/book.pdo.php) its really pretty easy – RiggsFolly Jul 30 '16 at 19:27
  • Can you describe what it is you actually want as a result – RiggsFolly Jul 30 '16 at 19:31
  • As I stated I want to be able to say something like alert("homepage title was "+json['homepage_title']); alert("index page title was "+json['index_page_title']); and get the option_value based on the option_name – George Nicolaou Jul 30 '16 at 19:34
  • Please try `$rows[$r['option_name']]=$r['option_value'];` – Ismail RBOUH Jul 30 '16 at 19:40

1 Answers1

0

What's your intention of doing this?

$rows[$r['option_name']][$r['option_value']][]=$r['option_value'];

Maybe you want just this?

$rows[$r['option_name']]=$r['option_value']; 
Artem Kolontay
  • 840
  • 1
  • 10
  • 16