Session value to array - php

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);

Related

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

PHP is filling json with duplicates of last item

I am working on a web app using php. I am trying to pull from a database and fill an array with the information then encode it to json.
Here is what I have so far:
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frat->name = $row['name'];
$frat->description = $row['description'];
$frat->chapter = $row['chapter'];
$frat->members = $row['members'];
$frat->cover_image = $row['cover_image'];
$frat->profile_image = $row['profile_image'];
$frat->calendar_image = $row['calendar_image'];
$frat->preview_image = $row['preview_image'];
$frat->address = $row['address'];
$frats[] = $frat;
}
echo json_encode($frats);
What I get in return is in the correct json format I want with the correct keys and everything, but every item in the json is the same. All of them are the last one. I believe this is because I might just be referencing the values, but I am not sure how to actually copy them in php.
Any suggestions?
you need to create a new instance of $frat inside the loop. Otherwise you are just updating the original $frat each time the loop runs and adding a reference to it in the array.
Assuming its not a static class you could use:
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frat = new frat();
$frat->name = $row['name'];
$frat->description = $row['description'];
$frat->chapter = $row['chapter'];
$frat->members = $row['members'];
$frat->cover_image = $row['cover_image'];
$frat->profile_image = $row['profile_image'];
$frat->calendar_image = $row['calendar_image'];
$frat->preview_image = $row['preview_image'];
$frat->address = $row['address'];
$frats[] = $frat;
}
echo json_encode($frats);
Even better would be to modify the constructor or create a method to consume the data. If you used the class's constructor then you could do something like this:
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frats[] &= new frat($row['name'], $row['description'], $row['chapter']);
}
echo json_encode($frats);
In the first line inside your while loop, you simply need the following line:
$frat = new \stdClass();
You need to properly declare your variables $frats (array) and $frat (object):
$frats = array();
while ($row = mysqli_fetch_array($result)) {
$frat = (object) array();
$frat->name = $row['name'];
$frat->description = $row['description'];
$frat->chapter = $row['chapter'];
$frat->members = $row['members'];
$frat->cover_image = $row['cover_image'];
$frat->profile_image = $row['profile_image'];
$frat->calendar_image = $row['calendar_image'];
$frat->preview_image = $row['preview_image'];
$frat->address = $row['address'];
array_push($frats, $frat); // For backward compatiblity
}
echo json_encode($frats);

How to add value to associative array that store in session?

include('session.php');
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$wishlist = array("$productname" => $productcode);
$_SESSION["wishlist"] = $wishlist;
print_r($_SESSION["wishlist"]);
This code set as an array to a session named "wishlist".
The problem is that the session is being replaced. I want to add to the array if it already exists.
So how can I update my array with new data.
I have tried the following.
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];
// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
$wishlist = array("$productname" => $productcode);
} else {
/*
How Can I Update array ???
*/
}
The array output is like so. It is associated not numeric indexed.
And i want result in single array. Not array in array.
[mobile] => iphone_2
Thank you.
In short, you can do this (if I understand the question correctly):
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];
// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
$wishlist = array("$productname" => $productcode);
} else {
array_push($wishlist, array("$productname" => $productcode));
}
array_push is a function that will add information to the end of an array. In this instance, we are using it to add the product array to the current wishlist.
An alternative simple solution would be:
// create a blank array if the session variable is not created
// array_push requires an array to be passed as the first parameter
$wishlist = isset($_SESSION["wishlist"]) ? $_SESSION["wishlist"] : array();
//$wishlist = $_SESSION["wishlist"] ?? array(); // this is for PHP 7+
array_push($wishlist, array("$productname" => $productcode));
// you can then access each product as:
$wishlist["mobile"];
Or replace line 5 from the above code snippet with the following:
$wishlist[$productname] = $productcode;
This would save you from creating an empty array as in line 3.
The advantage that array_push has over this is that you can add multiple products at once such as:
$products = [$productname1 => $productcode1, $productname2 => $productcode2];
array_push($wishlist, $products);
The one thing I have noticed is that you are setting the session to $lastsession as well as using $wishlist. Try and keep duplicate variables to non-existent.
$_SESSION["wishlist"] = array( 'product1' => 'product1 Name' );
// Initial products in session
$temp_session = $_SESSION["wishlist"];
//store products in wishlist in temp variable
$temp_session['mobile'] = 'iphone_2';
// Add new product to temp variable
$_SESSION["wishlist"] = $temp_session;
//Update session
print_r( $_SESSION["wishlist"] );
Set the wishlist data from the session to variable and then just add the new product to this variable. After that update the wishlist data in the session.
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
// do the same as: $wishlist = !empty($_SESSION["wishlist"]) ? $_SESSION["wishlist"] : [];
$wishlist = $_SESSION["wishlist"] ?? [];
$wishlist[$productname] = $productcode;
$_SESSION["wishlist"] = $wishlist;
print_r($_SESSION["wishlist"]);

convert data to json(jquery select2 plugin)

I have a table users. in this table i have a field and in that field data is something like this test,test1,test2.
I am using ajax to fetch the data from this table and show it on php file.
I am able to fetch the data but due to select2 plugin. i need to make proper formatting of this data.
fetch.php
$data = array();
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
}
echo json_encode($data);
keywords field have data something like this test,test1,test2
i need to make it in proper json format like this.
id:test text:test
id:test1 text:test1
so on.
Is it possible to make it like.
Add this code in your code (new code have comment):-
<?php
$data = array();
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
}
// code need to add
$new_data = explode(',',$data['keywords']);
$final_data = array();
foreach($new_data as $new_dat){
$final_data[] = array('id'=>$new_dat,'text'=>$new_dat);
}
echo "<pre/>";print_r( $final_data);
$data['keywords'] = $final_data; // assingnment
// print json encoded data in last
echo json_encode($data);
?>
An example code:- https://eval.in/528365
Yes you can make and two dimensional array inside empty array and $arrays = ('a' => 'b') like this then json_encode($arrays) now you get json object
Is this what are you looking for:
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
$data = array(
"id" => $data['keywords'],
"text" => $data['keywords']
);
}
echo json_encode($data);

php function not returning all results from a MySQL query in a foreach

Hey guys I have a little issue with a function that retrieves data from a MySQL Database and then I iterate over the results with a foreach loop, checking a value to see if it is null and if it is, replacing it with another value.
The problem with this function is this, that after returning the data I'm only able to view one record retrieved from the database. Probably something simple but it's beyond me.
I would like to do this before passing it to the controller or view. Maybe this isn't possible with the foreach loop? What am I missing?
Here is an example of my code.
public function get_basic_user_data(){
$sql = 'SELECT Account.First_Name, Account.Last_Name, Account.User_Name, Profile_Photos.Thumb_Url
FROM Account
LEFT JOIN Profile_Photos ON Account.idAccount = Profile_Photos.Account_Id
AND Profile_Photos.Active = 1
WHERE Account.idAccount != ?';
$account_id = $this->get_account_id();
$data = $this->db->query($sql, $account_id);
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
}
return $new_data;
}
Hopefully someone can help me with this? Thanks!
At the moment you are just returning the last data row. Change your code like this to return an array of all your rows from that function:
$rows = array()
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
$rows[] = $new_data;
}
return $rows;
This way every row returned from the database will be added to an array named $rows. At the end you have to return your new array.
You are overwriting $new_data each iteration. Try this
$new_data = new stdClass
...
$all_data[] = $new_data;
Instead of checking for null value in the code, you could just use a IFNULL statement in the SQL query, this does separate the logic a bit but it might just be worth it in this case.
The function returns only the last row in the result because the new_data variable is overwritten in every step of your loop. Declare new_data an array at the start of your function and add rows as array elements
...
$new_data[] = new stdClass;
...
Each iteration of the foreach overwrites $new_data so in the end when the function returns, only the last fetched row will be returned. To return more than one row you could store all the rows in an array and then return the array in the end. It would look something like this:
public function get_basic_user_data(){
$sql = 'SELECT Account.First_Name, Account.Last_Name, Account.User_Name, Profile_Photos.Thumb_Url
FROM Account
LEFT JOIN Profile_Photos ON Account.idAccount = Profile_Photos.Account_Id
AND Profile_Photos.Active = 1
WHERE Account.idAccount != ?';
$account_id = $this->get_account_id();
$data = $this->db->query($sql, $account_id);
$data = array();
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
$data[] = $new_data;
}
return $data;
}
To be able to use this function you have to change the code that uses it to loop through the array of objects.

Categories