How to assign a value to an associative array - php

I have an associative array called $data and a function called sendToView() which is accepting $email and $vehicleid as parameters. I need to assign those parameters to $data array. How can I do that?
Here I have mentioned what I have tried but it is giving "Trying to get property of non-object" error. How can i solve that?
public function sendToView($email, $vehicleid) {
$data['details'] = array(
'email' => $email,
'id' => $vehicleid
);
$this->load->view('pages/OfferView',$data);
}
offerView.php
<?php foreach ($details as $detail) {?>
<form name="myform4" action="<?php echo base_url(). 'OfferCtrl/sendEmailToReview/'. $detail->email .'/'. $detail->id ;?> " method="POST">
I have done this in offerView.php.Is that error occurs due to this?

When you just pass an data array can access it through foreach loop like this
$email = $data['details']['email'];
$id = $data['details']['id'];

public function sendToView($email, $vehicleid) {
$data['details'] = array();
$data['details']['email'] = $email;
$data['details']['id'] = $vehicleid;
$this->load->view('pages/OfferView',$data); //load it into the view
}
when accessing it, you can loop through and push your data back to a variable
i.e
$email = $details['email'];
$id = $details['id'];
You can then proceed to use the variables $email and $id in your code .
Something like this:
<form name="myform4" action="<?php echo base_url(). 'OfferCtrl/sendEmailToReview/'. $email .'/'. $>id ;?> " method="POST">

Related

Session value to array

I have this function that save data after the button is clicked.
$data=$_POST;
$details = array();
$details['title'] = $data['title'];
$details['content'] = $data['text'];
$details['snippet'] = $data['hidden_snippet'];
$details['createdDate']=date('Y-m-d H:i:s');
$result=$this->ask_model->book_add($details);
I want to add the session value which contains the user id from another table in a column named "author_id" .
$data= $this->session->userdata('user_id');
I tried to do this but the value I'm getting is null.
$data= $this->session->userdata('user_id');
$data=$_POST;
$details = array();
$details['title'] = $data['title'];
$details['content'] = $data['text'];
$details['snippet'] = $data['hidden_snippet'];
$details['createdDate']=date('Y-m-d H:i:s');
$details['author_id']= $data;
$result=$this->ask_model->book_add($details);
Here's the error:
Errors
What do I need to convert the session value into so I could add it to the array?
Update:
OK I'm a beginner at CodeIgniter and this problem is because of my own stupidity. The model I used was not set on $autoload['model'] on autoload.php plus I've been calling the wrong url in my ajax at my view file. The comments does solve one of my problem so thank you so much!
I think you are replacing data unnecessarily. This way I think you should do it
$user_id= $this->session->userdata('user_id');
$data=$_POST;
$details = array();
$details['title'] = $data['title'];
$details['content'] = $data['text'];
$details['snippet'] = $data['hidden_snippet'];
$details['createdDate']=date('Y-m-d H:i:s');
$details['author_id']= $user_id;
$result=$this->ask_model->book_add($details);
First load model in application/config/autoload.php
$autoload['model'] = array('Ask_model');
Make sure the first letter of file and class name should be capitalized. It should be Ask_model not ask_model
$data = $_POST overwriting the value of $this->session->userdata('user_id') because you are also giving the same variable name.
Overwriting here
$data= $this->session->userdata('user_id');
$data=$_POST;
Do like this
$author_id = $this->session->userdata('user_id');
$data=$_POST;
$details = array();
$details['title'] = $data['title'];
$details['content'] = $data['text'];
$details['snippet'] = $data['hidden_snippet'];
$details['createdDate']=date('Y-m-d H:i:s');
$details['author_id']= $author_id ;
$result=$this->ask_model->book_add($details);

how can get an object instead of array like FETCH_OBJECT instead of FETCH_ASSOC

I have a class names Product.php in my model directory. in my view directory, I have an index.php currently I fetching data out of my table using this function
the code works fine but I want to field $row['name'] to be called as an object. because I am not sure the way I'm doing is a semantically correct for oop programming.
public function display(){
$pizza = $this->connect()->query("SELECT * FROM pizza");
while ($row = $pizza->fetch(PDO::FETCH_ASSOC)) {
$data[]= $row;
} return $data;
}//end of method
and in my index page i write :
$blog = new Product();
$name = $blog->display();
foreach ($name as $row ) {
echo $row['name']. '<br>';
}
All you need to do is change PDO::FETCH_ASSOC to PDO::FETCH_OBJ.
Then for your index.php:
$blog = new Product();
$name = $blog->display();
foreach ($name as $row ) {
echo $row->name . '<br>';
}
Here is a really good article to read for PDO.
PDO Tutotrial

PHP, set all $_POST to its own named variable

on an PHP POST, is there a way of automatically setting each POST variable to its own named variable?
For example if I post
name = "henry"
age = "20"
location = "earth"
Instead of doing:
$name = $_POST['name'];
$age = $_POST['age'];
$location = $_POST['location'];
is there a way of looping through all POST variables and setting it to the same named standard variable?
Extract function can help with this issue:
$_POST = ['foo' => 'bar'];
extract($_POST);
var_dump($foo) //returns 'bar'
http://php.net/manual/en/function.extract.php
It is not recommended to set $_POST variables programmatically. However, if you want it you can use extract function
extract($_POST,EXTR_OVERWRITE,'prefix');
You can be use this:
if ($_POST) {
foreach ($_POST as $key => $value) {
$name = "{$key}";
$$name = $value;
echo "<pre>";
echo $name;
}
echo "<pre>";
echo $name;
echo "<pre>";
echo $age;
echo "<pre>";
echo $location;
}

How to loop through a JSON array and put data in variables

I am trying to get the data from an API and save it to a MySQL database. The problem is when I want to echo the data to check if it gets all the values I'm getting this error:
Notice: Trying to get property of non-object
My JSON data looks like this:
{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"},
I think this is because it is in an array. Because when I use this bit of code it gives no errors but I have to define the index of the array. What is the best way to loop through my data and put it in variables?
<?php
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = $data->AttractionInfo[0]->Id;
$attractieType = $data->AttractionInfo[0]->Type;
$attractieStatus = $data->AttractionInfo[0]->State;
$attractieStatusKleur = $data->AttractionInfo[0]->StateColor;
$attractieWachttijd = $data->AttractionInfo[0]->WaitingTime;
$attractieStatusPercentage = $data->AttractionInfo[0]->StatePercentage;
?>
I tried to find some solutions but all they use is a foreach loop. But i don't think that'll work right. Can anyone help me in the good direction or tell me how I might possibly fix this? I am not very experienced so any advice is welcome. Thanks in advance.
Update code:
require 'database-connection.php';
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = isset($data->AttractionInfo->Id);
$attractieType = isset($data->AttractionInfo->Type);
$attractieStatus = isset($data->AttractionInfo->State);
$attractieStatusKleur = isset($data->AttractionInfo->StateColor);
$attractieWachttijd = isset($data->AttractionInfo->WaitingTime);
$attractieStatusPercentage = isset($data->AttractionInfo->StatePercentage);
$sql = "INSERT INTO attracties (attractieId, attractieType, attractieStatus, attractieStatusKleur, attractieWachttijd, attractieStatusPercentage)
VALUES ('$attractieId', '$attractieType', '$attractieStatus', '$attractieStatusKleur', '$attractieWachttijd', '$attractieStatusPercentage')";
if ($db->query($sql) === TRUE) {
echo "success";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
It says 'success' but when I look into my database it inserted only empty data. I need to add all the attractions to my database so not just one row. So I need to loop through my data.
try this...
$content = json_decode(file_get_contents($url));
foreach($content->AttractionInfo as $data ){
$id = $data->Id;
$type = $data->Type;
$map = $data->MapLocation;
$state = $data->State;
$color = $data->StateColor;
if(!empty($data->WaitingTime)) {
$time = $data->WaitingTime;
}
if(!empty($data->StatePercentage)) {
$percent = $data->StatePercentage;
}
//persist your data into DB....
}
I think you need something like this:
$json = '{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"}]}';
$arr = json_decode($json);
foreach ($arr->AttractionInfo as $key => $attraction) {
foreach($attraction as $key=> $value) {
print_r($key.' - '.$value.'<br>');
$$key = $value;
}
}
echo '<br>';
echo $Id; // it will be last item/attraction id.
We can improve this code. Just say where and how do you want to use it

accesing post variables in array

how can I keep post variables through all the functions in php class?
I'm accessing post variables in a array in function. But when I try to access those in another function it retrvies only the last element in array.
foreach ( $questionAry as $questionID )
{
$questionName = $this->htmlID_questionID . $questionID;
$question_answer = $_POST[$questionName];
$_SESSION['qusID'] = $questionID;
$_SESSION['qusanswer'] = $question_answer;
}
I want to access $questionID and $question_answer in another function. I tried to do it through session, but I can only access last value.
Your loop is wrong...these guys are getting overwritten on every iteration
$_SESSION['qusID'] = $questionID;
$_SESSION['qusanswer'] = $question_answer;
You need to use an indexed loop, something like so...
foreach ( $questionAry as $key => $questionID )
{
$questionName = $this->htmlID_questionID . $questionID;
$question_answer = $_POST[$questionName];
$_SESSION['qusID'][$key] = $questionID;
$_SESSION['qusanswer'][$key] = $question_answer;
}
EDIT: based on conversation below, try something like so.
function getvalues() {
$questions = array();
$jsonEncoded = ( get_magic_quotes_gpc() ) ? stripslashes($_POST[$this->htmlID_questionIDAry]) : $_POST[$this->htmlID_questionIDAry];
$jsonDecoded = json_decode($jsonEncoded);
$questionAry = explode(",",$jsonDecoded->list);
$instr = "";
foreach ( $questionAry as $key => $questionID ) {
$questions[$key]['name'] = $this->htmlID_questionID . $questionID;
$questions[$key]['answer'] = $_POST[$questionName];
}
return $questions;
}
$parsedQuestions = getvalues();
name_of_other_function($parsedQuestions);
function name_of_other_function($parsedQuestions){
print_r($parsedQuestions);
}

Categories