I am trying to reproduce the following but my using rows from the database
var allCustomers = [
{ name: 'Customer1', contacts: [
{ name: 'Bob', id: ['1'] },
{ name: 'Sue', id: ['2'] },
{ name: 'John', id: ['3'] }
]},
{ name: 'Customer2', contacts: [
{ name: 'Max', id: ['4'] },
{ name: 'Ross', id: ['5'] },
{ name: 'Sally', id: ['6'] }
]}
];
In PHP I am fetching the rows from the database, each customer has multiple contacts, which is the bit I am struggling with. Currently I am using the method below:
<script type="text/javascript">
var allCustomers = [
<?php
include('connection.php');
$stmt = $db->prepare("SELECT customer.customerID, customerName, contactID, contactName FROM customer INNER JOIN customerContact ON customer.customerID = customerContact.customerID");
if ($stmt->execute())
{
while ($row = $stmt->fetch(PDO::FETCH_OBJ))
{
echo "{ name: '".$row->customerName."', contacts: [
{ name: '".$row->contactName."', id: ['".$row->contactID."'] }
]},";
}
}
?>
];
But obviously this isn't a very neat way of doing this, and it only works if a customer has only one contact, otherwise it reproduces the customer and contact again.
What would you suggest to fix this, could I make use of the php decode json function or something similar?
Thanks for any suggestions :).
I am trying to produce something similar to this post, but I need the id of the contact to post back to the server.