I have two functions that deal with sessions and i need to convert them into codeigniter way.I managed to do the first one
but i am stuck at accessing session array index at the second one
first function:
function addItem($pid,$qty=1){
$_SESSION['basket'][$pid]['kty']=$qty;
}
turned into:
function addItem($pid,$qty=1){
$arr=array($pid=>array('kty'=>$qty));
$this->session->set_userdata('basket',$arr);
}
second function:
function removeItem($pid,$qty=null){
if($qty != null && $qty < $_SESSION['basket'][$pid]['kty']){
$_SESSION['basket'][$pid]['kty']=($_SESSION['basket'][$pid]['kty']-$qty);
}else{
$_SESSION['basket'][$pid]=null;
unset($_SESSION['basket'][$pid]);
}
}
how do i rewrite the second function in codeigniter way?
function removeItem($pid,$qty=null){
if($qty != null && $qty < $_SESSION['basket'][$pid]['kty']){
$_SESSION['basket'][$pid]['kty']=($_SESSION['basket'][$pid]['kty']-$qty);
}else{
$_SESSION['basket'][$pid]=null;
unset($_SESSION['basket'][$pid]);
}
}
Change $_SESSION TO $this->session->userdata for ex :
$_SESSION['basket'][$pid]['kty']
to
$this->session->userdata['basket'][$pid]['kty']
Related
I have this code :
$status = htransaksi::find(auth()->user()->id)->where('Status','Open')->count();
if ($status != 0)
{
$idhtrans = htransaksi::select('id')->where('User_ID', auth()->user()->id)->where('Status', 'Open')->first();
$shopcart = DB::table('detiltransaksis')->join('Barangs', 'Barangs.id', '=', 'detiltransaksis.barang_Id')->where('htrans_Id', $idhtrans->id)->get();
return view('home')->with('barang', $barang)->with('jenis', $jenis)->with('shopcount',$shopcart);
}
else
{
return view('home')->with('barang', $barang)->with('jenis', $jenis);
}
This code checks, is there any item in your shopping cart? If there is an item then return that shopping cart and when there is no item it shows some error that say
Call to a member function where() on null
Anyone knows how to fix this?
I'm new to Laravel and sorry if this is such a newbie question.
Edit :
The error point to
$status = htransaksi::find(auth()->user()->id)->where('Status', 'Open')->count();
The issue is in this line:
$status = htransaksi::find(auth()->user()->id)->where('Status','Open')->count();
if htransaksi::find(auth()->user()->id) returns null then your code will call where on null hence the error:
Call to a member function where() on null
You can simply add a condition and do it separate:
$entryFound = htransaksi::find(auth()->user()->id);
if (empty($entryFound)) {
//this means its returning null then handle that condition here
}
//if entry is found then leave the code as is:
$status = $entryFound->where('Status','Open')->count();
if(Auth::check()) {
$status = htransaksi::where('user_id', Auth::id())->where('Status','Open')->count();
... your "normal logic"
} else {
$error_handling_user_not_logged_in();
}
The reason why I added the Auth::check() check is to make sure that the user is really logged in, feed free to remove it if you already know this because of middleware/request validation.
You code did not work because htransaksi::find(auth()->user()->id) returns a finished data set - if this dataset is empty PHP's where() function failed because you tried to search something which is NULL
As I see htransaksi::find(auth()->user()->id)->where('Status','Open')->count(); is incorrect. You cannot use where() function after find().
Let's try:
$status = htransaksi::where('User_ID',auth()->user()->id)->where('Status','Open')->count();
Can I use codeigniter redirects function contains variable name like this?
redirect($page_url);
I have page url in a session variable so, im saving session in codeigniter varible
$page_url=$_SERVER['REQUEST_URI'];
$page_url=explode("/", $page_url, 3);
$data = array('page_url'=>$page_url[2],'validated' => true);
$this->session->set_userdata($data);
Yes you can use variables surely but make sure you are loading URL helper first and checking if the $page_url variable is set. For example:
$this->load->helper('url');
if(isset($page_url) && $page_url != '') {
redirect($page_url);
} else {
redirect('/index.php');
}
I am trying to load a page dynamically based on the database results however I have no idea how to implement this into codeigniter.
I have got a controller:
function history()
{
//here is code that gets all rows in database where uid = myid
}
Now in the view for this controller I would like to have a link for each of these rows that will open say website.com/page/history?fid=myuniquestring however where I am getting is stuck is how exactly I can load up this page and have the controller get the string. And then do a database query and load a different view if the string exsists, and also retrieve that string.
So something like:
function history$somestring()
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
What I don't understand is how I can detect if $somestring is at the end of the url for this controller and then be able to work with it if it exists.
Any help/advice greatly appreciated.
For example, if your url is :
http://base_url/controller/history/1
Say, 1 be the id, then you retrieve the id as follows:
function history(){
if( $this->uri->segment(3) ){ #if you get an id in the third segment of the url
// load your page here
$id = $this->uri->segment(3); #get the id from the url and load the page
}else{
//here is code that gets all rows in database where uid = myid and load the listing view
}
}
You should generate urls like website.com/page/history/myuniquestring and then declare controller action as:
function history($somestring)
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
There are a lot of ways you can just expect this from your URI segments, I'm going to give a very generic example. Below, we have a controller function that takes two optional arguments from the given URI, a string, and an ID:
public function history($string = NULL, $uid = NULL)
{
$viewData = array('uid' => NULL, 'string' => NULL);
$viewName = 'default';
if ($string !== NULL) {
$vieData['string'] = $string;
$viewName = 'test_one';
}
if ($uid !== NULL) {
$viewData['uid'] = $uid;
}
$this->load->view($viewName, $viewData);
}
The actual URL would be something like:
example.com/history/somestring/123
You then know clearly both in your controller and view which, if any were set (perhaps you need to load a model and do a query if a string is passed, etc.
You could also do this in an if / else if / else block if that made more sense, I couldn't quite tell what you were trying to put together from your example. Just be careful to deal with none, one or both values being passed.
The more efficient version of that function is:
public function history($string = NULL, $uid = NULL)
{
if ($string !== NULL):
$viewName = 'test_one';
// load a model? do a query?
else:
$viewName = 'default';
endif;
// Make sure to also deal with neither being set - this is just example code
$this->load->view($viewName, array('string' => $string, 'uid' => $uid));
}
The expanded version just does a simpler job at illustrating how segments work. You can also examine the given URI directly using the CI URI Class (segment() being the most common method). Using that to see if a given segment was passed, you don't have to set default arguments in the controller method.
As I said, a bunch of ways of going about it :)
In my router.php file I added this code.
$route['mission'] = "content/index/mission";
Here as you know content is controller, index is function and mission is parameter to that function.
But when i check it in my browser, it takes me to content/index .
In other words, it is not passing required parameter to index function.
Make sure your recieving the parameters through the function parameters and not using uri segments.
Controller:
// This is incorrect, and will not work
public function index()
{
$param = $this->uri->segment(3); // This wont work
}
// This is correct and will work.
public function index($param = null) // use null to prevent "undefined var error"
{
if($param != null)
{
// The param was passed and do your stuff here
}
}
I have a model that works with one user in the database.
It is designed to do a lot of small changes to the user, so instead of querying the database multiple times I decided to get all of the user's information in the constructor of the model, and then work on that information through out the rest of the model (so instead of updating the database, it would be updating the array I got). Then I would just save that array back to the database in the destructor.
This works fine, but I've been reading a bit more, and it turns out you shouldn't run any non-cleanup code in the destructor (which is where I'm running the update query to the database). So I was curious, is there a better way to do this? Am I missing a better solution?
Thanks, Max
EDIT:
Here is an example of what I am doing (Note: This example is a shopping cart class, not a user class though):
<?php
class cartmodel extends CI_Model
{
private $sessionPrefix = 'Cart_';
private $CartCache = array();
function __construct ()
{
if ($this->session->userdata($this->sessionPrefix.'data') === FALSE)
$this->session->set_userdata($this->sessionPrefix.'data', array());
$this->CartCache = $this->session->userdata($this->sessionPrefix.'data');
parent::__construct();
}
function __destruct ()
{
$this->session->set_userdata($this->sessionPrefix.'data', $this->CartCache);
}
function AddItem ($id, $count)
{
if ($count == 0 || $count == '' || !is_numeric($count))
return;
if (!isset($this->CartCache[$id]))
$this->CartCache[$id] = 0; //Initialize it so that += works
$this->CartCache[$id] += (int)$count;
}
?>
You can directly manipulate session data in your AddItem() method. Something like this:
function AddItem ($id, $count)
{
// UPDATE CartCache VARIABLE
$this->CartCache = $this->session->userdata($this->sessionPrefix.'data');
// YOUR CODE BELOW
if ($count == 0 || $count == '' || !is_numeric($count))
return;
if (!isset($this->CartCache[$id]))
$this->CartCache[$id] = 0; //Initialize it so that += works
$this->CartCache[$id] += (int)$count;
// SAVE CartCache IN SESSION AGAIN
$this->session->set_userdata($this->sessionPrefix.'data', $this->CartCache);
}
This way if you want to manipulate the Cart_data session variable in other methods, you can still do it. Just update the CartCache array in every method and save it again to the session variable once you've done manipulating data in it.