B-B.
B-B.

Reputation: 193

How to assign key:value pairs from SQL to JavaScript Object using PHP?

I have the following data in an SQL database

cname, ccode, colour
Great Britain, GB, 1
Italy, IT, 1
France, FR, 1
Spain, ES, 1

How can I create a JavaScript object like below?

var countries = {"GB":1, "IT":1, "FR":1, "ES":1}

So far, I have the following code;

PHP

$query2 = "SELECT ccode,colour FROM country_data WHERE 1";
$result2 = mysql_query($query2);
if (!$result2) {
  die('Invalid query: ' . mysql_error());
}

$rows2 = array();
  while($r2 = mysql_fetch_assoc($result2)) {
     $rows2[] = $r2;
}

JS

var colours = '<?php print json_encode($rows2); ?>';

Which returns:

[{"ccode":"GB","colour":"1"},{"ccode":"IT","colour":"1"},{"ccode":"FR","colour":"1"},{"ccode":"ES","colour":"1"}]

Upvotes: 1

Views: 201

Answers (2)

Imran Qamer
Imran Qamer

Reputation: 2263

change php code as told in others answers too and it should be like

$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
     $rows2[$r2['ccode']] = $r2['colour'];
}

if it does not work then try this:

$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
     $rows2["'".$r2['ccode']."'"] = $r2['colour'];
}

if it also does not work then try this:

$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
     $rows2[{$r2['ccode']}] = $r2['colour'];
}

Upvotes: 1

user2503896
user2503896

Reputation:

change this code

while($r2 = mysql_fetch_assoc($result2)) {
     $rows2[] = $r2;
}

to this one:

while($r2 = mysql_fetch_assoc($result2)) {
     $rows2[$r2['ccode']] = $r2['colour'];
}

Upvotes: 2

Related Questions