Pass Value From Controller to Model CodeIginter Using Stored Procedure - php

I have a problem with Codeigniter. I try to pass value from view to controller and it works. But there is a problem when it passing from controller to model. It didn't return any value into View.
Here is my controller:
public function Edit2G() {
$id = $this->uri->segment(3);
$this->load->model("main_model");
$data['fetch_data_2G_where'] = $this->main_model->fetch_data_2G_id($id);
$data['id'] = $id;
$data['title'] = "Update Data 2G";
$this->load->view('templates/header');
$this->load->view("pages/Update2G", $data);
$this->load->view('templates/footer');
}
Here is Model
function fetch_data_2G_id($id)
{
$get_2G_data_stored_proc = "CALL Get_2G_Data(?)";
$data = array( 'id' =>$id);
$query = $this->db->query($get_2G_data_stored_proc, $data);
$result = $query->result_array();
return $get_2G_data_stored_proc;
}
And this is my View
<h2 align="center"><?=$title ?></h2>
<h3 align="center"><?=$id ?></h3>
<p align="center"><?php echo $fetch_data_2G_where['id'];?></p> //This is a test
<?php echo form_open('posts/update'); ?>
<input type="hidden" name="id" value="<?php //echo $fetch_data_2G_where['id']; ?>">
<div class="form-group">
<label>Site ID</label>
<input type="text" class="form-control" name="title" placeholder="add title" value="<?php //echo $fetch_data_2G_where['site_name'];?>">
</div>
This is the stored procedure result
id, id_site, site_name, bsc_name, bcf_id, vlan1, vlan2, status,status_vlan
'1', 'COK008', 'Combat Batylon754','FBTIMIKA-1','BCF-0112', '3677', '3137', '', 'Metro E'
This in Error That I got
A PHP Error was encountered Severity: Warning
Message: Illegal string offset 'id'
Filename: pages/Update2G.php
Line Number: 3
Backtrace:
File: C:\xampp\htdocs\DapotTimika\application\views\pages\Update2G.php
Line: 3 Function: _error_handler
File: C:\xampp\htdocs\DapotTimika\application\controllers\Pages.php
Line: 46 Function: view
File: C:\xampp\htdocs\DapotTimika\index.php Line: 315 Function:
require_once
What I am missing?
PS: the stored procedure only has one parameter (id) to return / get data

in your controller print_r the below line
$data['fetch_data_2G_where'] = $this->main_model->fetch_data_2G_id($id);
echo "<pre>"; print_r($data['fetch_data_2G_where']);
just to see what's the result your query returning. then from your result you can analyse and get the desired results in view.

Thank You Guys for the answer, I found the answer.
I Forgot to parse return value from model into array. The code in model and controller is fine.
here is my view code
<?php
if($fetch_data_2G_where->num_rows() > 0)
{
foreach($fetch_data_2G_where->result_array() as $data)
{
?>
<input type="hidden" name="id" value="<?php echo $data['id']; ?>">
<div class="form-group">
<label>Site ID</label>
<input type="text" class="form-control" name="site_id" value="<?php echo $data['id_site'];?>">
<?php } ?>
Here is the Result

Related

Trying to make a search bar with a MINI PHP MVC

I am trying to make a search bar for my application.
I am using the following Mini Framework: https://github.com/panique/mini
What I want to do is have an input field where you type an username, and then a table is displayed underneath with all the information from the Database.
Environment:
PHP 7.4
Apache
CentOS 8
SQL Server 2019
My problem is, I don't know how to pass the input value to the controller and then to the model.
Let me show you what I have tried:
Account Model:
public function getUser($name)
{
$sql = "SELECT * FROM dbo.user_table WHERE Name = :name ORDER BY UserID DESC";
$query = $this->db->prepare($sql);
$query->execute(array(':name' => $name));
return $query->fetchAll();
}
Account Controller:
/**
* ACTION: getUser
*/
public function getUser()
{
if(isset($_POST['search_user'])) {
$checkUser = $this->model->getUser($_POST['username']);
}
}
My View:
<form action="<?php echo URL; ?>account/getUser" method="POST" class="mb20">
<div class="row">
<div class="input-wrap col-sm-12">
<input type="text" placeholder="Type username" name="username" autocomplete="off" />
</div>
</div></br>
<input type="submit" value="Search" name="search_user" />
</form>
I am not sure how to echo the result in the view. Maybe someone here could guide me in the correct direction.
Thanks!
Account Controller:
/**
* ACTION: getUser
*/
public function search()
{
if(isset($_POST['search_user'])) {
$checkUser = $this->model->getUser($_POST['username']);
}
require APP . 'view/search/index.php'; // your search view path
}
Search View:
<form action="<?php echo URL; ?>search" method="POST" class="mb20">
<div class="row">
<div class="input-wrap col-sm-12">
<input type="text" placeholder="Type username" name="username" autocomplete="off" />
</div>
</div></br>
<input type="submit" value="Search" name="search_user" />
</form>
<?php
if (isset($checkUser)) {
echo '<ul>';
foreach ($checkUser as $key => $value) {
echo '<li>';
echo $value->name;
echo '</li>';
}
echo '</ul>';
}
In this way, if there's the $_POST['search_user'], the function search will perform the search and put the result on the $checkUser variable. The variable will be still present on the View because you're requiring it after the $checkUser declaration. Then, the View checks if the variable is present and displays the results.
IMPORTANT
The line echo $value->name; is a dangerous behavior, because it can allow XSS, so, before rendering anything from the database, remember to escape it properly. Some ways to do it:
How to prevent XSS with HTML/PHP?
https://www.php.net/manual/pt_BR/function.strip-tags.php

database error: A PHP Error was encountered in codeigniter 3

My model:
class Admin_model extends CI_Model{
function add_blog($data){
$this->db->insert('blog',$data);
return true;
}
}
My controller function:
function add_blog(){
$this->form_validation->set_rules('heading','Heading', 'trim|required');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error',"Please check the required field");
redirect('admin/dashboard/add');
}else{
//for upload file
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'pdf|doc|docx|txt|jpeg|png|ppt';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$image_path = base_url("uploads/".$post['raw_name'].$post['file_ext']);
$data['picture'] = $image_path;
$data_image = array('upload_data' => $this->upload->data());
}
//Upload file end
$data['picture'] = $data_image['upload_data']['file_name'];
$data['heading'] = ucwords($this->input->post('heading'));
$data['description'] = ucfirst($this->input->post('description'));
$data['type_id'] = ucwords($this->input->post('type_id'));
$data['price'] = $this->input->post('price');
$insert_data = $this->admin_model->add_blog($data);
if($insert_data){
echo '<script>alert("Note added sucessfully.");</script>';
redirect('admin/dashboard');
}else{
$this->session->set_flashdata('message',"There is problem in inserting data, please retry once");
echo "error at last ";
redirect('admin/dashboard/add');
}
}
}
My view:
<form role="form" name="myForm" method="post" enctype="multipart/form-data" action="<?php echo site_url('admin/dashboard/add_blog');?>">
<label for="">Category</label>
<select name="type_id" id="" class="form-control" >
<?php
if(count($product_list )>0 ){
foreach ($product_list as $key => $value) {
?>
<option value="<?php echo $value['type_id'];?>"><?php echo $value['type'];?></option>
<?php
}}?>
</select>
<label for=""> Heading </label>
<input type="text" name="heading"class="form-control">
<label for="">Price</label>
<input type="number" name="price" class="form-control">
<label for="">Description</label>
<textarea name="description" id="" cols="30" rows="5" class="form-control"></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">Upload pic</label>
<div class="input-group">
<div class="custom-file">
<!-- <input type="file" name="userfile" class="form-control"> -->
<?php echo form_upload(['name'=>'userfile']); ?>
</div>
</div>
<?php if(isset($upload_error)){echo $upload_error;}?>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data_image
Filename: admin/Dashboard.php
Line Number: 64
Backtrace:
File:
/opt/lampp/htdocs/shremad/application/controllers/admin/Dashboard.php
Line: 64 Function: _error_handler
File: /opt/lampp/htdocs/shremad/index.php Line: 315 Function:
require_once
A PHP Error was encountered
Severity: Notice
Message: Trying to access array offset on value of type null
Filename: admin/Dashboard.php
Line Number: 64
Backtrace:
File:
/opt/lampp/htdocs/shremad/application/controllers/admin/Dashboard.php
Line: 64 Function: _error_handler
File: /opt/lampp/htdocs/shremad/index.php Line: 315 Function:
require_once
A Database Error Occurred
Error Number: 1048
Column 'picture' cannot be null
INSERT INTO blog (picture, heading, description, type_id,
price) VALUES (NULL, 'Djjdjdj', 'Jjdjdj', '1', '')
Filename: models/Admin_model.php
Line Number: 5
Let's analyze the error message first.
Message: Undefined variable: data_image
Which means, somewhere in the code you're calling a variable named "data_image" which is undefined. Now, please notice that this is a NOTICE, so there might be cases that your code would work well BUT it's a bad practice and might cause troubles. (As in your case for instance).
Looking at your code, the following "block":
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$image_path = base_url("uploads/".$post['raw_name'].$post['file_ext']);
$data['picture'] = $image_path;
$data_image = array('upload_data' => $this->upload->data());
}
//Upload file end
$data['picture'] = $data_image['upload_data']['file_name'];
The $data_image variable is defined only under the "else" statement.
So if the condition returns true, the $data_image variable is truly undefined.
In that case, the following command:
$data['picture'] = $data_image['upload_data']['file_name'];
which is based on the $data_image variable, would return another problem:
Message: Trying to access array offset on value of type null
so $data['picture'] now is NULL, which cause your last problem:
Column 'picture' cannot be null
The solution?
Make sure you have a value for $data_image even in the case that the condition returns true. Or, if this condition returns true - handle the things differently. Please also notice that there might be a logical problem with the function in the condition that returns an unexpected result.
(The condition: if ( ! $this->upload->do_upload()))

How insert multiple data using array

I'm a newbie using php CodeIgniter. I can insert the array using php native. but how I can insert array using CodeIgniter, please? help me
I have a program for many checkboxes. if I checked more than 1 or checked all it's just still insert 1 data. its said success but just 1 data. so I want to insert more than 1. how can I do that's code? please fix it
this is my function order code from the controller :
public function order()
{
$this->form_validation->set_rules('id_sub', 'Id_sub', 'required|trim');
if ($this->form_validation->run() == false) {
$data['title'] = 'Order';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
$data["home"] = $this->product_model->getAll_join();
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar', $data);
$this->load->view('templates/topbar', $data);
$this->load->view('user/order', $data);
$this->load->view('templates/footer');
} else {
$data = [
'id_sub' => htmlspecialchars($this->input->post('id_sub', true))
];
$this->db->insert('tbl_order_detail', $data);
$this->session->set_flashdata('message', '<div class="alert alert-success" role="alert">Data berhasil disimpan.
</div>');
redirect('user/order');
}
}
this is my view order code :
<tbody>
<tr>
<td>
<?php
$query = $this->db->query("select tbl_referensi.referensi, tbl_sub_kategori.sub, tbl_sub_kategori.id_sub
from tbl_referensi
inner join tbl_sub_kategori
on tbl_referensi.id_ref = tbl_sub_kategori.id_ref
where tbl_referensi.id_ref = $tampil->id_ref;
");
foreach ($query->result() as $tampil_sub) :
?>
<input type="checkbox" aria-label="Checkbox for following text input" name="id_sub" id="id_sub" value="<?= $tampil_sub->id_sub ?>"> <label for="name" class="mr-4"><?= $tampil_sub->sub ?></label>
<?php endforeach; ?>
</td>
</tr>
</tbody>
i think the problem is from function order and tag HTML(name="id_sub") from view order. maybe using id_sub[].
but how? please fix it and help me.
Use this
<input type="checkbox" aria-label="Checkbox for following text input" name="id_sub[]" id="id_sub" value="<?= $tampil_sub->id_sub ?>"> <label for="name" class="mr-4"><?= $tampil_sub->sub ?></label>
and you will get value in controller using
$post_data = $this->input->post('id_sub');
foreach ($post_data as $key=>$value) {
// do your code
}
Here in html, input name should be an array
<input type="checkbox" aria-label="Checkbox for following text input" name="id_sub[]" id="id_sub" value="<?= $tampil_sub->id_sub ?>"> <label for="name" class="mr-4"><?= $tampil_sub->sub ?>
Mysql Query:
$data = [
'id_sub' => implode(',',$this->input->post('id_sub'))
];
$this->db->insert('tbl_order_detail',$data);

Update a database record using codeigniter

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

CodeIgniter: Populate an input text in the view from data array grabbed from database

This return of print_r($query->result()); would be:
Array ( [0] => stdClass Object ( [guest_name] => Test Name [guest_gender] => Male [guest_nic_pp_dl] => 123456789 ) )
What I need is to pass those values into input text boxes, radio buttons and dropdowns in the view respectilvely.
For example, I need 'guest_name' to be in an input, 'guest_gender' value to be selected on the view, and dropdown value corresponding to 'guest_nic_pp_dl' to be selected on a dropdown (HTML select).
Controller:
function get_customer_details() {
$guest_name = $this->input->post('guest_name');
$this->banquet_model->talk_to_new_guest_table($guest_name);
$this->load->view('/main/banquet_view');
}
Model:
function talk_to_new_guest_table($guest_name) {
$query = $this->db->query(" SELECT guest_name, guest_gender, guest_nic_pp_dl
FROM new_guest
WHERE guest_name LIKE '$guest_name%'
LIMIT 1 ");
if($query->num_rows()>0) {
return $query->result();
}
else {
return 0;
}
}
View:
<div class="control-group">
<label for="guest_name" class="control-label"><i class="icon-user"></i> Name: </label>
<div class="controls">
<div class="input-append">
<input type="text" id="appendedInputButtons" class="span2" name="guest_name" value="<?php echo set_value('guest_name'); ?>">
<input class="btn" type="submit" name="searchGuest" value="Search">
</div>
<?php echo form_error('guest_name'); ?>
</div>
make some changes in
Controller :
$guest=$this->banquet_model->talk_to_new_guest_table($guest_name);
//creating data array from returned result
$data['guest_name']=$guest->guest_name;
$data['guest_gender']=$guest->guest_gender;
$data['guest_nic_pp_dl']=$guest->guest_nic_pp_dl;
//loading view with data
$this->load->view('/main/banquet_view',$data);
more important all these data array element will be available as variable on view page like
$data['guest_gender'] as $guest_gender
The answers from Rajeev Ranjan and Prasanth are ok but on the line return $query->result(); you can do thisreturn $query->row(); the reason is because the result() returns an array of objects which needs to be iterated while the row() object returns a single object which you can reference without iterating with a loop. I hope this will help
Try something on the lines of:
Controller:
function get_customer_details() {
$guest_name = $this->input->post('guest_name');
$data = $this->banquet_model->talk_to_new_guest_table($guest_name);
if ($data != 0) {
$this->load->view('/main/banquet_view', $data);
}
}
Model:
function talk_to_new_guest_table($guest_name) {
$query = $this->db->query(" SELECT guest_name, guest_gender, guest_nic_pp_dl
FROM new_guest
WHERE guest_name LIKE '$guest_name%'
LIMIT 1 ");
if($query->num_rows()>0) {
return $query->result();
}
else {
return 0;
}
}
View:
<div class="control-group">
<label for="guest_name" class="control-label"><i class="icon-user"></i> Name: </label>
<div class="controls">
<div class="input-append">
<input type="text" id="appendedInputButtons" class="span2" name="guest_name" value="<?php echo $guest_name; ?>">
<input class="btn" type="submit" name="searchGuest" value="Search">
</div>
<?php echo form_error('guest_name'); ?>
</div>

Categories