I want to insert data in Mongo database using PHP script, in year wise documents so that it may look like this (All years in one document);
cars{
2017{
car=Motorolla
color = blue
}
2016{
car=Toyota
color = green
}
2015{
car=Corolla
color = black
}
}
I wanted to add the document but it prompts
Document can't have $ prefixed field names: $years[0]
Is it possible to make such schema in Mongo using PHP?
Code
<?php
try {
$car = 'Motorolla';
$color = 'blue';
//$car = 'Toyota';
//$color = 'green';
//$car = 'Corolla';
//$color = 'black';
$years = array(2017, 2016, 2015);
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulkWriteManager = new MongoDB\Driver\BulkWrite;
$document = ['_id' => new MongoDB\BSON\ObjectID, '$years[0]' => $car, '$years[1]' => $color]; // Making a query type
try {
$bulkWriteManager->insert($document); // Inserting Document
echo 1;
} catch(MongoCursorException $e) {
/* handle the exception */
echo 0;
}
$manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager); // Going to DB and Collection
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
}
?>
I do not want to add whole car object at once. I want to add Year object every time. Any help will be appreciable.
OR
Any relative answer so that I may get the data from Mongo Database according to the year?
Edit1
For first time creation. - Credits goes to #Veeram
<?php
try {
$car = 'Malibu';
$color = 'red';
$years = array(2017);
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulkWriteManager = new MongoDB\Driver\BulkWrite;
//{"car":"chevy", "color":"black", year: 2017}
$insert = ['car' => $car, 'color' => $color, 'year' => $years[0]];
try {
$bulkWriteManager -> insert($insert); // Inserting Document
echo 1;
} catch (MongoCursorException $e) {
echo 0;
}
$manager->executeBulkWrite('dbName.mycol', $bulkWriteManager); // Going to DB and Collection
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
echo "In file:", $e->getFile(), "\n";
echo "On line:", $e->getLine(), "\n";
}
?>
For the updation- Credits goes to #Veeram
<?php
try {
$car = 'ChangedCar';
$color = 'changedColor';
$years = array(2017);
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulkWriteManager = new MongoDB\Driver\BulkWrite;
$query = ['cars.year' => $years[0]];
//{ $push: { "cars.$.data": { "car":"chevy", "color":"black"} }}
$update = ['$push'=> ['cars.$.data'=>['car' => $car, 'color' => $color]]];
try {
$bulkWriteManager->update($query, $update); // Inserting Document
} catch(MongoCursorException $e) {
}
$manager->executeBulkWrite('dbName.mycol', $bulkWriteManager); // Going to DB and Collection
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
}
?>
The problem in this code is that it successfully insert the data for the first time but when i update the data it does not update it.
Example:
There is a document named as cars . Insert the data with object of year in one document. Let's say the Object is 2017, it contains color and car Model. As showing below; (Multiple objects with years. Year is unique in whole document.)
cars{
2017{
car=Motorolla
color = blue
}
2016{
car=Toyota
color = green
}
2015{
car=Corolla
color = black
}
}
If I want to update just make an object of 2017 like 2017{car=Updated-Motorolla color =Updated-blue} and insert in the document. It should update only the year 2017 object in side the document.
cars{
2017{
car=Updated-Motorolla
color =Updated-blue
}
2016{
car=Toyota
color = green
}
2015{
car=Corolla
color = black
}
}
You can try something like this. Its not possible to perform all the Mongo db operations just based off key as a value.
The first solution is written to stay close to OP's design.
Assuming you can add a key to the year.
{
"cars": [{
"year": "2017",
"data": [{
"car": "Motorolla",
"color": "blue"
}]
}, {
"year": "2016",
"data": [{
"car": "Toyota",
"color": "green"
}]
}]
}
Makes it easy to reference the year by its value.
For example to add a new value into the data array for year 2017. You can try the below code.
Uses update positional $ operator.
query part to reference the array where 2017 record is stored.
update part using push to add the new car record to the existing data array for 2017 row.
<?php
try {
$car = 'Malibu';
$color = 'blue';
$years = [2017];
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulkWriteManager = new MongoDB\Driver\BulkWrite;
//{"cars.year":2017}
$query = ['cars.year' => $years[0]];
//{ $push: { "cars.$.data": { "car":"chevy", "color":"black"} }}
$update = ['$push'=> ['cars.$.data'=>['car' => $car, 'color' => $color]]];
try {
$bulkWriteManager->update($query, $update); // Update Document
echo 1;
} catch(MongoCursorException $e) {
/* handle the exception */
echo 0;
}
$manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager); // Going to DB and Collection
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
}
?>
For accessing data by year you can run below query.
Use query positional $operator to find the array index using the query part and reference that value in projection part.
db.collection.find({"cars.year":2017}, {"cars.$.data":1});
Alternative Solution :
This will take care of everything as just inserts
You are better off saving each car entry in its own document.
{ "year" : 2017, "car" : "Motorolla", "color" : "blue" }
{ "year" : 2016, "car" : "Toyota", "color" : "green" }
{ "year" : 2015, "car" : "Corolla", "color" : "black" }
For each entry you can use:
db.collection.insert({"year":2017, "car":"Motorolla", "color":"blue"});
PHP Code:
//{"car":"chevy", "color":"black", year: 2017}
$insert = ['car' => $car, 'color' => $color, 'year' => $years[0]];
try {
$bulkWriteManager - > insert($insert); // Inserting Document
echo 1;
} catch (MongoCursorException $e) {
/* handle the exception */
echo 0;
}
For access data by year you can use
db.collection.find({"year":2017});
Updated PHP code:
<?php
try {
$cars = ['Motorolla','Toyota', 'Corolla'] ;
$colors = ['blue', 'green', 'black'];
$years = [2017, 2016, 2015];
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulkWriteManager = new MongoDB\Driver\BulkWrite;
$query1 =["year" => $years[0]];
$query2 =["year" => $years[1]];
$query3 =["year" => $years[2]];
$update1 = ['$set' => ['car' => $cars[0], 'color' => $colors[0]]];
$update2 = ['$set' => ['car' => $cars[1], 'color' => $colors[1]]];
$update3 = ['$set' => ['car' => $cars[2], 'color' => $colors[2]]];
try {
$bulkWriteManager->update($query1, $update1, ["upsert" => true]);
$bulkWriteManager->update($query2, $update2, ["upsert" => true]);
$bulkWriteManager->update($query3, $update3, ["upsert" => true]);
echo 1;
} catch(MongoCursorException $e) {
/* handle the exception */
echo 0;
}
$manager->executeBulkWrite('dbName.carsCol', $bulkWriteManager); // Going to DB and Collection
} catch (MongoDB\Driver\Exception\Exception $e) {
$filename = basename(__FILE__);
echo "The $filename script has experienced an error.\n";
echo "It failed with the following exception:\n";
echo "Exception:", $e->getMessage(), "\n";
}
?>
You can perform complex queries using aggregation pipeline and you can add index to make your response quicker.
Observations:
First Solution : Harder to update/insert data, but keeps everything together so easier to read data.
Second Solution :
Cleaner and simpler to do CRUD operations on documents and use aggregation pipeline to preform complex queries.
Try to change
$document = ['_id' => new MongoDB\BSON\ObjectID, '$years[0]' => $car, '$years[1]' => $color];
to something like:
$document = ['_id' => new \MongoDB\BSON\ObjectID, $years[0] => ['car' => $car, 'color' => $color]];
it gives such result in mongo:
{ "_id" : ObjectId("58a936ecfc11985f525a4582"), "2017" : { "car" : "Motorolla", "color" : "blue" }
If data about all cars must be in one document, you need to combine data fitst:
$cars = [
'2017' => [
'car' => 'Motorolla',
'color' => 'blue'
],
'2016' => [
'car' => 'Toyota',
'color' => 'green'
],
'2015' => [
'car' => 'Corolla',
'color' => 'black'
]
];
and than
$document = ['_id' => new \MongoDB\BSON\ObjectID, 'cars' => $cars];
It gives mongo document like:
{ "_id" : ObjectId("58aabc0cfc11980f57611832"), "cars" : { "2017" : { "car" : "Motorolla", "color" : "blue" }, "2016" : { "car" : "Toyota", "color" : "green" }, "2015" : { "car" : "Corolla", "color" : "black" } } }
Related
I'm trying to add new "commands" to an existing json file and I'm stuck, I have a .json file with subarrays.
This is how the file looks like:
{
"template_commands":{
"web":[
"Webadded cmds are working!",
"Rights['0']"
],
"streamer":[
"This is only for Streamers!",
"Rights['3']"
],
"admin":[
"This is only for Admins!",
"Rights['2']"
],
"mod":[
"This is only for mods",
"Rights['1']"
],
"taka":[
"taka",
"Rights['2']"
]
},
"doggo_counter":0,
"admins":{
"touru":"name",
"juufa":"name"
}
}
I want to add new values into "template_commands" Here is the php code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function get_data() {
$name = $_POST['name'];
$file_name='commands'. '.json';
if(file_exists("$file_name")) {
$current_data=file_get_contents("$file_name");
$array_data=json_decode($current_data, true);
$extra=array(
$_POST['name'] => array($_POST['branch'],$_POST['year'])
);
$array_data['template_commands'][]=$extra;
echo "file exist<br/>";
return json_encode($array_data);
}
else {
$datae=array();
$datae[]=array(
'Name' => $_POST['name'],
'Branch' => $_POST['branch'],
'Year' => $_POST['year'],
);
echo "file not exist<br/>";
return json_encode($datae);
}
}
$file_name='commands'. '.json';
if(file_put_contents("$file_name", get_data())) {
echo 'success';
}
else {
echo 'There is some error';
}
}
?>
It almost works but it puts the newly added in like this:
"0":{
"Test":[
"Lets see if this works!",
"1"
]
}
What am I doing wrong? I tried it with array_push() as well and it didn't work either.
The source of your problem is the way you're adding your element:
$array_data['template_commands'][]=$extra;
By using [] you're instructing PHP to add a new entry while automatically determining the key (which will be 0, since your array is associative, not numerical). So what you're doing can be shown as trying to add
[
'Test' => [
"Lets see if this works!",
"1"
]
]
at the next available numerical index, in this case zero.
This way of adding is suitable for numeric arrays, but not for associative ones. For them, you should explicitly define the index. So what you really want is to add
[
"Lets see if this works!",
"1"
]
under the key Test. To achieve that, change your code to this:
// only the inner array of what you used
$extra = array($_POST['branch'], $_POST['year']);
// the index is directly specified during assignment
$array_data['template_commands'][$_POST['name']] = $extra;
I have a collection in MongoDB called restaurants
{
"_id" : ObjectId("5281f8d660ad39040c000001"),
"name" : "Bucksters Coffee",
"serves" : "Fast Food",
"location" : [
"23.755339",
"90.375408"
]
}
{
"_id" : ObjectId("5285cf0860ad39380b000000"),
"name" : "A1 Donuts",
"serves" : "Fast Food",
"location" : [
"18.5087016",
"73.8124984"
]
}
{
"_id" : ObjectId("5285cf3f60ad39380b000002"),
"name" : "B1 Donuts",
"serves" : "Fast Food",
"location" : [
"18.4893148",
"73.8213213"
]
}
{
"_id" : ObjectId("5285e7a260ad39380b000009"),
"name" : "C1 Donuts",
"serves" : "Fast Food",
"location" : [
"18.5308225",
"73.8474647"
]
}
And my location is ["18.5170345","73.83476"] and I want to find nearest restaurants from my location around 5 kms.
so I try following things,
for insert restaurants,
<?php
try {
$conn = new Mongo('localhost');
// access database
$db = $conn->demo;
// access collection
$collection = $db->restaurants;
$forlatadd="shivaji nagar, pune";
//for lat& Long
$prepAddr = str_replace(' ','+',$forlatadd);
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
$a=array("$lat","$long");
//print_r($a);
$document = array( "name" => "C1 Donuts","serves" => "Fast Food","location" =>$a);
$collection->insert($document);
$collection->ensureIndex(array("location" => "2d"));
// disconnect from server
$conn->close();
} catch (MongoConnectionException $e) {
die('Error connecting to MongoDB server');
} catch (MongoException $e) {
die('Error: ' . $e->getMessage());
}
?>
And for searching data,
<?php
try {
$conn = new Mongo('localhost');
// access database
$db = $conn->demo;
// access collection
$collection = $db->restaurants;
$forlatadd="deccan, pune";
//for lat& Long
$prepAddr = str_replace(' ','+',$forlatadd);
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
$a=array("$lat","$long");
//print_r($a);
$distance='5000';
$query = array('location' => array('$near' => array($lat,$long),'$maxDistance' => intval($distance)));
$cursor = $collection->find($query);
if ($cursor) {
echo json_encode(iterator_to_array($cursor));
} else {
echo "{ 'status' : 'false' }";
}
// disconnect from server
$conn->close();
} catch (MongoConnectionException $e) {
die('Error connecting to MongoDB server');
} catch (MongoException $e) {
die('Error: ' . $e->getMessage());
}
?>
But this gives following error
Error: localhost:27017: can't find any special indices: 2d (needs index), 2dsphere (needs index), for: { location: { $near: [ 18.5170345, 73.83476 ], $maxDistance: 5000 } }
But i already done
$collection->ensureIndex(array("location" => "2d"));
while inserting new restaurants in collection,
Please help me to find nearest restaurants from my locations.
It working for me,
Only change,
$a=array("$lat","$long"); //It takes lat & long as string
to
$a=array($long,$lat); //It takes lat&long as float.
And its working
In mongodb docs, they specify order in a location definition and indeed I had problems with the order in my previous dev :
Important Specify coordinates in this order: “longitude, latitude.”
http://docs.mongodb.org/manual/reference/operator/query/near/
I'm trying to search my collection for all occurrences where the body property contains all of the search keywords.
Example string - "The black cat is definitely purple."
Keywords "black", "purple" would return the string.
Keywords "black", "dog" would not return that string.
I've been cruising some topics and Googling, but cannot seem to find the proper syntax to do this.
Currently, I am taking an string of keywords separated by commas, exploding it into an array, and then putting that into a MongoRegex Object. I know my syntax is off, because when I send just one keyword it works, but when there is more than one, I do not get any results that I would expect to get.
Current Approach:
<?php
function search_topics($array)
{
include_once('config.php');
$collection = get_connection($array['flag']);
$x = 0;
$string = null;
$search_results = null;
$keywords = explode(',', $array['search']);
$end_of_list = count($keywords);
while ($x < $end_of_list)
{
$string = $string."/".$keywords[$x];
$x++;
if($x >= $end_of_list)
{
$string = $string."/i";
}
}
if ($string != null)
{
try
{
$regex_obj = new MongoRegex($string);
$cursor = $collection->find(array('body' => $regex_obj));
}
catch (MongoCursorException $e)
{
return array('error' => true, 'msg' => $e->getCode());
}
foreach($cursor as $post)
{
$search_results[] = $post;
}
if ($search_results != null && count($search_results) > 1)
{
usort($search_results, 'sort_trending');
}
return array('error' => false, 'results' => $search_results);
}
else
{
return array('error' => false, 'results' => null);
}
}
?>
So, if I send the string black in $array['search'], my object is formed with /black/i and would return that string.
If I send the string black,cat in $array['search'], my object is formed with /black/cat/i and returns null.
Can anyone point me in the right direction with this regex syntax stuff?
Thanks in advance for any help!
Nathan
Instead of regular expressions, I would suggest you look at MongoDB's text search functionality instead, which is specifically made for situations like this: http://docs.mongodb.org/manual/core/text-search/
You would use that like this (on the MongoDB shell):
use admin
db.runCommand( { setParameter: 1, 'textSearchEnabled' : 1 } );
use test
db.so.ensureIndex( { string: 'text' } );
db.so.insert( { string: "The black cat is definitely purple." } );
db.so.runCommand( 'text', { search: '"cat" AND "dog"' } )
db.so.runCommand( 'text', { search: '"cat" AND "purple"' } )
A command doesn't return a cursor, but instead it will return one document containing all the query results in the results field. For the last search command, the result is:
{
"queryDebugString" : "cat|purpl||||cat|purple||",
"language" : "english",
"results" : [
{
"score" : 2.25,
"obj" : {
"_id" : ObjectId("51f8db63c0913ecf728ff4d2"),
"string" : "The black cat is definitely purple."
}
}
],
"stats" : {
"nscanned" : 2,
"nscannedObjects" : 0,
"n" : 1,
"nfound" : 1,
"timeMicros" : 135
},
"ok" : 1
}
In PHP, for the runCommand to turn on text search, you'd use:
$client->database->command( array(
'setParameter' => 1,
'textSearchEnabled' => 1
) );
And the text search itself as:
$client->database->command( array(
'text' => 'collectionName',
'search' => '"cat" AND "purple"'
) );
I have been trying to use the mongo::command in PHP to build a MapReduce but every time I run my code I get the following error: PHP Fatal Error, call to undefined method "mongo:command"
My Code:
try {
$map = new MongoCode("function() {
if (!this.tags) {
return;
}
for (index in this.tags) {
emit(this.tags[index], 1);
}");
$reduce = new MongoCode("function(previous, current) {
var count = 0;
for (index in current) {
count += current[index];
}
return count;
}");
$tags = $this->db->command(array( //Line the error is found on
"mapreduce" => "blog",
"map" => $map,
"reduce" => $reduce));
$con=$this->db->selectCollection($tags['result'])->find();
var_dump($con);
}
catch(MongoCursorException $e) {
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
}
Please note $this->db refers to my connection (previously defined) and blog is the collection.
For reference I have used: http://php.net/manual/en/mongodb.command.php
The OS I use is Ubuntu 12.04 and I've double checked both php.ini files which both include mongo.so - I can do normal queries with mongodb like inserting and fetching data, its just the command seems not to work.
do you select collection like $d = $m->demo;
php.net:
<?php
$m = new MongoClient();
$d = $m->demo;
$c = $d->poiConcat;
$r = $d->command(array(
'geoNear' => "poiConcat", // Search in the poiConcat collection
'near' => array(-0.08, 51.48), // Search near 51.48°N, 0.08°E
'spherical' => true, // Enable spherical search
'num' => 5, // Maximum 5 returned documents
));
print_r($r);
?>
i think in your code you didn't select collection $d = $this->db->demo; put collection name instead of demo
try {
$map = new MongoCode("function() {
if (!this.tags) {
return;
}
for (index in this.tags) {
emit(this.tags[index], 1);
}");
$reduce = new MongoCode("function(previous, current) {
var count = 0;
for (index in current) {
count += current[index];
}
return count;
}");
$d = $this->db->demo;// attention
$tags = $d->command(array( //Line the error is found on
"mapreduce" => "blog",
"map" => $map,
"reduce" => $reduce));
$con=$d->selectCollection($tags['result'])->find();
var_dump($con);
}
catch(MongoCursorException $e) {
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
}
Edit Sample:i Do this sample see it
try {
$map = new MongoCode("function() { emit(this.user_id,1); }");
$reduce = new MongoCode("function(k, vals) { ".
"var sum = 0;".
"for (var i in vals) {".
"sum += vals[i];".
"}".
"return sum; }");
$db=new Mongo("mongodb://sepidar:123#localhost:27017/admin");
$d = $db->SepidarSoft_CBMS;// attention
$tags = $d->command(array( //Line the error is found on
'mapReduce'=>'RunUser',
"map" => $map,
"reduce" => $reduce,
"out" => array('merge'=>'SepidarSoft_CBMS', 'db'=> 'RunUser')
));
print_r($tags);
}
catch(MongoCursorException $e) {
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
}
result
Array
(
[result] => Array
(
[db] => RunUser
[collection] => SepidarSoft_CBMS
)
[timeMillis] => 2
[counts] => Array
(
[input] => 1
[emit] => 1
[reduce] => 0
[output] => 1
)
[ok] => 1
)
Good Afternoon,
I am trying to get these results into arrays in PHP so that I can encode them into json objects and send them to the client. The results of the query look like this:
id name hours cat status
3bf JFK Int 24 pass open
3bf JFK Int 24 std closed
3bf JFK Int 24 exp open
5t6 Ohm CA 18 pass closed
5t6 Ohm CA 18 std closed
5t6 Ohm CA 18 std2 open
5t6 Ohm CA 18 exp open
...
I would like for the json objects to look like this:
{ "id": "3bf", "name": "JFK Int", "cats":
{ [ { "cat": "pass", "status": "open" },
{ "cat": "std", "status": "closed" },
{ "cat": "exp", "status": "open" } ] }
{ "id": "5t6", "name": "Ohm CA", "cats":
{ [ { "cat": "pass", "status": "closed" },
{ "cat": "std", "status": "closed" },
{ "cat": "std2", "status": "open" } ],
{ "cat": "exp", "status": "open" } ] }
I have succesfully connected to mysql and exported using json_encode using flat tables but this part I do not know how to do in PHP. Thanks.
This is the code that I have. This returns an array of json objects but it is flat, not nested:
$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";
$result = mysql_query($SQL);
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr[] = $row;}
$json = json_encode($arr);
echo $json;
The data itself is from a view that combines the tables ports and cats.
what you could do (sorry, not the best code I could write... short on time, ideas, and energy ;-) is something like this (I hope it still conveys the point):
$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";
$result = mysql_query($SQL);
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
// You're going to overwrite these at each iteration, but who cares ;-)
$arr[$row['id']]['id'] = $row['id'];
$arr[$row['id']]['name'] = $row['name'];
// You add the new category
$temp = array('cat' => $row['cat'], 'status' => $row['status']);
// New cat is ADDED
$arr[$row['id']]['cats'][] = $temp;
}
$base_out = array();
// Kind of dirty, but doesn't hurt much with low number of records
foreach ($arr as $key => $record) {
// IDs were necessary before, to keep track of ports (by id),
// but they bother json now, so we do...
$base_out[] = $record;
}
$json = json_encode($base_out);
echo $json;
Haven't had the time to test or think twice about it, but again, I hope it conveys the idea...
With thanks to #maraspin, I have got my below code:
function merchantWithProducts($id)
{
if (
!empty($id)
) {
//select all query
$query = "SELECT
m.id as 'mMerchantID', m.name as 'merchantName', m.mobile, m.address, m.city, m.province,
p.id as 'ProductID', p.merchantId as 'pMerchantID', p.category, p.productName, p.description, p.price, p.image, p.ratingCount
FROM " . $this->table_name . " m
JOIN by_product p
ON m.id = p.merchantId
WHERE m.id = :id
GROUP BY m.id";
// prepare query statement
$stmt = $this->conn->prepare($query);
// sanitize
// $this->id = htmlspecialchars(strip_tags($this->id));
// bind values
$stmt->bindParam(":id", $this->id);
try {
$success = $stmt->execute();
if ($success === true) {
$results = $stmt->fetchAll();
$this->resultToEncode = array();
foreach ($results as $row) {
$objItemArray = array(
"merchantID" => $row->mMerchantID,
"merchantName" => $row->merchantName,
"mobile" => $row->mobile,
"address" => $row->address,
"city" => $row->city,
"province" => $row->province,
"product" => array(
"productID" => $row->ProductID,
"pMerchantID" => $row->pMerchantID,
"category" => $row->category,
"productName" => $row->productName,
"description" => $row->description,
"price" => $row->price,
"image" => $this->baseUrl . 'imagesProducts/' . $row->image,
"ratingCount" => $row->ratingCount
)
);
array_push($this->resultToEncode, $objItemArray);
}
http_response_code(200);
$httpStatusCode = '200 OK';
$pass = true;
// return json_encode($resultToEncode);
} else {
http_response_code(204);
$httpStatusCode = '204 No Content';
$pass = false;
$this->resultToEncode = 'No Record Found';
}
} catch (PDOException $pdoEx) {
http_response_code(500); // internal server error.
$httpStatusCode = '500 Internal Server Error';
$pass = false;
$this->resultToEncode = $pdoEx->getCode();
} catch (Exception $ex) {
// return $ex->getMessage();
http_response_code(404); // 404 Not Found.
$httpStatusCode = '404 Not Found';
$pass = false;
$this->resultToEncode = $ex->getMessage();
}
} else {
http_response_code(400);
$httpStatusCode = '400 bad request';
$pass = false;
$this->resultToEncode = 'User id not specified';
}
echo json_encode(array('passed' => $pass, 'Response' => $httpStatusCode, 'result' => $this->resultToEncode));
}