Pass Variable from View to Controller in Codeigniter using PHP - php

I am working on a project where I need to pass a variable from the View to a Controller's method where I'll be using that variable's value. I have tried the following.
View
...
$user = 3;
...
<ul class="nav navbar-nav navbar-right">
<li>
<a href="<?php echo base_url() ?>index.php/studentDashboardController/index?user=$user">
My Dashboard
</a>
</li>
...
studentDashboardController (Method 1)
public function index()
{
...
if ( isset($_GET['user']) ) {
$user = $_GET['user'];
echo '<script type="text/javascript">alert("User taken from GET: ' . $user . '")</script>';
}
...
Output for Method 1
studentDashboardController (Method 2)
public function index()
{
...
if($this->input->get())
{
$user = $this->input->get('user');
echo '<script type="text/javascript">alert("Uid taken from Method 2 ' . $user . '")</script>';
}
...
Output for Method 2
Any suggestions on how to get the value of this passed variable will be highly appreciated.

You were missing the PHP notation while printing the $user variable. Update the below line in the View
<a href="<?php echo base_url() ?>index.php/studentDashboardController/index?user=<?php echo $user; ?>">

Related

How to pass argument for function in controller from view

I have function in controller with one argument and now I want to pass value for it from view through url.
courses.php
public function index($id){
print_r();
exit;
}
coursesview.php
<a class="jscroll-next" href="<?php echo base_url(); ?>/courses/index?page=<?php echo $nextPage; ?>&id=<?php echo $parentId ?>">next page</a>
How it possible?
From the user guide,
Simply put the parameter in an array and pass it to the view by using the second parameter of load->view().
Afterwards, in the view, the variable will be available as the key.
In this example: $id or $anothervar.
courses.php
public function index($id){
$data = array('id' => $id, 'anothervar' => 'yeahi');
$this->load->view('coursesview', $data);
// exit;
}
coursesview.php
echo $id; // the ID
echo $anothervar; // "yeahi"
You are going to use minimum arguments in URL, here is my suggestions
1.<a class="jscroll-next" href="<?php echo base_url('courses/$nextPage/$parentId/'); ?>">next page</a> //controller followed by arguments - if you call index method
(OR)
2.<a class="jscroll-next" href="<?php echo base_url('courses/methodname/$nextPage/$parentId/'); ?>">next page</a> //controller,method name and followed by arguments
How to get those arguments in controller
Example:
$nextPage = $this->uri->segment(3);
$parentId = $this->uri->segment(4);

syntax error, unexpected '.' in PHP OOP [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
I'm working on a simple project and I'm using PHP Object Oriented. Basically I have a class that contains information about how to get data from MySQL database and show them on a page. This class is called admin.php and goes like this:
<?php
class Admin{
private $db,$username,$password,$id,$group,$Datetime,$msg;
public function __construct()
{
$this->db = new Connection();
$this->db = $this->db->dbConnect();
}
public function getAdmin($name)
{
if(!empty($name))
{
$adm = $this->db->prepare("select * from admins where username=?");
$adm->bindParam(1,$name);
$adm->execute();
while($row = $adm->fetch())
{
$this->id = $row['id'];
$this->username = $row['username'];
$this->password = $row['password'];
$this->group = $row['group'];
$this->Datetime = $row['date_joined'];
$this->msg = $row['welcome_message'];
}
}
}
public function getID()
{
return $this->id;
}
public function getUsername()
{
return $this->username;
}
public function getPassword()
{
return $this->password;
}
public function getGroup()
{
return $this->group;
}
public function gtDate()
{
return $this->Datetime;
}
public function welcomeMessage()
{
return $this->msg;
}
}
?>
Then on another page which is called dashboard.php ,I have included this class file and coded this:
<?php if ($dataSet->welcomeMessage()== 0){
echo "
<li class='dropdown messages-menu'>
<!-- Menu toggle button -->
<a href='#' class='dropdown-toggle' data-toggle='dropdown'>
<i class='fa fa-envelope-o'></i>
<span class='label label-success'>1</span>
</a>
<ul class='dropdown-menu'>
<li class='header'>You have one new message</li>
<li>
<!-- inner menu: contains the messages -->
<ul class='menu'>
<li><!-- start message -->
<a href='message.php?msg=".$dataSet->msg();."'>
<div class='pull-left'>
<!-- User Image -->
<img src='dist/img/user2-160x160.jpg' class='img-circle' alt='User Image'>
</div>
<!-- Message title and timestamp -->
<h4>
Support Team
<small><i class='fa fa-clock-o'></i>Just now</small>
</h4>
<!-- The message -->
<p>Welcome to your admin panel</p>
</a>
</li>
<!-- end message -->
</ul>
<!-- /.menu -->
</li>";
}
?>
But whenever I run it ,I get this error message:
Parse error: syntax error, unexpected '.' on line 15 in dasboard.php
Here's the line 15 of the dasboard file:
<a href='message.php?msg=".$dataSet->msg();."'>
Pretty sure that this must be related to the wrong concatenating and combining a class method within a html tag while I'm echoing out a statement.
So what's the correct way to do this ?
"$dataSet->msg" is not a function but a property, and you need to call it like this.
<a href='message.php?msg=".$dataSet->msg."'> // but wont work as it is private
or use the method call as in the below line
<a href='message.php?msg=".$dataSet->welcomeMessage()."'>
Ok, let supoose that $dataSet is defined, and it has all required methods. Then you just need to omit the ;:
echo "some text " . $dataSet->msg() . " more text";

Delete from the database using CodeIgniter

I want to make one delete function, but I do not know what steps did wrong?
This is the file model:
function delete()
{
$this->db->delete('ns_categories', array('cat_id' => $cat_id));
}
Controller:
function delete()
{
$this->cat_model->delete();
$cat_id=$this->uri->segment(3);
if($cat_id->delete()) return json_encode(array("success" => true));
}
View:
<td class="centeralign"><a class="deleterow" href="<?php echo anchor('admin/categories/delete' .<?php echo $row['cat_id']; ?>"><span class="icon-trash"></span></a></td>
Please help me.
You haven't done anything right, no offense. It's a mess.
View:
You missed a forward slash here:
href="<?php echo 'admin/categories/delete' .<?php echo $row['cat_id']; ?>"
^^^
...but you don't use anchor() this way anyways, it generates an entire link. And you have nested two <?php echos... What a mess. Do it like this:
<a href="<?php echo base_url('admin/categories/delete/'.$row['cat_id']; ?>">
Model:
You haven't defined $cat_id in the model's delete function. Also, don't return json from a model. Do it like this:
function delete($cat_id = null)
{
return $this->db->delete('ns_categories', array('cat_id' => $cat_id));
}
Controller:
You're calling delete as a method of $cat_id which makes no sense, as the variable contains a number - not an object you can call a method on. You also have to echo/print the json, and you should set json headers. Do it like this:
function delete($cat_id = null) {
$status = $this->cat_model->delete($cat_id);
header('Content-type: application/json');
echo json_encode(array("success" => $status));
}
You should use POST method to delete things, otherwise people can delete things accidentally or do stupid tricks like <img src="delete/item/1">
Remove extra echo from link:
<td class="centeralign">
<a class="deleterow" href="<?php echo anchor('admin/categories/delete' . $row['cat_id']); ?>">
<span class="icon-trash"></span>
</a>
</td>
In your Controller delete function you have got the category id after calling the delete function of model why? And in your model function from where you are getting $cat_id ?? it should be like this
function Category_delete(){
$cat_id=$this->uri->segment(3);
if($this->cat_model->delete($cat_id)) return json_encode(array("success" => true));
}
In your view you have opened the <?php again and also you are using anchor function in the href anchor function generates the complete <a> tag see reference for helpers CI Helpers
<td class="centeralign"><a class="deleterow" href="<?php echo site_url('admin/categories/Category_delete/'.$row['cat_id']; ?>">
<span class="icon-trash"></span></a></td>
And you should rename the functions because delete may be a keyword so use ordinary names for the functions

Zend getting database record false

I have a link http://mywebsite.com/referral/dafa60b2b96c366e165be58649755742
With a parameter dafa60b2b96c366e165be58649755742
Was try to get that parameter to connect to database to get that user information, but it end up getting no object: Notice: Trying to get property of non-object in line.....
here's my code:
application.ini:
resources.router.routes.referralSelectProduct.route = "/referral/:url"
resources.router.routes.referralSelectProduct.defaults.controller = Index
resources.router.routes.referralSelectProduct.defaults.action = referral-select-product
resources.router.routes.referralSelectProduct.reqs.url = "[0-9a-zA-Z]+"
controller:
public function referralSelectProductAction()
{
$referral_url = $this->getRequest()->getParam('url');
$user = $this->_helper->model('Users')->fetchRowByFields(array('url' => $referral_url));
setcookie('referral_url', $referral_url, time() + 3600*24*30, '/');
}
model:
class Application_Model_DbTable_Users extends Sayka_Db_Table_Abstract{
protected $_rowClass = 'Application_Model_DbTable_Row_User';protected $_name = 'users';}
view:
<div id="content_bottom" class="content"><br/>
<h1>Select the product to refer your friend <span class="colorset_orange"><?php echo $this->user()->first_name; ?></span>.</h1>
<div><a class="refer_submit" href="?email=<?php echo $this->user()->email ?>&first_name=<?php echo $this->user()->first_name; ?>&last_name=<?php echo $this->user()->last_name; ?>" id="btn_free_download">Free Download</a></div>
<div><a class="refer_submit" href="#" id="btn_buy_now">Buy Now</a></div>
My view end up getting no object of that user in the database.
If i remember it correctly (for zend framework 1.*):
// Controller
...
$this->view->user = $this->_helper->model('Users')->fetchRowByFields(array('url' => $referral_url));
// View
echo $this->user->email;
Make sure that this $this->_helper->model('Users')->fetchRowByFields(array('url' => $referral_url)) returns you what you expect. var_dump it in controller

call class method from included file, can set class variable but not call method/function

I have a very simple class
if(!isset($_GET['page'])) {
$_GET['page'] = "home";
}
class be_site {
var $thelink;
public function get_static_content($page) {
$this->check_path($page);
} // end function
private function check_path($pathfile) {
if(file_exists($pathfile)) {
$b = 1;
include_once($pathfile);
} else {
$b = 2;
include_once('error_page.php');
}
}// End Function
public function selectedurl($subpage, $linkname){
if($subpage == $this->thelink) {
echo "<strong>" . $linkname . "</strong>";
} else {
echo $linkname;
}// End if
} // End function
} /// End site class
Now I create a new object in the index.php
include('connections/functions.php'); $site_object = new be_site;
In the content are I have
//get file
if(isset($_GET['subpage'])){
$site_object->get_static_content('content/' . $_GET['subpage'] . '.php');
}else {
$berkeley_object->get_static_content('content/' . $_GET['page'] . '.php');
}
Ok so all working fine. But if an included page is called I use try to use my other method to wrap a link and make it bold if it is selected depending on the $_GET['page'] value.
for instance
<ul>
<li><a href="index.php?page=team&subpage=about" target="_self" title="opens in same window" >
<?php $site_object->thelink = "about_us";
$site_object->selectedurl($_GET['subpage'],'about Our Website'); ?>
</a>
</li>...
And so on for each link.
Now can set the variable in the object but not call the method. I get the error
Fatal error: Call to undefined method stdClass::selectedurl()
Just wondered why I am able to set the $thelink variable in the class from an included file but not call a public function?
Thanks
Change this code:
<?php $site_object->thelink = "about_us";
$site_object->selectedurl($_GET['subpage'],'about Our Website'); ?>
To this:
<?php
global $site_object;
$site_object->thelink = "about_us";
$site_object->selectedurl($_GET['subpage'],'about Our Website'); ?>
The reason this isn't working is due to the nature of using include within a function. If you use include inside a function (be_site::check_path), the variable scope is specific to that function. See http://php.net/manual/en/function.include.php example #2.

Categories