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
Related
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
I am getting this error
Unknown column 'Array' in 'field list'
When inserting checkbox list into database. When I do print_array I am getting this result :
Array
(
[0] => Array
(
[user_id] => 3
[project_id] => 10
[project_type] => 5
[project_list] => Array
(
[0] => 17
[1] => 18
)
)
)
The project_list value supposed to be inserted into a new row in the database.
my view : <input type="checkbox" value="<?php echo $project_list['id']; ?>" name="project_list[]"> which is populated from database.
my controller : $this->Project_module->createProject($_POST['project_list']);
my module
public function createProject($project_list){
if($project_list != null){
$data = array();
foreach($project_list as $project_list){
$data[] = array(
'user_id' => $this->getUserId(),
'project_id' => $this->getProjectId(),
'project_type' => $this->getProjectType(),
'project_list' => $this->getProjectList(),
);
}
$this->db->insert_batch('tblProject', $data);
if($this->db->affected_rows()){
return true;
} else {
return false;
}
}
}
EDIT
I was edited my foreach like this
foreach($project_list as $row){
$data = array(
'user_id' => $this->getUserId(),
'project_id' => $this->getProjectId(),
'project_type' => $this->getProjectType(),
'project_list' => $this->getProjectList(),
);
}
But I am still getting the same error.
Linundus, you need to name the array alias in the foreach something different. You have
foreach ($project_list as $project_list)
you need to have something like this:
foreach($project_list as $list)
You already pass the project_list So you don't want to get the list again. And you can store the just foreach string. In my side confusion with $data and $data[] So test with both and let me know....
Please check before with Table fields are correct
public function createProject($project_list){
if($project_list != null){
$data = array();
foreach($project_list as $row){
$data[] = array(
'user_id' => $this->getUserId(),
'project_id' => $this->getProjectId(),
'project_type' => $this->getProjectType(),
'project_list' => $row,
);
}
$this->db->insert_batch('tblProject', $data);
if($this->db->affected_rows()){
return true;
} else {
return false;
}
}
}
I have solved the problem and here is my coding that working fine now.
ERROR CAUSE
In the controller I have already set the checkbox setter like this :
$this->Project_module->setProjectList($this->input->post('project_list'));
and then call the createProject function after like this :
$this->Project_module->createProject($_POST['project_list']);
So I am getting error with the foreach inside my module.
SOLUTION
In controller
Remove this line
$this->Project_module->setProjectList($this->input->post('project_list'));
Simply hold all checkbox value in line
$this->Project_module->createProject($_POST['project_list']);
And in module
public function createProject($project_list){ // $_POST['project_list'] value pass in $project_list
if($project_list != null){
$data = array();
foreach($project_list as $row){ // Do foreach to insert every value in different rows in database
$data[] = array(
'user_id' => $this->getUserId(),
'project_id' => $this->getProjectId(),
'project_type' => $this->getProjectType(),
'project_list' => $row,
);
}
$this->db->insert_batch('tblProject', $data);
if($this->db->affected_rows()){
return true;
} else {
return false;
}
}
}
Array
(
[0] => Array
(
[user_id] => 3
[project_id] => 10
[project_type] => 5
[project_list] => Array
(
[0] => 17
[1] => 18
)
)
)
your value is in a nested key 0 so if you want to access project_id you'll have to use $array[0]['project_id']
a suggestion here would be to you check if values inside key 0 exist then do print
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]];
I'm face a new Problem in Codeigniter Framework. Her is my Out put
Array
(
[id] => 2
[firstname] => Maruf
[lastname] => Ifftekhar
[slug] =>
[email] => support#russelhost.com
[email_subscribe] => 1
[self] =>
[phone] => 01767820010
[company] => Russel Host
[default_billing_address] =>
[default_shipping_address] =>
[ship_to_bill_address] => true
[password] => 0689d59aa30bdca7207db3d449255650
[active] => 1
[group_id] => 1
[confirmed] => 0
[group_discount_formula] => - 0
[expire] => 1380390903
)
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: controllers/secure.php
Line Number: 46
abida Sultana
Here is Controller
`$`email = `$`this->input->post('email');
`$`password = `$`this->input->post('password');
`$`remember = `$`this->input->post('remember');
`$`redirect = `$`this->input->post('redirect');
`$`login = `$`this->Customer_model->login(`$`email, `$`password, `$`remember);
echo '/pre>-----';
print_r(`$`login);
echo 'abida Sultana'.`$`login->last_name; --------------------Line Number: 46
exit();
and Model is
function login(`$`email, `$`password, `$`remember = false) {
`$`this->db->select('*');
`$`this->db->where('email', `$`email);
`$`this->db->where('active', 1);
`$`this->db->where('password', md5(`$`password));
`$`this->db->limit(1);
`$`result = `$`this->db->get('customers');
`$`customer = `$`result->row_array();
if (`$`customer) {
// Retrieve customer addresses
`$`this->db->where(array('customer_id' => `$`customer['id'], 'id' => `$`customer['default_billing_address']));
`$`address = `$`this->db->get('customers_address_bank')->row_array();
if (`$`address) {
$fields = unserialize($address['field_data']);
$customer['bill_address'] = $fields;
$customer['bill_address']['id'] = $address['id']; // save the addres id for future reference
}
$this->db->where(array('customer_id' => $customer['id'], 'id' => $customer['default_shipping_address']));
$address = $this->db->get('customers_address_bank')->row_array();
if ($address) {
$fields = unserialize($address['field_data']);
$customer['ship_address'] = $fields;
$customer['ship_address']['id'] = $address['id'];
} else {
$customer['ship_to_bill_address'] = 'true';
}
// Set up any group discount
if ($customer['group_id'] != 0) {
$group = $this->get_group($customer['group_id']);
if ($group) { // group might not exist
if ($group->discount_type == "fixed") {
$customer['group_discount_formula'] = "- " . $group->discount;
} else {
$percent = (100 - (float) $group->discount) / 100;
$customer['group_discount_formula'] = '* (' . $percent . ')';
}
}
}
if (!$remember) {
$customer['expire'] = time() + $this->session_expire;
} else {
$customer['expire'] = false;
}
// put our customer in the cart
$this->go_cart->save_customer($customer);
return $customer;
} else {
return false;
}
}
If you did a var_dump on your login variable you will see that it is an array not an object so you can't deal with it like an object.
so go to your model and modify the following:
$customer = $result->row_array();
to be:
$customer['result'] = $result->row_array();
then in line 46 use it as:
$login['result']->last_name;
Why this is happening:
because as you defined $customer as an object at first. you also redefined it later in your model as an array by using $customer['something'] pattern of assignation.
So you can't have it your way, it's either an array or an object.
//You used this code because row_array return array not object
`$`login["result"] = `$`this->Customer_model->login(`$`email, `$`password, `$`remember);
echo $login['result']["last_name"];
I am currently working on a site that is being built on codeigniter, I am currently querying the data at the moment I think there could be possible 3 arrays that could be returned as array each with a varying amount of results, my question I cannot for life of me loop through the array I have at the moment,
my model looks like this
public function get_special_backgrounds() {
$this->db->select('*');
$this->db->from('background');
$this->db->where('is_special', 1);
$query = $this->db->get();
return $query->result_array();
}
my controller
enter public function index() {
// $this->output->enable_profiler(TRUE);
$data = array();
if($query = $this->category_model->get_all_online()) {
$data['main_menu'] = $query;
}
$this->load->model('image_model');
/*
* Sort out the users backgrounds, basically do a check to see if there is a 'special' background
* if there is not a 'special' background then IF the user is logged in and has a background of there
* own show that one, if not show a generic one, if they are not logged in show a generic one
*/
$image = array();
if ($query = $this->image_model->get_special_backgrounds()) {
$image = $query;
}
$data = array_merge($data, $image);
die(print_r($data));
$this->load->view('home/main_page.php', $data);
}
the array the gets return looks like this,
Array
(
[main_menu] => CI_DB_mysql_result Object
(
[conn_id] => Resource id #28
[result_id] => Resource id #35
[result_array] => Array
(
)
[result_object] => Array
(
)
[current_row] => 0
[num_rows] => 1
[row_data] =>
)
[special] => Array
(
[0] => Array
(
[background_id] => 6
[background_name] => Master-Backgrounds.png
[background_path] => /Users/Simon/Sites/mysite/media/uploads/backgrounds/
[is_special] => 1
[background_date_uploaded] => 1262687809
[users_user_id] => 1
[users_user_group_group_id] => 1
)
[1] => Array
(
[background_id] => 11
[background_name] => Master-mysite-Template.png
[background_path] => /Users/Simon/Sites/mysite/media/uploads/backgrounds/
[is_special] => 1
[background_date_uploaded] => 1262795313
[users_user_id] => 5
[users_user_group_group_id] => 2
)
)
)
1
It's an object, so you can't loop through it like an array. I do see what you're trying to do and understand why it seems like that makes sense, but to see what I'm talking about, try this:
Change this:
public function get_special_backgrounds() {
$this->db->select('*');
$this->db->from('background');
$this->db->where('is_special', 1);
$query = $this->db->get();
return $query->result_array();
}
To this:
public function get_special_backgrounds() {
$this->db->select('*');
$this->db->from('background');
$this->db->where('is_special', 1);
$query = $this->db->get();
return $query;
}
AND
Change this:
$image = array();
if ($query = $this->image_model->get_special_backgrounds()) {
$image = $query;
}
To this:
if($images = $this->image_model->get_special_backgrounds()) {
foreach($images->result_array() as $image) {
echo "<pre>";
print_r($image);
echo "</pre></br >";
}
}
Do you need to loop on the special part of the array?
foreach ( $data['special'] as $row ) {
// do stuff with the $row array
}
Try foreach
$arr = (your array);
foreach ($arr as $key => $insideArrays) {
foreach ($insideArrays as $k2 => $insideInsideArrays){
..........
}
}
Looks like a result array, with an odd element at the beginning. I'd get rid of the first element and then just loop through it:
array_shift($data);
foreach ($data as $row) {
// Do stuff with $row
var_dump($row);
}