Use returned data from array - php

I get some data from a table
Data is returned into an array like this
Array ( [id_widget] => 11 [id_user] => 7 [active] => 1 )
Then I am trying to use this "id_widget" and "entryemail" to insert them into another table.
"newentry" comes from an input, but I don't know how to post the "id_widget"
This is my model function
public function addentry($data) {
$this->db->insert('entries', array(
'id_widget' => $data['id_widget'],
'entryemail' => $data['entryemail']
));
}
This is my controller function:
public function entercontest() {
$entry = array(
'id_widget' => $this->widget[0]['id_widget'],
'entryemail' => $_POST['entryemail']
);
$this->model->addentry($entry);
}
It works to insert "entryemail" if I comment id_widget line everywhere.

The error doesn't occur when getting the value from the array $data['id_widget']. The error occurs in the entercontent function because you're populating the array with an undefined value because $this->widget is undefined.
Make sure $this->widget is defined and has the data before using it.

Related

Push an array within an array

I created a function called "keyword_query()" which gets a single string and runs a query with this variable on an API - then the API returns an array (which is defined global so it's changed outside the function too).
The second function "keyword_query_array()" should run the "keyword_query()" more than once, and push to a new array (which is global too) and get an array of several arrays. This function gets a variable of an array of keywords. The function gets the array and navigates through the array without any problem.
Please notice the comments in the code:
<?php
// Runs the query "Research Key" on a keyword and get App ids, names, ect'.
function keyword_query($keyword){
global $research_key_array, $keyword;
// Add the keyword to the "Research Key" query:
$research_key_query = "https://example.com/api/banana/ajax/kaka?term=$keyword&country=US&auth_token=666";
// Create a stream for Json. That's how the code knows what to expect to get.
$context_opts = array(
'http' => array(
'method' => "GET",
'header' => "Accepts: application/json\r\n"
)
);
$context = stream_context_create($context_opts);
// Get the Json
$research_key_json = file_get_contents($research_key_query, false, $context);
// Turn Json to a PHP array
$research_key_array = json_decode($research_key_json, true);
//var_dump($research_key_array);
//print_r($research_key_array);
return $research_key_array;
}
// Runs the keyword_query() function on an array of keywords.
function keyword_query_array($keyword_array){
global $array_of_key_queries;
// Get the last array cell
$last_array_cell = count($keyword_array);
// Navigate through the array
for ($i=0; $i<=$last_array_cell ; $i++) {
//echo $keyword_array[$i]; ****works!
// Error here: Notice: Undefined offset: 3 in C:\wamp\www\PHPExcel\api_fun.php on line 51
array_push( $array_of_key_queries, keyword_query($keyword_array[$i]) );
}
var_dump($array_of_key_queries);
}
But when I get to this line:
array_push( $array_of_key_queries, keyword_query($keyword_array[$i]) ); I get an error of:
Notice: Undefined offset: 3 in C:\wamp\www\PHPExcel\api_fun.php on line 51
with this var_dump:
array (size=4)
0 =>
array (size=1)
'keyword' =>
array (size=0)
empty
1 =>
array (size=1)
'keyword' =>
array (size=0)
empty
2 =>
array (size=1)
'keyword' =>
array (size=0)
empty
3 =>
array (size=1)
'keyword' =>
array (size=0)
empty
What is the right way to push an array within an array like this case?
I changed global $research_key_array, $keyword; from the first function to global $research_key_array;
Works great now!
Thanks #Adelphia !

Yii 2.0 $request->post() issues

In my controller I have the following lines
$request = Yii::$app->request;
print_r($request->post());
echo "version_no is ".$request->post('version_no',-1);
The output is given below
Array
(
[_csrf] => WnB6REZ6cTAQHD0gAkoQaSsXVxB1Kh5CbAYPDS0wOGodSRANKBImVw==
[CreateCourseModel] => Array
(
[course_name] => test
[course_description] => kjhjk
[course_featured_image] =>
[course_type] => 1
[course_price] => 100
[is_version] => 1
[parent_course] => test
[version_no] => 1
[parent_course_id] => 3
[course_tags] => sdsdf
)
)
version_no is -1
So here the return value of post() contains the version_no.But when it is called as $request->post("version_no"), it is not returning anything (or $request->post("version_no",-1) returns the default value -1).
As per Yii 2.0 docs, the syntax is correct and should return the value of post parameter.
But why is it failing in my case.The post array has the parameter in it.But the function is not returning when called for an individual parameter value.
your parameters are in $_POST['CreateCourseModel']['version_no'] etc. with $request->post('version_no',-1) you trying to get $_POST['version_no'] which is not defined so it returns you -1. So to get version_no use
$data = $request->post('CreateCourseModel');
print_r($data['version_no']);
You can access nested $_POST array elements using dot notation:
\Yii::$app->request->post('CreateCourseModel.version_no', -1);
Model properties are grouped like that for massive assignment that is done via $model->load(Yii::$app->request->post()).
Depending on your needs maybe it's better use default value validator like that:
['version_no', 'default', 'value' => -1],

Codeigniter - passing multiple values to view

Okay, so generally I wouldn't have a problem doing this and it would be fairly straight forward, but not so much this time.
Here is the relevant code in my controller:
// In order to properly build the form url, we need to include the
// category and product to the view
$this->data = array(
'category' => $category,
'product' => $product
);
// Load the product model and get editable values from the database
$this->load->model('productadmin/products_model');
$productInformation = $this->products_model->get_product_data($product);
// Modular code! Use variable-variables to prevent having to write multiple lines of code
// when we start returning more information from the data
foreach ( $productInformation as $variable => $value )
{
$this->data[$variable] = $value;
}
Now, ideally, I should be able to access $product, $category and any variables returned from the products model. Doing a print_r, I get the following:
Array ( [category] => 1 [product] => 1 [0] => Array ( [id] => 1 [product_name] => Duff ) )
Notice how what was generated by the foreach statement is contained in it's own array. The easiest solution, would be to know how to access that second array from the view, just by passing $this->data.
If that's not do-able, what can I change that would assign the model's associative values inside the data array without creating another array inside of it?
The model simply returns key, value pairs from a get_where statement.
You should use an associative array for your data before it is passed to the view. Try changing this lines:
foreach ( $productInformation as $variable => $value )
{
$this->data[$variable] = $value;
}
with this:
foreach ( $productInformation as $variable => $value )
{
$this->data['product_information'][$variable] = $value;
}
And then in your view you can access your product information using $product_information variable.
Note: I am assuming that you're passing your data to the view using:
$this->load->view('your_view', $this->data);

Do I need to write a custom session class for CodeIgniter?

I cannot seem to get CI's session library to function the way I want it to. Essentially, I am storing 2 different categories of data within the sessions. The data within the 2 categories may contain the same value. Right now my attempt to add a key => value pair to the session is failing, as it is only allowing 1 key => value pair to be associated with the array. It overrides itself each time I do a post.
$arr = array(
'favorite_products' => array(),
'viewed_products' => array()
);
$arr["favorite_products"][] = $fav_id;
$this->session->set_userdata($arr);
This is what the array looks when I print_r it:
Array ( [favorite_products] => Array ( [4f1066c2b7fff] => 1648406 ) [viewed_products] => Array ( ))
Am I doing something wrong, or is this just the way CI's session library works?
Make sure you are destroying your session between attempts, but this code should work just fine...
$arr = array(
'favorite_products' => array(),
'viewed_products' => array()
);
$arr["favorite_products"][] = $fav_id;
$arr["favorite_products"][] = 033333; // another id
$this->session->set_userdata($arr);
should give you...
Array (
[favorite_products] => Array (
[0] => 1648406,
[1] => 033333
),
[viewed_products] => Array ()
)
If you are trying to do this between requests...
// if it doesn't already exist in the session, create an empty array.
if( ! ($favorite_products = $this->session->get_userdata("favorite_products")))
{
$favorite_products = array();
}
$favorite_products[] = "new id or info";
$this->session->set_userdata("favorite_products", $favorite_products);

CakePHP query array

I am running this query using CakePHP:
$total = $this->Lapse->query("select sum(unix_timestamp(stop) - unix_timestamp(start)) from lapses where id = ".$lastId."");
And i get back this array structure:
Array
(
[0] => Array
(
[0] => Array
(
[sum(unix_timestamp(stop) - unix_timestamp(start))] => 1
)
)
)
So my variable holds this: $updateVal = $total[0][0][0];
Which isn't the prettiest, is there a way i can simplify this OTT array?
Have you tried the find() method passing a custom fields option?:
$this->Lapse->find('all', array(
'fields' => array('sum(unix_timestamp(stop) - unix_timestamp(start)) as elapsed_time'),
'conditions' => array('Lapse.id' => $lastId),
));
The returned array is prettier than the one you're getting, although it's not prettier than elapsed_time being an actual model property.
Another solution would be to set elapsed_time as a virtual field within the model:
class Lapse extends AppModel {
...
public $virtualFields = array(
'elapsed_time' => 'sum(unix_timestamp(Lapse.stop) - unix_timestamp(Lapse.start)',
);
...
}
Then elapsed_time acts as a model property and would be returned as $updateVal['Lapse']['elapsed_time'] in every find() call.

Categories