I'm trying to get data from my database into a chart. The charts i'm using are from fusioncharts. If i print the row_cnt's they give me the correct information but in the table it gives me the wrong/no information.
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<script src="includes/fusioncharts.js"></script>
<script src="includes/fusioncharts.charts.js"></script>
</head>
<body>
<?php
$result = $dbhandle->query("SELECT * FROM email");
$result2 = $dbhandle->query("SELECT * FROM email WHERE status='1'");
$result3 = $dbhandle->query("SELECT * FROM email WHERE status='0'");
$row_cnt = $result->num_rows;
$row_cnt2 = $result2->num_rows;
$row_cnt3 = $result3->num_rows;
// If the query returns a valid response, prepare the JSON strin
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array
(
"caption" => "Aantal geregistreerde emails",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues" => "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => 'active emails',
"value" => $row_cnt,
)
);
}
row_cnt gives me the total amount of emails
row_cnt2 gives me the total active emails
row_cnt3 gives me the total inactive/signedoff emails
in the chart it only gives me the total registered emails (row_cnt) and when i want to try to add the other 2 in the chart its not giving me any information. The bar with the total registered emails is also display twice. Someone know what im doing wrong or how to do this?
I want to display 3 different bars 1 needs to be the total registered emails bar number 2 needs to be the active ones and bar number 3 the inactive ones.
I think, you should simply push the three values $row_cnt, $row_cnt2 and $row_cht3 one after another.
Look at this:
// The `$arrData` array holds the chart attributes and data
// First, add the chart array that describes the chart itself.
$arrData = array(
"chart" => array
(
"caption" => "Aantal geregistreerde emails",
...
...
"showAlternateHGridColor" => "0"
)
);
// Second, we add the values displayed by the bars.
$arrData["data"] = array();
// In this code example, we add the values each by each as they are available in three single variables.
// 1. Total:
array_push($arrData["data"], array(
"label" => 'total emails',
"value" => $row_cnt
));
// 2. Active:
array_push($arrData["data"], array(
"label" => 'active emails',
"value" => $row_cnt2
));
// 3. Active:
array_push($arrData["data"], array(
"label" => 'inactive emails',
"value" => $row_cnt3
));
But maybe you need to loop, as the number of processed values couldĀ change and you need to be flexible. In that case I recommend to collect the values in a separate array first and then loop the separate array. Like this:
...
// Second, we add the values displayed by the bars.
$arrData["data"] = array();
// In this code example, we for an array first and are able to loop over it.
$myBarArray = array();
// 1. Total:
$myBarArray[] = array(
"label" => 'total emails',
"value" => $row_cnt
);
// 2. Active:
$myBarArray[] = array(
"label" => 'active emails',
"value" => $row_cnt2
);
// 3. Active:
$myBarArray[] = array(
"label" => 'inactive emails',
"value" => $row_cnt3
);
// Now we can loop this array, or pass it to a further function or whatever:
foreach ($myBarArray as $bar) {
$arrData["data"][] = $bar;
}
Either way, iterating over $result as in your question does not seem to be the right way.
Also please note the syntax with [] instead of array_push(), which sometimes is more readable.
Hope this helps :-)
Related
I'm getting the Warning Error while sending QUERY packet in PID= when I use a SELECT statement that only gets 5 rows of data from 2 columns, then make the script sleep for 10 minutes before waking up to continue an INSERT into the db.
If I close the connection after the SELECT statement and reopen the connection just before the INSERT, then everything works fine and no error is produced.
I can't figure out why this is happening. I'm on a public shared server.
Select
The values selected are:
Seller which is 10 characters in length and Token which is 872 in length.
include('con.php');
if ($result = $con->query("SELECT Seller,Token FROM `Sellers`")) {
$sellers = $result->fetch_all(MYSQLI_ASSOC);
$result->close();
}
$con->close();
Sleep
sleep(600);
Insert
All values being inserted are minimal in length of which 21 characters is the longest in the column jobType. Total of 5 rows being inserted from the foreach loop.
include('con.php');
foreach(...) {
$insert = "INSERT INTO `jobStatus` (ack, jobId, RefId, Type, Status, error, percent, Seller, creationTime, completionTime) VALUES ('$ack', '$jid', '$frid', '$jtyp', '$jstat', '$errc', '$pcom', '$sid', '$crtime', '$cotime')";
if($con->query($insert)) {
echo "inserted into db successfully.\n";
} else {
echo "not inserted into db. Query Failed.\n";
}
}
$con->close();
Above code works without an error because of closing and reopening the connection in between the statements.
I want it to work without the error when I keep the connection open after the SELECT and then closing the connection after the INSERT.
Can someone point out what I need to do in order to accomplish this?
Note: I already have the set_time_limit set to 0 in my script.
set_time_limit(0);
Here is the code which produces the error.
Code that causes error
Select
include('con.php');
if ($result = $con->query("SELECT Seller,Token FROM `Sellers`")) {
$sellers = $result->fetch_all(MYSQLI_ASSOC);
$result->close();
}
Sleep
sleep(600);
Insert
foreach($sellers as $seller) {
$insert = "INSERT INTO `jobStatus` (ack, jobId, RefId, Type, Status, error, percent, Seller, creationTime, completionTime) VALUES ('$ack', '$jid', '$frid', '$jtyp', '$jstat', '$errc', '$pcom', '$sid', '$crtime', '$cotime')";
if($con->query($insert)) {
echo "inserted into db successfully.\n";
} else {
echo "not inserted into db. Query Failed.\n";
}
}
$con->close();
Update:
Here are the results of SHOW VARIABLES LIKE '%timeout'
$SESSION_VARIABLES = array(
array(
"Variable_name" => "connect_timeout",
"Value" => "10",
),
array(
"Variable_name" => "delayed_insert_timeout",
"Value" => "300",
),
array(
"Variable_name" => "innodb_flush_log_at_timeout",
"Value" => "1",
),
array(
"Variable_name" => "innodb_lock_wait_timeout",
"Value" => "50",
),
array(
"Variable_name" => "innodb_rollback_on_timeout",
"Value" => "OFF",
),
array(
"Variable_name" => "interactive_timeout",
"Value" => "30",
),
array(
"Variable_name" => "lock_wait_timeout",
"Value" => "86400",
),
array(
"Variable_name" => "net_read_timeout",
"Value" => "30",
),
array(
"Variable_name" => "net_write_timeout",
"Value" => "60",
),
array(
"Variable_name" => "slave_net_timeout",
"Value" => "60",
),
array(
"Variable_name" => "thread_pool_idle_timeout",
"Value" => "60",
),
array(
"Variable_name" => "wait_timeout",
"Value" => "30",
),
);
The mysql connection times out after 30 seconds, i. e., gets closed automatically after 30 seconds of inactivity and there is nothing you can do about it (except polling it every 29 seconds while sleeping). I suggest you use mysqli::ping after the sleep to reconnect if necessary:
if ($con->ping()) {
// foreach... insert
}
I am trying to get multidimensional array out of query and for some reasons it does not work.
I use query to retrieve data from mysql.
$sql = "SELECT Id, UserID, TimeAction, Command FROM users_checked WHERE UserId = 4 AND date(TimeAction) = '2016-12-05 '";
$q=$conn->query($sql);
$data = array();
while($r=$q->fetchAll((PDO::FETCH_ASSOC))){
$data[]=$r;
}
Array output
I should get array like printed below
$data = array(
array(
"Id" => "1",
"UserID" => "1",
"TimeAction" => "2016-11-29 08:00:00",
"Command" => "Prijava"
),
array(
"ID" => "1",
"USERID" => "1",
"TimeAction" => "2016-11-29 10:05:14",
"Command" => "Odjava"
),
array(
"Id" => "1",
"UserID" => "1",
"TimeAction" => "2016-11-29 12:22:14",
"Command" => "PoslovniIzlazak"
),
array(
"ID" => "1",
"USERID" => "1",
"TimeAction" => "2016-11-29 13:32:14",
"Command" => "Prijava"
),
array(
"ID" => "1",
"USERID" => "1",
"TimeAction" => "2016-11-29 16:00:00",
"Command" => "Odjava"
),
);
fetchAll - Returns an array containing all of the result set rows where as fetch - Fetches the next row from a result set.
So you have to use fetch instead of fetchAll if you want the data row wise.
Try this code.
while ($r = $q->fetch(PDO::FETCH_ASSOC))
{
$data[] = $r;
}
Reference:
fetch
fetchAll
You should probably use fetch_assoc() instead of fetch_all in your for loop, this way you can push the data you want into your array for each row of your mysql query result.
It would look like this :
$data = array();
while ($row = $r->fetch_assoc()) {
$row_array = array(
"Id" => row['Id'],
"UsedID" => row['UserID'],
"TimeAction" => row['TimeAction'],
"Command" => row['Command']
);
array_push($data, $row_array);
}
Please note I didn't test the code, I'm doing this by head.
Also, I'm guessing you didn't mean to write all Ids to "1" in your example.
I have the following code which produces this:
If you look at my code, I'm actually trying to rendor 2 charts, and put them on separate table rows so they will be one on top of the other. That's why there are the table lines bunched up around the bottom of the graph. When I delete all the code for my first graph, my second graph shows up on the webpage, but if it is there it does not show up. Is there something I am missing?
I was thinking that maybe I had to include the line: dbhandle->close after each graph, but that wouldn't make much sense since it is just the connection to my MySQL database.
<?php
include("includes/fusioncharts.php");
// variables declared before
$dbhandle = new mysqli($hostdb, $userdb, $passdb, $namedb);
// Render an error message, to avoid abrupt failure, if the database connection parameters are incorrect
if ($dbhandle->connect_error) {
exit("There was an error with your connection: ".$dbhandle->connect_error);
}
?>
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="fusioncharts/js/fusioncharts.js"></script>
</head>
<body>
<?php
$strQuery = "SELECT Department, SUM(Quantity) AS Quantity FROM Scrap GROUP BY Department ORDER BY Department";
// Execute the query, or else return the error message.
$result = $dbhandle->query($strQuery) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result) {
// The `$arrData` array holds the chart attributes and data
$arrData = array(
"chart" => array(
"caption" => "Scrap by Department",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result)) {
array_push($arrData["data"], array(
"label" => $row["Department"],
"value" => $row["Quantity"],
//"link" => "deptDrillDown.php?Department=".$row["Department"]
)
);
}
$jsonEncodedData = json_encode($arrData);
$columnChart = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-1", "json", $jsonEncodedData);
// Render the chart
$columnChart->render();
}
$strQuery2 = "SELECT ScrapDate, SUM(Quantity) AS Quantity FROM Scrap WHERE Department = 'NW' GROUP BY ScrapDate ORDER BY ScrapDate";
// Execute the query, or else return the error message.
$result2 = $dbhandle->query($strQuery2) or exit("Error code ({$dbhandle->errno}): {$dbhandle->error}");
// If the query returns a valid response, prepare the JSON string
if ($result2) {
// The `$arrData` array holds the chart attributes and data
$arrData2 = array(
"chart" => array(
"caption" => "By Week",
"paletteColors" => "#0075c2",
"bgColor" => "#ffffff",
"borderAlpha"=> "20",
"canvasBorderAlpha"=> "0",
"usePlotGradientColor"=> "0",
"plotBorderAlpha"=> "10",
"showXAxisLine"=> "1",
"xAxisLineColor" => "#999999",
"showValues"=> "0",
"divlineColor" => "#999999",
"divLineIsDashed" => "1",
"showAlternateHGridColor" => "0"
)
);
$arrData2["data"] = array();
// Push the data into the array
while($row = mysqli_fetch_array($result2)) {
array_push($arrData2["data"], array(
"label" => $row["ScrapDate"],
"value" => $row["Quantity"],
//"link" => "deptDrillDown.php?Department=".$row["Department"]
)
);
}
$jsonEncodedData2 = json_encode($arrData2);
$columnChart2 = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-2", "json", $jsonEncodedData2);
// Render the chart
$columnChart2->render();
// Close the database connection
$dbhandle->close();
}
?>
<table border='1'>
<tr>
<td>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</td>
</tr>
<tr>
<td>
<div id="chart-2"><!-- Fusion Charts will also be rendered here--></div>
</td>
</tr>
</table>
</body>
</html>
SOLVED:
I looked up the constructor for the FusionCharts object, and the 2nd parameter is a unique identifier for the chart. Since I copy and pasted before, I did not think to change it. I set it to chart 2 and now both charts render properly.
This is what it used to be:
$columnChart2 = new FusionCharts("column2D", "myFirstChart" , 600, 300, "chart-2", "json", $jsonEncodedData2);
This is the updated code:
$columnChart2 = new FusionCharts("column2D", "mySecondChart" , 600, 300, "chart-2", "json", $jsonEncodedData2);
I am trying to convert an array obtained by the code below using non-deprecated techniques with php pdo:
$stm = $conn->prepare("SELECT * FROM mysqltable");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
print_r($results);
to the following format required for fusioncharts to be used
[
{
label: "CJ Anderson",
value: "25"
},
{
label: "Imran Tahir",
value: "25"
},
...
...
]
The original array is as follows:
Array (
[0] => Array (
[Id] => 6
[Number] => 1234567890
[Visits] => 1
[Name] => John
)
[1] => Array (
[Id] => 7
[Number] => 1236549871
[Visits] => 9
[Name] => Jerry
)
[2] => Array (
[Id] => 8
[Number] => 2147483647
[Visits] => 3
[Name] => Jane
)
)
Any help would be appreciated, thanks.
EDIT:
As I commented below. I have a full php file that works if you put data in manually. I can't get it to work though when I put the $jsonEncodedData in though. Thoughts?
<html>
<head>
<title>FusionCharts XT - Column 2D Chart - Data from a database</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- You need to include the following JS file to render the chart.
When you make your own charts, make sure that the path to this JS file is correct.
Else, you will get JavaScript errors. -->
<script src="fusioncharts/js/fusioncharts.js"></script>
</head>
<body>
<?php
try {
# MySQL with PDO_MYSQL
$mysql_host = 'host';
$mysql_database = 'table';
$mysql_username = 'user';
$mysql_password = 'pass';
$conn = new PDO("mysql:host=$mysql_host; dbname=$mysql_database", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
}
catch(PDOException $e) {
echo $e->getMessage();
}
// Form the SQL query that returns the top 10 most populous countries
// Execute the query, or else return the error message.
$stm = $conn->prepare("SELECT Name, Visits FROM mysqltable"); //WHERE Area :SelArea");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
include("fusioncharts.php");
$jsnarray = array();
foreach($results as $k => $v){
$jsnarray[] = array('label' => $results[$k]['Name'], 'value' => $results[$k]['Visits']);
};
$jsonEncodedData=json_encode($jsnarray);
new FusionCharts("type of chart",
"unique chart id",
"width of chart",
"height of chart",
"div id to render the chart",
"type of data",
"actual data");
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": //$jsonEncodedData}'); <---I tried to insert this after "data":but no results unlike if you put raw data**
[
{
"label":"Bakersfield Central",
"value":"880000"
},
{
"label":"Garden Groove harbour",
"value":"730000"
},
{
"label":"Los Angeles Topanga",
"value":"590000"
},
{
"label":"Compton-Rancho Dom",
"value":"520000"
},
{
"label":"Daly City Serramonte",
"value":"330000"
}
]
}');
// Render the chart
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
==============Edit 12/28/15==========
Tried the following code with no results, Question I have is shouldn't we end in "}" as they require that:
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": ' . $jsonEncodedData);
//}';
// Render the chart
print_r($columnChart);
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
I wanted to post the array differences as well between the "manual" method and the "fetch method (above in this edit).
With fetch:
FusionCharts Object ( [constructorOptions:FusionCharts:private] => Array ( >[type] => column2d [id] => ex1 [width] => 600 [height] => 400 [renderAt] => >chart-1 [dataFormat] => json [dataSource] => { "chart": { >"caption":"Harry's SuperMart", "subCaption":"Top 5 stores in last month by >revenue", "numberPrefix":"$", "theme":"ocean" }, "data": >[{"label":"John","value":"125"},{"label":"Jerry","value":"125"},{"label":"Jane","value":"125"}] ) [constructorTemplate:FusionCharts:private] => >[renderTemplate:FusionCharts:private] => )
With Manual Method (that works):
FusionCharts Object ( [constructorOptions:FusionCharts:private] => Array ( >[type] => column2d [id] => ex1 [width] => 600 [height] => 400 [renderAt] => >chart-1 [dataFormat] => json [dataSource] => { "chart": { >"caption":"Harry's SuperMart", "subCaption":"Top 5 stores in last month by >revenue", "numberPrefix":"$", "theme":"ocean" }, "data": [ { >"label":"Bakersfield Central", "value":"880000" }, { "label":"Garden Groove >harbour", "value":"730000" }, { "label":"Los Angeles Topanga", >"value":"590000" }, { "label":"Compton-Rancho Dom", "value":"520000" }, { >"label":"Daly City Serramonte", "value":"330000" } ] } ) >[constructorTemplate:FusionCharts:private] => >[renderTemplate:FusionCharts:private] => )
I see two differences offhand, the manual inserts spaces around "data" and the ending } parameter.
There is an automatic (and much much easier) way of doing this:
$stm = $conn->prepare('SELECT Name AS label, Visits AS value FROM mysqltable;');
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
$jsonEncodedData = json_encode($results);
echo $jsonEncodedData;
Output (locally tested):
[{"label":"Foo","value":"5"},{"label":"Bar","value":"15"}]
That way you can just use it like this:
$columnChart = new FusionCharts('...
...
"data": ' . $jsonEncodedData . '}');
Note the . '}' in the end.
Before Edit:
You could do something like this:
// This part is just for running purposes
$foo = array (
0 => Array (
'Id' => 6,
'Number' => 1234567890,
'Visits' => 1,
'Name' => 'John'
),
1 => array (
'Id' => 7,
'Number' => 1236549871,
'Visits' => 9,
'Name' => 'Jerry'
),
2 => array (
'Id' => 8,
'Number' => 2147483647,
'Visits' => "3", // Example to output quoted
'Name' => 'Jane'
)
);
$bar = array();
foreach($foo as $k => $v){
$bar[] = array('label' => $foo[$k]['Name'], 'value' => $foo[$k]['Visits']);
}
echo json_encode($bar);
Output:
[{"label":"John","value":1},{"label":"Jerry","value":9},{"label":"Jane","value":"3"}]
Compare with yours (from question) in one line:
[{label: "CJ Anderson",value: "25"},{label: "Imran Tahir",value: "25"},...]
Note: I assumed that value is represented by Visit and label by Name.
Read more about json_encode.
As a summary this is the piece that solved the issue including FirstOne's foreach statement:
$stm = $conn->prepare("SELECT Name, Visits FROM mysqltable"); //WHERE Area :SelArea");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
include("fusioncharts.php");
$jsnarray = array();
foreach($results as $k => $v){
$jsnarray[] = array('label' => $results[$k]['Name'], 'value' => $results[$k]['Visits']);
};
$jsonEncodedData=json_encode($jsnarray);
//print_r($jsonEncodedData);
new FusionCharts("type of chart",
"unique chart id",
"width of chart",
"height of chart",
"div id to render the chart",
"type of data",
"actual data");
$columnChart = new FusionCharts(
"column2d",
"ex1" ,
"600",
"400",
"chart-1",
"json",
'{
"chart":
{
"caption":"Harry\'s SuperMart",
"subCaption":"Top 5 stores in last month by revenue",
"numberPrefix":"$",
"theme":"ocean"
},
"data": ' . $jsonEncodedData . '}');
// Render the chart
print_r($columnChart);
$columnChart->render();
?>
<div id="chart-1"><!-- Fusion Charts will render here--></div>
</body>
</html>
Thanks for everyone's help in solving the issue.
I use this method to generate a pass: public function setJSON($JSON) {
if(json_decode($JSON) !== false) {
$this->JSON = $JSON;
return true;
}
$this->sError = 'This is not a JSON string.';
return false;
}
I call this method to generate pass by: $pass->setJSON('{
"passTypeIdentifier": "'.$passTypeID.'",
"formatVersion": 1,
..............
"barcode": {
"altText" : "'.$alt.'",
"format" : "PKBarcodeFormatPDF417",
"message": "Member-Card",
"messageEncoding": "iso-8859-1",
"changeMessage" : "This pass now has altText %# !"
},
"locations" : [
{
"longitude" : 104.89529371261597,
"latitude" : 11.576150037278605,
"relevantText": "CamMob (dis. 1%)"
},
.....................
]
}');
But now I don't write those locations statically and I get those data from database by : $query5 = mysql_query("select * from company");
while ($row5 = mysql_fetch_array($query5)){
$companyName = $row5['relevantTextName'];
$discount = $row5['relevantTextDiscount'];
$long = $row5['longitute'];
$lat = $row5['latitute'];
$link = $row5['link'];
$location['locations'][] = array("longitute" => $long, "latitute" => $lat, "relevantText" => $companyName." (" . $discount. "%)" );
}
$jsonString = json_encode($location) ;
error_log("Locations: ".$jsonString,0);
$pass->setJSON($jsonString);
$pass->setJSON('{
"passTypeIdentifier": "'.$passTypeID.'",
"barcode": {
"altText" : "'.$alt.'",
"format" : "PKBarcodeFormatPDF417",
"message": "Member-Card",
"messageEncoding": "iso-8859-1",
"changeMessage" : "This pass now has altText %# !"
}
}');</pre>
There is no error when I test for updating pass, but I cannot see the pass on lock screen like before. Thus it means that I not yet include those locations to the pass. What should I change ? Is it the problem of method setJSON ? If I do like this, how can I combine these 2 jsons to become together ?
Rather than constructing the JSON directly, construct an array first, then transform it into JSON.
$pass_data = array("passTypeIdentifier" => $passTypeID,
"formatVersion" => 1,
"barcode" => array (
"altText" => $alt,
"format" => "PKBarcodeFormatPDF417",
"message" => "Member-Card",
"messageEncoding" => "utf-8", // use UTF8 in case you want to encode Khmer or other non ASCII
"changeMessage" => "This pass now has altText %# !"
),
"locations" => $locationsArray,
"organizationName" => "Digi club card",
"description" => "Membership card",
"logoText" => "Digiclub",
"foregroundColor" => "rgb(0,0,0)",
"backgroundColor" => "rgb(211,211,211)",
"generic" => array (
"headerFields" => array(
array ( "key" => "Status",
"label" => " ",
"value" => "Membership card"
),
),
"primaryFields" => array(
array ( "key" => "Name",
"value" => $memberName,
),
),
"secondaryFields" => array(
// Secondary Field data
),
"auxiliaryFields" => array(
// Auxiliary Field data
),
"backFields" => array(
// Backfiels Field data
),
)
);
Then transform the array into JSON:
$pass->setJSON(json_encode($pass_data));