Use variable to query MongoDB with PHP - php

I need to dynamically build a complex MongoDB query before executing it in PHP. My query line looks like $cursor = $c_sbc->aggregate($query_string);, where $query_string is something like [['$match' => ['symbol' => $sym]],['$project' => ['first' => ['$arrayElemAt' => ['$data.1000', -1]]]]].
Copy-and-pasting the above-given example to replace $query_string gives the desired result. However, running it with $query_string in place gives an error saying it expects an array, not a string. How do I get this query to work?
Catchable fatal error: Argument 1 passed to MongoDB\Collection::aggregate() must be of the type array, string given, called in C:\xampp\htdocs\gc5\screen.php on line 60 and defined in C:\xampp\htdocs\gc5\vendor\mongodb\mongodb\src\Collection.php on line 163
Edit: relevant PHP
$query = $_POST['screen'];
$t = array(
"revenue" => 1000,
"costofgoodssold" => 1001
);
$data_array = [];
//turn words into data.XXXX codes
function translate($match){
global $t;
global $data_array;
foreach($match as $m){
$d = "data.".$t[$m];
$data_array[] = $d;
return $d;
}
}
$query = preg_replace('/\s/', '', $query); //strip whitespace
$query = strtolower($query);
$query = preg_replace_callback('/([A-Z]+)/i','translate', $query);
echo "<br>Query: ";
print_r($query);
echo "<br>";
$client = new MongoDB\Client("mongodb://localhost:27017");
$db = $client->gc_dev;
$c_sbc = $db->screenByCompany;
$for_years = [-1]; //default is TTM
$symbols = ['goog', 'fb', 'crmt', 'vlgea', 'ko', 'pep', 'flws'];
for($i=0;$i<count($symbols);$i++){
$sym = $symbols[$i];
for($j=0;$j<count($for_years);$j++){
$k = $for_years[$j];
//build query for data
$data_query = "";
foreach($data_array as $d){
if($data_query == ""){ //first go-around, no need for comma
$data_query .= "['first' => ['\$arrayElemAt' => ['$".$d."', ".$k."]]]";
}else{
//$data_query .= ",['second' => ['\$arrayElemAt' => ['$".$d."', ".$k."]]]";
}
$query_string = "[['\$match' => ['symbol' => \$sym]],['\$project' => ".$data_query."]]";
}
echo "<br>\$query_string: ".$query_string;
$cursor = $c_sbc->aggregate($query_string);
//$cursor = $c_sbc->aggregate([['$match' => ['symbol' => $sym]],['$project' => ['first' => ['$arrayElemAt' => ['$data.1000',-1]]]]]);
$cursor = iterator_to_array($cursor);
//var_dump($cursor);
echo "Cursor: ".$cursor[0]['first'] . "<br><br>";
}
Results in:
Query: (data.1000-data.1001)>1,000
$query_string: [['$match' => ['symbol' => $sym]],['$project' => ['first' => ['$arrayElemAt' => ['$data.1000', -1]]]]]
Catchable fatal error: Argument 1 passed to MongoDB\Collection::aggregate() must be of the type array, string given, called in C:\xampp\htdocs\gc5\screen.php on line 60 and defined in C:\xampp\htdocs\gc5\vendor\mongodb\mongodb\src\Collection.php on line 163

Found your error. You are declaring $query_string as a string and not as an array like what the function aggregate is asking for. Your code is:
$query_string = "[['\$match' => ['symbol' => \$sym]],['\$project' => ".$data_query."]]";
Replace it with:
$query_string = [['\$match' => ['symbol' => \$sym]],['\$project' => $data_query]];

Related

Explode MYSQL DB column [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 1 year ago.
I have a DB column with a string as shown below
{"gpslev":"11","gsmlev":"4","hdop":"0.4","io16":"202847595","io175":"-1","io200":"0","io236":"0","io239":"0","io240":"0","io241":"65510","io247":"0","io251":"0","io252":"0","io253":"0","io254":"25","io310":"0","io66":"12299","io67":"4014","io68":"0","io69":"1","pdop":"0.5"}
I want to extract certain data from this string and echo it to a PHP page
I have used the following to no avail
function populateArrayFromString($string)
{
$array = [];
$pairs = explode(",", $string);
foreach ($pairs as $pair) {
list($key, $value) = explode(":", $pair);
$arrayToReturn[trim($key, '"')] = trim($value, '"');
}
return $array;
}
$result = mysql_query("SELECT * FROM gs_objects WHERE imei = '354018115539821' ");
?>
<?php
while ($row = mysql_fetch_array($result)) {
$data = populateArrayFromString($row['params']);
?>
<?php echo $row['params']; ?>
</br>
<?php echo $data['io16']; ?>
If I echo the PARAMS coumn I see the whole string. If I echo the io16 in the param colum I get error
Notice: Undefined index: io16
use
$stmt = '{"gpslev":"11","gsmlev":"4","hdop":"0.4","io16":"202847595","io175":"-1","io200":"0","io236":"0","io239":"0","io240":"0","io241":"65510","io247":"0","io251":"0","io252":"0","io253":"0","io254":"25","io310":"0","io66":"12299","io67":"4014","io68":"0","io69":"1","pdop":"0.5"}';
$result = json_decode($stmt,true);
print_r($result);
and you will get and array
Array
(
[gpslev] => 11
[gsmlev] => 4
[hdop] => 0.4
[io16] => 202847595
[io175] => -1
[io200] => 0
[io236] => 0
[io239] => 0
[io240] => 0
[io241] => 65510
[io247] => 0
[io251] => 0
[io252] => 0
[io253] => 0
[io254] => 25
[io310] => 0
[io66] => 12299
[io67] => 4014
[io68] => 0
[io69] => 1
[pdop] => 0.5
)
No nbeed to self poarse the json

Codeigniter - how to passing foreach value to inside of array

I use CodeIgniter 3 and libraries of http://biostall.com/codeigniter-google-maps-v3-api-library/ .
When I take the data from the database and put it into the polygon points, I encountered some error .
Severity: Warning Message: trim() expects parameter 1 to be string,
array given Filename: libraries/Googlemaps.php
Line Number: 2179
my controller function :
public function testing()
{
$config['center'] = '-8.1768084, 113.6559507';
$config['zoom'] = 'auto';
$this->googlemaps->initialize($config);
$kecamatan = $this->Peta_model->get_kecamatan();
foreach ($kecamatan as $k) {
$kcmt = $k->name;
$coor = $this->Peta_model->get_coor_by_kcmt($kcmt);
if ($coor) {
$polygon = array(
'points' => array() ,
'strokeColor' => '#000099' ,
'fillColor' => '#000099' ,
);
foreach ($coor as $c) {
$polygon ['points'][] = array("'".$c->latitude.",".$c->longitude."'");
}
$this->googlemaps->add_polygon($polygon);
}
}
$user = $this->ion_auth->user()->row();
$user_level = $this->ion_auth->get_users_groups($user->id)->row();
$data = array(
'user' => $user ,
'user_level' => $user_level ,
'title' => 'Peta' ,
'content' => 'peta/v_peta' ,
'map' => $this->googlemaps->create_map(),
);
$this->load->view('dashboard/layout', $data);
}
normaly add polygon is :
$polygon = array(
'points' => array('37.425, -122.1321',
'37.4422, -122.1622',
'37.4412, -122.1322',
'37.425, -122.1021') ,
'strokeColor' => '#000099' ,
'fillColor' => '#000099' ,
);
$this->googlemaps->add_polygon($polygon);
how do I fix it ?
You are storing an array in $polygon ['points'][].
i think you should store a string. like..
$polygon ['points'][] = "'".$c->latitude.",".$c->longitude."'";
Solved !. only cahange
$polygon ['points'][] = array("'".$c->latitude.",".$c->longitude."'");
to
$polygon ['points'][] = $c->latitude.','.$c->longitude;
thank you #Muhammad Suhaib

Zabbix Reading the Api

I'm getting Informations from the Zabbix Api with a PHP library. At the moment I get the "lastvalue" from the json Array:
try {
// connect to Zabbix-API
$api = new ZabbixApi($api_url, $username, $password);
$params = array(
'groupids' => '2',
'real_items' =>TRUE,
'monitored_items' =>TRUE,
'search' => array('name' => 'Disk root used p'),
'selectFunctions' => 'extend',
'output' => 'extend',
'sortfield' => 'name',
'limit' => '1'
);
$trends = $api->itemGet($params); // get data from api
$names = array();
foreach($trends as $trend) { // loop through the returned data
$names[] = $trend->lastvalue;
}
//print_r($names);
} catch(Exception $e) {
// Exception in ZabbixApi catched
echo $e->getMessage();
}
But now I want to get the "lastvalue" plus the "name" of the Item in this Array for example like that: "name"+"lastvalue". How can I get both of them into my array $names[]?
Here is my answer from my comments, hope its what you are looking for!
$trends = $api->itemGet($params);
$names = array();
foreach($trends as $trendKey => $trendValue)
{
$names[$trendKey] = $trendValue;
}
#Test the names array
foreach ($names as $nameKey => $nameValue)
{
print("{$nameKey} = {$nameValue}<br />");
}
Return value:
groupids = 2
real_items = TRUE
...
sortfield = name
limit = 1

Saving Array Variable From Oracle Query

I am creating a function that extract all rows from a column with parameters and returning them as an array. So when user needed to call that function to fill in a select dropdown, the function will read from several parameters and display them in an array. but im getting an error. please help me
my function is ,
function QueryParam($conn, $data, $table){
static $stmt = array();
$firstParam = TRUE;
$query = 'SELECT * FROM ' . $table;
foreach ($data as $key => $value){
if ($firstParam){
$firstParam = FALSE;
$query .= ' WHERE ';
} else {
$query .= ' AND ';
}
$query .= "$key = :b$key";
}
$queryhash = md5($query);
if (is_null($stmt[$queryhash])) {
$stmt[$queryhash] = oci_parse($conn, $query);
}
foreach ($data as $key => $value) {
oci_bind_by_name($firstStmt[$queryhash], ":b$key", $data[$key], -1);
}
oci_execute($stmt[$queryhash], OCI_DEFAULT);
return oci_fetch_array($stmt[$queryhash], OCI_ASSOC);
}
And I am calling that function
$test = QueryParam($conn, "PROJECT_NAME = LPIEXTMILLHOUSE", "MASTER_DRAWING");
print_r($test);
The errors I am getting are,
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\WeltesProjectManagement\lib\GeneralFunction.php on line 47
Notice: Undefined index: a8961369da6bc0fd60c573021c17ddc2 in C:\xampp\htdocs\WeltesProjectManagement\lib\GeneralFunction.php on line 59
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\WeltesProjectManagement\lib\GeneralFunction.php on line 63
Array ( [HEAD_MARK] => IGG-SW-CP1 [ENTRY_DATE] => 18-SEP-14 [COMP_TYPE] => CANOPY [WEIGHT] => 35.8 [SURFACE] => 2 [PROFILE] => L50*50*5 [PROJECT_NAME] => SUGARWHOUSE [LENGTH] => 3040 [TOTAL_QTY] => 1 [SUBCONT_STATUS] => ASSIGNED [DWG_STATUS] => ACTIVE [REV] => 0 [DISTRIBUTION_COUNT] => 1 )
The result only returning 1 row of array, the result should be more than 1 row

Insert several array of value different in new row from database

I want insert in the row from database, array of values as that each of they put in new row from database.
I not want insert all values in a row from database with use of serialize(json_encode or etc).
For example:(in this example, i want three times insert data(value), because i have 3 value different)
Update 4:
this my value:
<input name="name[0][]" value="11">
<input name="passport_number[0][]" value="11">
<input name="name[1][]" value="22">
<input name="passport_number[1][]" value="22">
i do it, but it not worked:
$name_input = $this->input->post('name');
$passport_number_input = $this->input->post('passport_number');
//$term_passport_input = $this->input->post('term_passport');
//$date_of_birth_input = $this->input->post('date_of_birth');
//$age_input = $this->input->post('age');
//$national_number_input = $this->input->post('national_number');
//$mobile_input = $this->input->post('mobile');
//$address_input = $this->input->post('address');
$data = array();
foreach ($name_input as $idx => $name) {
$data[] = array(
'name' => $name_input[0]
'passport_number' => $passport_number_input[0],
//'term_passport' => $term_passport_input[$idx],
//'date_of_birth' => $date_of_birth_input[$idx],
//'age' => $age_input[$idx],
//'national_number' => $national_number_input[$idx],
//'mobile' => $mobile_input[$idx],
//'address' => $address_input[$idx],
);
};
var_dump($name_input);
$this->db->insert_batch('customer_info', $data);
This is output '$name_input' with var_dump:
array(2) {
[0] = > array(1) {
[0] = > string(2)"11"
}[1] = > array(1) {
[0] = > string(2)"22"
}
}
I get this error:
A PHP Error was encountered Severity: Warning Message: Cannot
modify header information - headers already sent by (output started at
D:\xampp\htdocs\application\controllers\admin\tour_foreign.php:405)
Filename: core/Common.php Line Number: 413 A Database
Error Occurred Error Number: 1054 Unknown column '0' in 'field
list' INSERT INTO customer_info (0) VALUES ('22')
Filename: D:\xampp\htdocs\system\database\DB_driver.php Line
Number: 330
Update 3: Per updated question (update 4)
Looking at the var_dump of $name_input following code should work:
$name_input = $this->input->post('name');
$passport_number_input = $this->input->post('passport_number');
$data = array();
foreach ($name_input as $idx => $name) {
$data[] = array(
'name' => $name_input[$idx][0],
'passport_number' => $passport_number_input[$idx][0]
);
};
$this->db->insert_batch('customer_info', $data);
It is further needed to access the [0] element as the POST input is passes as an array of arrays
Update 2:
Seeing the problem is because the POST returns the data as a further array following code MIGHT work. I would need var_dump of POST inputs ($hi_input..) to give the exact code.
$hi_input = $this->input->post('hi');
$hello_input = $this->input->post('hello');
$how_input = $this->input->post('how');
$data = array();
foreach ($hi_input as $idx => $name) {
$data[] = array(
'hi' => $hi_input[$idx][0],
'hello' => $hello_input[$idx][0],
'how' => $how_input[$idx][0]
);
};
$this->db->insert_batch('table', $data);
The following code should work as I have tested it (I do not have CodeIgniter Installed). It does not use CodeIgniter to get post data.
$hi_input = $_POST['hi'];
$hello_input = $_POST['hello'];
$how_input = $_POST['how'];
$data = array();
foreach ($hi_input as $idx => $name) {
$data[] = array(
'hi' => $hi_input[$idx][0],
'hello' => $hello_input[$idx][0],
'how' => $how_input[$idx][0]
);
};
$this->db->insert_batch('table', $data);
Update :
You can also do this using $this->db->insert_batch();, like this :
$hi_input = $this->input->post('hi');
$hello_input = $this->input->post('hello');
$how_input = $this->input->post('how');
$data = array();
foreach ($hi_input as $idx => $name) {
$data[] = array(
'hi' => $hi_input[$idx],
'hello' => $hello_input[$idx],
'how' => $how_input[$idx]
);
};
$this->db->insert_batch('table', $data);
Old answer
The CodeIgniter documentation on insert - http://codeigniter.com/user_guide/database/active_record.html#insert
states that the $data parameter is an associative array with column names as keys and data to insert as values.
So you need to call it once for each row. Thus
Try this:
$hi_input = $this->input->post('hi');
$hello_input = $this->input->post('hello');
$how_input = $this->input->post('how');
foreach ($hi_input as $idx => $name) {
$data = array(
'hi' => $hi_input[$idx],
'hello' => $hello_input[$idx],
'how' => $how_input[$idx]
);
$this->db->insert('table', $data);
};

Categories