I am not very much sure if my title question is correct, however i am facing sever error of multiple loops within foreach, despite of having only one item in array. I am pasting my code here;
Display (Controller)
$table_data = array(
'table_data' => $this->display_model->get_table_data($table_name),
'edit_table_data'=>$this->display_model->get_table_data($table_name,$row_id)
);
$form_name='edit_'.$table_name;
$this->load->view('header');
$this->load->view($form_name,$table_data);
$this->load->view('footer');
You can see tabe_data and edit_table_data is calling same function with different parameter.
Here i doubt on the time scheduling between these two function calls (which honestly i am wrong because codeigniter manages function calls)
Display_model (Model)
public function get_table_data($table_name,$row_id=null)
{
$return = "";
if ($row_id != null)
{
switch ($table_name) {
case 'user':
//$return = $this->db->where($table_name."_id",$row_id)->get($table_name)->result();
$return = $this->db->select($table_name.'.*,country.country_name')
->join('country','country.country_id=user.user_country_id','left')
->where($table_name.'_id',$row_id)
->get($table_name)->result();
break;
case 'user_document':
//$return = $this->db->where($table_name."_id",$row_id)->get($table_name)->result();
$return = $this->db->select($table_name.'.*,document.document_name')
->join('document','document.document_id=use_document.document_id','left')
->where($table_name.'_id',$row_id)
->get($table_name)->result();
break;
default:
$return = $this->db->where($table_name."_id",$row_id)->get($table_name)->result();
break;
}
if($return != null)
{
return $return;
}
else
{
return "no_data";
}
}
Here is my view where i am getting error
<?php foreach ($edit_table_data as $etd_row) {?>
<form method="post" class="form-horizontal" action="<?php echo site_url('admin/edit_row/user_type/'.$etd_row->user_type_id)?>">
<div class="form-group">
<label class="col-sm-4 control-label">User Type Name</label>
<div class="col-sm-8"><input type="text" class="form-control" name="user_type_name" value="<?php echo $etd_row->user_type_name?>"></div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-2 col-sm-offset-2">
<button class="btn btn-primary" type="submit">Edit changes</button>
</div>
</div>
</form>
<?php } ?>
on the foreach loop line, i am given error
Thanks in advance for your comments
Error
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: views/edit_user_type.php
Line Number: 18
Backtrace:
File: C:\wamp\www\gmf\application\views\edit_user_type.php
Line: 18
Function: _error_handler
File: C:\wamp\www\gmf\application\controllers\Display.php
Line: 170
Function: view
File: C:\wamp\www\gmf\index.php
Line: 315
Function: require_once
You'd get this error if $edit_table_data is not an array -- in this case probably a string.
My CI knowledge is a bit rusty, but I guess something along these lines may help you out:
$query = $this->db->select($table_name.'.*,country.country_name')
->join('country','country.country_id=user.user_country_id','left')
->where($table_name.'_id',$row_id)
->get($table_name);
if ($query->num_rows() === 0){
return []; // Make sure we're always returning an array.
// I'd rather handle this stuff in the view...
// Probably some kind of message that shows:
// that there are not results when $edit_table_data is not an array, otherwise loop.
}
return $query->result();
Or you could do something along these lines:
<?php
if (!is_array($edit_table_data)) {
echo 'No results here.';
} else {
foreach ($edit_table_data as $etd_row) { ?>
<form method="post" class="form-horizontal"
action="<?php echo site_url('admin/edit_row/user_type/' . $etd_row->user_type_id) ?>">
<div class="form-group">
<label class="col-sm-4 control-label">User Type Name</label>
<div class="col-sm-8"><input type="text" class="form-control" name="user_type_name"
value="<?php echo $etd_row->user_type_name ?>"></div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-2 col-sm-offset-2">
<button class="btn btn-primary" type="submit">Edit changes</button>
</div>
</div>
</form>
<?php
}
}
?>
There does not seem to be a reason to call get_table_data twice, once with and once without $row_id, because you never use $table_data['$table_data'] in the view. In the interests of getting something that works that first call should be eliminated. The revised controller looks like this.
$table_data['edit_table_data'] = $this->display_model->get_table_data($table_name,$row_id) ;
$form_name='edit_'.$table_name;
$this->load->view('header');
$this->load->view($form_name,$table_data);
$this->load->view('footer');
The model code in the question is missing a curly brace } to close this statement.
if ($row_id != null)
{
So it is a little hard to tell exactly what you want to happen if $row_id is not provided. Without further information, my opinion is that get_table_data should not give the second argument a default value. In other words, the function should be defined without a default value for `$row_id - like this.
public function get_table_data($table_name, $row_id)
Without a default value for `$row_id a fatal error occurs if no value is provided. So the controller will need to make sure a value is provided.
Likewise, the controller should always check the return of the model is appropriate, or the model should always return something that the view can use.
get_table_data() contains a lot of repeated code - where($table_name.'_id', $row_id) and get($table_name)->result() appear three times each. By rearranging the logic, the repeating lines can be eliminated to make the function much more concise. Consider this version.
public function get_table_data($table_name, $row_id)
{
if($table_name === 'user')
{
$this->db
->select($table_name.'.*, country.country_name')
->join('country', 'country.country_id = user.user_country_id', 'left');
}
elseif($table_name === 'user_document')
{
$this->db
->select($table_name.'.* ,document.document_name')
->join('document', 'document.document_id = use_document.document_id', 'left');
}
return $this->db
->where($table_name."_id", $row_id)
->get($table_name)
->row();
}
The above returns data from any $table_name where $table_name."_id" == $row_id. Specific "select" and "join" clauses are added in the case of 'user' or 'user_document' tables.
Because you seem to be interested in only one row you should call row() instead of result().
It's important to know that db->row() will return NULL if no records are found. That fact can be used to test the model return and react appropriately. In this case, we do the check in the view. Because there is only one row. no foreach is needed.
<?php if(isset($edit_table_data)) { ?>
<form method="post" class="form-horizontal" action="<?php echo site_url('admin/edit_row/user_type/'.$edit_table_data->user_type_id) ?>">
<div class="form-group">
<label class="col-sm-4 control-label">User Type Name</label>
<div class="col-sm-8"><input type="text" class="form-control" name="user_type_name" value="<?php echo $edit_table_data->user_type_name ?>"></div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-2 col-sm-offset-2">
<button class="btn btn-primary" type="submit">Edit changes</button>
</div>
</div>
</form>
<?php
}
else { ?> <div>No Data Available</div> <?php } ?>
Related
So, in my project, a user needs to register first before logging-in. I am trying to display their first, middle and last name. But, I am having a problem since multiple data are displayed on my input field. What is the correct query? Here is my controller code
public function get_first_name()
{
$first_names = UserModel::all();
$input="<input></input>";
foreach($first_names as $first_name)
{
$input.="<input value={$first_name->seq_id}>{$first_name->first_name}</input>";
}
return $input;
}
public function step1()
{
$users = UserModel::all();
$data['optStatus']=$this->get_civil_status();
$data['displayFirstName']=$this->get_first_name();
return view ("enrollment-steps.step1", $data);
}
Here is the blade file
<div class="col-sm-12 col-lg-4">
<div class="form-group row">
<label for="firstName" class="col-sm-3 text-right control-label col-form-label">First
Name</label>
<div class="col-sm-9">
<input class="form-control" type="text" id='firstName' readonly value="{!! $displayFirstName !!}" >
</div>
</div>
</div>
this is the data that it displays
There is some confusing stuff going on there, but you probably want
<input class="form-control" type="text" id='firstName' readonly value="{{ $data['displayFirstName'] }}" >
which will display the value with the key 'displayFirstName' in the $data array.
dd is your friend, use this in your blade file to see what you have in your $data variable.
{{dd($data)}}
In you controller bind the data's in a single variable, then show it in the blade
public function get_first_name()
{
$first_names = UserModel::all();
$input="<input></input>";
foreach($first_names as $first_name)
{
$input.="<input value={$first_name->seq_id}>{$first_name->first_name}</input>";
}
return $input;
}
Instead of this, do something like this:
public function get_first_name()
{
$first_names = UserModel::all();
$input="<input></input>";
foreach($first_names as $first_name)
{
$displayname = $first_name->seq_id . $first_name->first_name;
$input.="<input value="{$displayname}"</input>";
}
return $input;
}
This question already has an answer here:
PDO Return All Rows [duplicate]
(1 answer)
Closed 3 years ago.
I have a cooperative(user) that can post many newsfeeds, so a one is to many relationship. My goal is to show all the newsfeeds of the cooperative in a list and use that list to link each newsfeeds to an update and delete page. However my code is only showing the first newsfeed and since I put it inside a loop, the first newsfeed is being loop six times. Why is that?
Im using the $loggerUser['coopID'] to get the coopID that is supplied to the where clause of the viewCoopNewsfeed function.
this is my sql command
function viewCoopNewsfeed($coopID)
{
try {
$connection = connect();
$statement = $connection->prepare("SELECT * FROM newsfeed WHERE
coopID = :coopID");
$statement->bindParam(":coopID", $coopID);
$statement->execute();
$statement->setFetchMode(PDO::FETCH_ASSOC);
if ($coopNewsfeed = $statement->fetch()) {
return $coopNewsfeed;
} else {
return NULL;
}
} catch (PDOException $exception) {
die("Error: " . $exception->getMessage());
}
}
and this is the loop in the view
<?php
if(!empty($coopNewsfeeds))
{
foreach($coopNewsfeeds as $coopNewsfeed)
{
?>
<form method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Photo</label>
<img class="profile-pic" src="<?=$coopNewsfeeds['photo']?>"/>
</div>
</div>
<br><br><br><br><br><br><br><br><br><br>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" placeholder="Title" name="title" value="<?=$coopNewsfeeds['title']?>" required>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Body</label>
<textarea class="form-control" name="Body" value="<?=$coopNewsfeeds['Body']?>" placeholder="Body" id="" cols="30" rows="2"></textarea>
</div>
</div>
</form>
<?php
}
?>
<?php
}
?>
$coopNewsfeed = $statement->fetch() this fetches the next result (the first one in your case, because you executed fetch() only once). Since you are returning $coopNewsfeed immediatly after this statement, you are getting only 1 row.
Use fetchAll() instead.
if ($coopNewsfeed = $statement->fetchAll()) {
return $coopNewsfeed; // this now returns all results in a 2d array
} else {
return NULL;
}
And then, in your view :
foreach($coopNewsfeeds as $coopNewsfeed)
{
// some html
// notice the variable name -----v-----------v
<img class="profile-pic" src="<?=$coopNewsfeed['photo']?>"/>
// more html and stuff
}
I did a search and I want to display the result, but I cannot convey the variable to the view,
although I specify it in the controller.
My piece of view code:
<div class="search col-md-6">
<p>
Найти сотрудника по id
</p>
<form action="{{route('searchID')}}" class="search-id" method="GET">
<div class="row">
<div class="col-xs-10">
<div class="form-group">
<input class="form-control" name="id" required="" type="text" value="{{ old('id') }}">
</input>
</div>
</div>
<div class="col-xs-2">
<div class="form-group">
<input class="btn btn-info" type="submit" value="Искать">
</input>
</div>
</div>
</div>
{{$result}}
</form>
<div>
</div>
</div>
my route:
Route::match(['get', 'post'], 'searchID', 'SearchController#indexID')->name('searchID');
my method in the controller:
public function indexID(Request $request, View $view)
{
//$message= "Сотрудник не найден";
$id = $request->input('id');
dump($id);
$result = Staff::where('public_id', $id)->get();
if ($result == null) {
//dump($message);
return redirect()->back()->withInput($id);
} else {
dump($result);
return view('addworker')->with('result', $result);
}
}
But I constantly get an error: Undefined variable: result
I tried:
return view('addworker')->with($result);
and
return view('addworker',$result);
and
return view('addworker', ['result', $result]);
None of this helped me, I don't know what to do anymore
How to make the template access this variable only after the controller has been processed?
You can use compact for the same,
return view('addworker', compact('result'));
compact — Create array containing variables and their values
I hope this will help you
return view('addworker', ['result' => $result]);
You used the wrong syntax to send your variable to your view, there is a lot os ways to do that:
You could use the compact function:
return view('addworker', compact('result'));
You could use the with() method:
return view('addworker')->with('result', $result);
Or:
return view('addworker', ['result' => $result]);
You could also check the official documentation: click here
Error
Not able to pass the value from this application to other website.
View
In this view using action i have called the controller function. If the user selects Pay-Me then value 1 will be passed to controller function.
<form id="formMuktinath" method="post" action="<?php echo base_url().'index.php/booking/bookManakamana'?>">
<div class="form-group">
<label for="name" class="col-sm-3 col-lg-offset-2 control-label">Payment From </label>
<div class="col-sm-4">
<select class="select form-control" name="manakamana[payment_from]">
<option value="1" selected>Pay-Me</option>
<option value="2">BIL</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
Controller
If 1 is selected then it calls payme website. Then there redirect function using $data does not pass amt value to payme website.
public function bookManakamana(){
if ($data = $this->input->post('manakamana')) {
$data['created_on'] = date('Y-m-d H:i:s');
if ($data['payment_from'] == '1') {
$data['amt'] = '100';
redirect('http://dev.payme.com/pay/main',$data);
}
if ($data['payment_from'] == '2') {
echo 'bli';
exit;
}
redirect('booking/index');
} else {
$this->load->view('index');
}
}
if you want to pass values in link as get variable
www.somewebsite.com/?var='value'
but if you want to send variable as post you need to use curl
I have been having a problem... a frustrating problem at that. I cannot seem to edit a specific row in Codeigniter. I have found previous questions on the same here, and even tried the solutions but to no avail. I am press for time on this project I am undertaking. Before you regard this question as a duplicate please have a look see. Any help will be greatly appreciated... Thank you in advance My code snippets are below:
Codeigniter/Controller
<?php..
//Selects all from admin table
function get_admin(){
$data['query'] = $this->Superuser_Model->selectadmin();
}
//brings in the view
// function editAdmin(){
// $data['content'] = 'admin/edit_admin';
// $this->load->view('include/template_back', $data);
// }
//click a specific row in the view (tabulated data)
function edit($id){
$data['array']= $this->Superuser_Model->editadmin($id);
// $data['content'] = 'admin/edit_admin';
$this->load->view('include/header_back');
$this->load->view('admin/edit_admin', $data);
$this->load->view('include/footer_back');
}
//Should update the from
function update_superuser(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run()==FALSE)
{
$data['content'] = 'admin/add_admin';
$this->load->view('include/template_back', $data);
}
else
{
$username = $this->input->post('username');
$password = md5($this->input->post('password'));
$date_added = $this->input->post('date_added');
$this->Superuser_Model->update_superuser($username,$password,$date_added);
redirect('login/index', 'refresh');
}
}
..?>
Codeigniter/Model
<?php...
function selectadmin(){
// $id = $this->uri->segment(3);
$query = $this->db->get('admin');
return $query->result_array();
}
function editadmin($id){
$id = $this->uri->segment(3);
$query = $this->db->get('admin');
$this->db->where('adminID', $id);
return $query->result_array();
}
function update_superuser($data, $id){
$this->uri->segment(3);
$id = $this->input->post('adminID');
$data = array(
'username'=> $this->input->post('username'),
'password'=> $this->input->post('password'),
'date_added'=> $this->input->post('date_added')
);
$this->db->where('adminID', $id);
$this->db->update('admin', $data);
}
...?>
Codeigniter/View
...
<?php echo form_open('superuser/update_superuser', array('class' => 'form-horizontal', 'enctype' => 'multipart/form-data')); ?>
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-btns">
×
−
</div>
<h4 class="panel-title">Admin Details</h4>
<p>Please, Insert your details here below... (for Superuser use only)</p>
</div>
<div class="panel-body panel-body-nopadding">
<!--username-->
<div class="form-group">
<!-- <input type="hidden" name="adminID" class="form-control" value="<?php echo $array->adminID;?>"/> -->
<label class="col-sm-4 control-label">Username</label>
<div class="col-sm-8">
<input type="text" name="username" class="form-control" value="<?php echo $array['username'];?>"/>
</div>
// <?php // form_error('username');?>
</div>
<!--password-->
<div class="form-group">
<label class="col-sm-4 control-label">Password</label>
<div class="col-sm-8">
<input type="password" name="password" class="form-control" value="<?php echo $array['password'];?>"/>
</div>
<?php //echo form_error('date_added');?>
</div>
<!--Date Added-->
<div class="form-group">
<label class="col-sm-4 control-label">Date</label>
<div class="col-sm-8">
<input type="text" name="date_added" class="form-control" id="datepicker" value="<?php echo $array['date_added'];?>" /> <img src="<?php echo base_url();?>components/backend/images/calendar.gif" alt="" /><br /><br />
</div>
<?php //echo form_error('date_added');?>
</div>
</div><!-- panel-body -->
<div class="panel-footer">
<button class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div><!-- panel-footer -->
</div><!-- panel-default -->
<?php form_close();?>
...</body></html>
Errors Displayed
A PHP Error was encountered
Severity: Notice
Message: Undefined index: username
Filename: admin/edit_admin.php
Line Number: 54
A PHP Error was encountered
Severity: Notice
Message: Undefined index: password
Filename: admin/edit_admin.php
Line Number: 62
A PHP Error was encountered
Severity: Notice
Message: Undefined index: date_added
Filename: admin/edit_admin.php
Line Number: 70
Seems like not correct $array['username'], $array['password'] and $array['date_added']. Print out $array first and you'll see what's wrong.
I see a few things... Firstly, you are trying to use the $this->input->post method which is beyond the scope of the model (relevant only to the controller). This is what provides you with the php errors...
Secondly, you are passing the right parameters to the model (minus cleaning them from XSS attacks, notice), but you are accepting different ones, so in the model your function should look something like this
function update_superuser($username, $password, $data_added){
$id = $this->input->post('adminID'); // I believe you should be getting the id from the database/session honestly, much safer in these cases
$data = array(
'username'=> $username,
'password'=> $password,
'date_added'=> $data_added
);
$this->db->where('adminID', $id);
$this->db->update('admin', $data);
}
Hope this helps!
You are passing 3 parameters to your update_superuser() function here
$this->Superuser_Model->update_superuser($username,$password,$date_added);
and your function in your model only takes 2 params:
function update_superuser($data, $id){
$this->uri->segment(3);
$id = $this->input->post('adminID');
$data = array(
'username'=> $this->input->post('username'),
'password'=> $this->input->post('password'),
'date_added'=> $this->input->post('date_added')
);
$this->db->where('adminID', $id);
$this->db->update('admin', $data);
}