Dynamic Select Dropdowns with CodeIgniter - codeigniter

I'm using CodeIgniter to develop a web application and wondered if anyone could help with a problem that has arose.
I have two dropdowns - Division and Teams. I'm creating a fixture so want to be able to allow the user to choose a division from the first dropdown, then within the second dropdown will only contain the teams from the selected division.
The Code I have so far:
Controller:
function create() {
$data['division_list'] = $this->add_fixture_model->get_divisions();
$data['team_list'] = $this->add_fixture_model->get_teams();
$data['referee_list'] = $this->add_fixture_model->get_referee();
// field name, error message, validation rules
$this->form_validation->set_rules('team_name', 'Team Name', 'trim|required');
$this->form_validation->set_rules('home_team', 'Home Team Name', 'trim|required');
$this->form_validation->set_rules('away_team', 'Away Team Name', 'required');
$this->form_validation->set_rules('division_name', 'Division', 'trim|required');
$this->form_validation->set_rules('referee', 'Referee', 'trim|required');
$this->form_validation->set_rules('fixture_week', 'Fixture Week', 'trim|required');
$this->form_validation->set_rules('fixture_day', 'Fixture Day', 'trim|required');
$this->form_validation->set_rules('fixture_month', 'Fixture Month', 'trim|required');
$this->form_validation->set_rules('fixture_year', 'Fixture Year', 'trim|required');
$this->form_validation->set_rules('confirm_day', 'Fixture Confirm Day', 'trim|required');
$this->form_validation->set_rules('confirm_month', 'Fixture Confirm Month', 'trim|required');
$this->form_validation->set_rules('confirm_year', 'Fixture Confirm Year', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('includes/top');
$this->load->view('includes/header');
$this->load->view('league/add_fixture', $data);
$this->load->view('includes/footer');
}
else
{
if($query = $this->add_fixture_model->add_fixture())
{
$this->load->view('includes/top');
$this->load->view('includes/header');
$this->load->view('league/fixture_added');
$this->load->view('includes/footer');
}
else
{
$this->load->view('includes/top');
$this->load->view('includes/header');
$this->load->view('league/fixture_added', $data);
$this->load->view('includes/footer');
}
}
}
Model:
class Add_fixture_model extends Model {
function add_fixture()
{
$add_new_fixture = array(
'team_name' => $this->input->post('team_name'),
'home_team' => $this->input->post('home_team'),
'away_team' => $this->input->post('away_team'),
'division' => $this->input->post('division_name'),
'ground' => $this->input->post('ground'),
'ground_postcode' => $this->input->post('ground_postcode'),
'referee' => $this->input->post('referee'),
'fixture_week' => $this->input->post('fixture_week'),
'fixture_day' => $this->input->post('fixture_day'),
'fixture_month' => $this->input->post('fixture_month'),
'fixture_year' => $this->input->post('fixture_year'),
'confirm_day' => $this->input->post('confirm_day'),
'confirm_month' => $this->input->post('confirm_month'),
'confirm_year' => $this->input->post('confirm_year')
);
$insert = $this->db->insert('fixtures', $add_new_fixture);
return $insert;
}
function get_divisions()
{
$this->db->from('divisions');
$this->db->order_by('division_name');
$result = $this->db->get();
$return = array();
if($result->num_rows() > 0) {
foreach($result->result_array() as $row) {
$return[''] = 'Select a division';
$return[$row['id']] = $row['division_name'];
}
}
return $return;
}
function get_teams()
{
$this->db->from('teams');
$this->db->order_by('team_name');
$result = $this->db->get();
$return = array();
if($result->num_rows() > 0) {
foreach($result->result_array() as $row) {
$return[''] = 'Select a team';
$return[$row['id']] = $row['team_name'];
}
}
return $return;
}
function list_teams() {
$this->db->from('teams');
$this->db->where('division_id', $this->input->post('id'));
$this->db->order_by('team_name');
$result = $this->db->get();
return $result;
}
function get_referee() {
$this->db->from('referees');
$this->db->order_by('id');
$result = $this->db->get();
$return = array();
if($result->num_rows() > 0) {
foreach($result->result_array() as $row) {
$return[''] = 'Select a referee';
$return[$row['id']] = $row['first_name'].' '.$row['surname'];
}
}
return $return;
}
}
View:
<?php echo form_open('add_fixture/create') ;?>
<label for="division" class="label">Division:</label><?php $js = 'id="division"'; echo form_dropdown('division', $division_list, set_value('division'), $js); ?>
JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$('select#division').change(function() {
var div = $(this).val();
if(div != '') {
$.post("/add_fixture/list_teams/",{division_id: div}, function(data){
$("select#team_name").html(data);
});
}
});
});
</script>
Any help would very much be appreciated :)

Related

Laravel 7: Full Calendar not showing events

Please see my code first:
Controller:
public function getHolidays($days, $start_date) {
$date = date('Y-m-d',strtotime($start_date));
$i = 0;
$response = array();
while ($i <= 42) {
$tsDate = strtotime($date. ' ' .'+ '.$i.' days');
$day = date('D', $tsDate);
if(in_array($day, $days)) {
$data = array();
$data['title'] = 'Weekend';
$data['start'] = date('Y-m-d',$tsDate);
$data['end'] = date('Y-m-d',$tsDate);
$response[] = $data;
}
$i++;
}
return $response;
}
public function index(request $request){
if($request->ajax()) {
$weekends = DB::table('working_days')
->where('status', 0)
->get(['day'])
->map(function($item) {
return $item->day;
})->toArray();
$holidays = DB::table('holidays')
->get()
->map(function($item) {
return [
'title' => 'Holiday',
'start' => Carbon::parse($item->date)->format('Y-m-d'),
'end' => Carbon::parse($item->date)->format('Y-m-d'),
];
})->toArray();
$attendances = DB::table('attendances as a')
// ->where('leave_cat_id', '!=', null)
->where('user_id', Auth::user()->id)
->get()
->map(function($item) {
return [
'title' => 'Leave',
'start' => Carbon::parse($item->date)->format('Y-m-d'),
'end' => Carbon::parse($item->date)->format('Y-m-d'),
'color' => 'red',
];
})->toArray();
$data = [...$this->getHolidays($weekends, $request->start), ...$holidays, ...$attendances];
return response()->json($data);
}
return view('admin.dashboard');
}
Blade File script:
<script>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var calendar = $('#full-calendar').fullCalendar({
editable: true,
editable: true,
events: '/dashboard',
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
});
});
</script>
Tables:
attendances
id
user_id
date
status
leave_cat_id
1
2
2022-07-13
1
null
2
2
2022-07-12
0
1
holidays
id
date
1
2022-07-13
2
2022-07-20
working_days
id
day
working_status
1
Fri
0
2
Sat
1
3
Sun
1
I want to show attendances on Full Calendar [https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.10.2/fullcalendar.min.js]
First, weekly holiday will show when the working_status = 0 and day is matched with calendar.
Second, holidays will show when it will match the dates with calendar date
Third, attendance will show on other days. If the status is 1 it will show present and if 0 it will show absent. Also, if the leave_cat_id column is not equal to null, then it will show On leave, others it will show the attendance status.
Can you please modify my code for this?
Thanks
public function getHolidays($days, $start_date) {
$date = date('Y-m-d',strtotime($start_date));
$i = 0;
$response = array();
while ($i <= 42) {
$tsDate = strtotime($date. ' ' .'+ '.$i.' days');
$day = date('D', $tsDate);
if(in_array($day, $days)) {
$data = array();
$data['title'] = 'Weekend';
$data['start'] = date('Y-m-d',$tsDate);
$data['end'] = date('Y-m-d',$tsDate);
$response[] = $data;
}
$i++;
}
return $response;
}
public function index(request $request){
if($request->ajax()) {
$weekends = DB::table('working_days')
->where('working_status''status', 0)
->get(['day'])
->map(function($item) {
return $item->day;
})->toArray();
$holiday$holidays = DB::table('holidays')
->get()
->map(function($item) {
return [
'title' => 'Holiday',
'start' => Carbon::parse($item->date)->format('Y-m-d'),
'end' => Carbon::parse($item->date)->format('Y-m-d'),
];
})->toArray();
$attendances = DB::table('attendances''attendances as a')
// ->where('leave_cat_id', '!=', null)
->where('user_id', Auth::user()->id)
->get()
->map(function($item) {
return [
'title' => $item->leave_cat_id ? 'Leave' : ($item->attendance_status == 1 ? 'Present' : 'Absent'),
'start' => Carbon::parse($item->attendance_date>date)->format('Y-m-d'),
'end' => Carbon::parse($item->attendance_date>date)->format('Y-m-d'),
'color' => $item->attendance_status == 1 ? 'green' : 'red',
];
})->toArray();
$data = [...$this->getHolidays($weekends, $request->start), ...$holiday$holidays, ...$attendances];
return response()->json($data);
}
return view('admin.dashboard');
}
<script type="text/javascript"><script>
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var calendar = $('#full-calendar').fullCalendar({
editable: true,
editable: true,
events: '/dashboard',
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
});
});
</script>

How to get/view images dynamically in homepage using CodeIgniter?

image
New_model
=========
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class New_model extends CI_Model
{
private $_table = "news";
public $title;
public $date;
public $description;
public $image = "default.jpg";
public $url;
public function rules()
{
return [
['field' => 'title',
'label' => 'Title',
'rules' => 'required'],
['field' => 'date',
'label' => 'Date',],
// 'rules' => 'required'],
['field' => 'description',
'label' => 'Description',
'rules' => 'required']
];
}
public function getAll()
{
return $this->db->get($this->_table)->result();
}
public function getById($id)
{
return $this->db->get_where($this->_table, ["new_id" => $id])->row();
}
public function save()
{
$post = $this->input->post();
// $this->new_id = uniqid();
$this->title = $post["title"];
$this->date = $post["date"];
$this->description = $post["description"];
$this->image = $this->_uploadImage();
$this->db->insert($this->_table, $this);
// $this->url = base_url() . 'uploads/';
$post['url'] = base_url() . 'uploads/';
}
public function update()
{
$post = $this->input->post();
$this->new_id = $post["id"];
$this->title = $post["title"];
$this->date = $post["date"];
$this->description = $post["description"];
if (!empty($_FILES["image"]["name"])) {
$this->image = $this->_uploadImage();
} else {
$this->image = $post["old_image"];
}
$this->db->update($this->_table, $this, array('new_id' => $post['id']));
}
public function delete($id)
{
$this->_deleteImage($id);
return $this->db->delete($this->_table, array("new_id" => $id));
}
private function _uploadImage()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
// $config['file_name'] = $this->new_id;
$config['overwrite'] = true;
$config['max_size'] = 1024; // 1MB
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
return $this->upload->data("file_name");
}
return "default.jpg";
}
private function _deleteImage($id)
{
$new = $this->getById($id);
if ($new->image != "default.jpg") {
$filename = explode(".", $new->image)[0];
return array_map('unlink', glob(FCPATH."uploads/$filename.*"));
}
}
}
public function single($id)
{
$data['news'] = $this->New_model->where('new_id',$id)->order_by('new_id','desc')->get_all();
$data['news1'] = $this->New_model->limit(5)->order_by('id','desc')->get_all();
$this->current = 'news';
$this->load->view(['current' => $this->current]);
$this->load->view('news',$data);
}
Controller
==========
public function index()
{
$data["news"] = $this->New_model->getAll();
$this->load->view('index',$data);
}
public function latestnews()
{
$data['news'] = $this->New_model->where('new_id',$id)->order_by('new_id','desc')->get_all();
$this->load->view('news',$data);
}
view
====
<?php
if (isset($news) and $news) {
foreach ($news as $new) {
?>
<div class="tile-primary-content">
<img src="<?php echo $new->url . $new->image;?>" alt="image" />
</div>
<div class="tile-secondary-content">
<div class="section-title-1">
<span class="title"><?php echo $new->title;?></span>
</div>
<h2 class="heading-20"><?php echo $new->date;?></h2>
</div>
<?php
}
}
?>
I'm trying to upload an image in the dashboard with a title and date along with the image upload.
How to display that image on the homepage?
How to set the URL in the New_model?
How to set the links to display the images in the homepage?
How to set the date links?
The title field can be viewed in the homepage, but no image and dateā€¦
Try this code.
Controller: (Edited)
function index() {
$this->data["news"] = $this->new_model->getAll();
$this->load->view('index', $this->data);
}
function single_news($id) {
$this->data['news_data'] = $this->new_model->getNewsByID($id);
$this->load->view('single-news', $this->data); // Create New View file named single-news.php
}
function add_news() {
$image_status = FALSE;
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == TRUE) {
$image_name = NULL;
if ($_FILES['image']['size'] > 0) {
$this->load->library('upload');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if( ! $this->upload->do_upload('image')){
$this->data['error'] = $this->upload->display_errors();
}
$image_name = $this->upload->file_name;
$image_status = TRUE;
}
$data = array(
'title' => $this->input->post('title'),
'date' => $this->input->post('date')?date('Y-m-d', strtotime($this->input->post('date'))):NULL,
'description' => $this->input->post('description'),
'image' => $image_name
);
}
if($this->form_validation->run() == TRUE && $image_status && $this->new_model->addNews($data)) {
$this->session->set_flashdata('message', 'News has been created successfully.');
redirect('index');
} else {
$this->data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
$this->data['page_title'] = 'Add News';
$this->load->view('add_news', $this->data);
}
}
When adding new News you don't need to add the uploaded location (Not necessary).
Model: (Edited)
function getAll() {
$q = $this->db->get('news');
if($q->num_rows() > 0) {
foreach($q->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
function getNewsByID($id) {
$this->db->where('id', $id);
$q = $this->db->get('news');
if($q->num_rows() > 0) {
return $q->row();
}
return false;
}
function addNews($data) {
if($this->db->insert('news', $data)){
return true;
}
return false;
}
View: (Edited)
<?php
if ($news) {
foreach ($news as $new) {
?>
<div class="tile-primary-content">
<a href="<?php echo base_url('single_news/'.$new->id); ?>"
<img src="<?php echo site_url('uploads/'.$new->image); ?>" alt="image" />
</a>
</div>
<div class="tile-secondary-content">
<div class="section-title-1">
<span class="title"><?php echo $new->title;?></span>
</div>
<h2 class="heading-20"><?php echo !is_null($new->date)?date('d.m.Y', strtotime($new->date)):' - ';?></h2>
</div>
<?php
}
}
?>
single-news.php: (View)
...
<img src="<?php echo site_url('uploads/'.$news_data->image); ?>" />
...

error column 'picture' cannot be null

My initial question was posted wrong so i'm reposting it. I am practicing with a tutorial on tutsplus by joost van veen and i added an image upload to the controller but every time i try to save a post i get an error from database saying column 'picture' cannot be null. I've checked other answers but nothing explains the problem. Any help would be appreciated.
MY CONTROLLER
public function edit($post_id = NULL) {
// Fetch all articles or set a new one
if ($post_id) {
$this->data['article'] = $this->article_m->get($post_id);
count($this->data['article']) || $this->data['errors'][] = 'article could not be found';
}
else {
$this->data['article'] = $this->article_m->get_new();
}
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
if ($this->input->post('userSubmit')) {
//check if user uploads picture
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['file_name'] = $_FILES['picture']['name'];
//load upload library and initialize configuration
$this->upload->initialize($config);
if ($this->upload->do_upload('picture')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
} else {
$picture = '';
}
// prepare array of posts data
$data = $this->article_m->array_from_post(array(
'title',
'slug',
'content',
'category_id',
'picture',
'pubdate'
));
$insertPosts = $this->article_m->save($data, $post_id);
redirect('admin/article');
//storing insertion status message
if ($insertPosts) {
$this->session->set_flashdata('success_msg', 'Post has been added Successfully.');
} else {
$this->session->set_flashdata('error_msg', 'error occured while trying upload, please try again.');
}
}
// Load view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/components/page_head', $this->data);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/components/page_tail');
}
MY_MODEL
public function array_from_post($fields) {
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
}
return $data;
}
public function save($data, $id = NULL) {
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
RULES TO SET FORM VALIDATION
public $rules = array(
'pubdate' => array(
'field' => 'pubdate',
'label' => 'Publication date',
'rules' => 'trim|required|exact_length[10]'
),
'title' => array(
'field' => 'title',
'label' => 'Title',
'rules' => 'trim|required|max_length[100]'
),
'slug' => array(
'field' => 'slug',
'label' => 'Slug',
'rules' => 'trim|required|max_length[100]|url_title'
),
'content' => array(
'field' => 'content',
'label' => 'Content',
'rules' => 'trim|required'
),
'picture' => array(
'field' => 'picture',
'label' => 'Upload File',
'rules' => 'trim'
),
);
public function get_new() {
$article = new stdClass();
$article->title = '';
$article->category_id = '';
$article->slug = '';
$article->content = '';
$article->picture = '';
$article->pubdate = date('Y-m-d');
return $article;
}
I fixed the problem by creating a new method array_me() in the model and calling it in the controller.
NEW METHOD IN MY_MODEL
public function array_me($fields) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
$data['category_id'] = $this->input->post('category');
$data['picture'] = $picture;
}
return $data;
}
EDITED CONTROLLER
public function edit($post_id = NULL) {
// Fetch all articles or set a new one
if ($post_id) {
$this->data['article'] = $this->article_m->get($post_id);
count($this->data['article']) || $this->data['errors'][] = 'article could not be found';
}
else {
$this->data['article'] = $this->article_m->get_new();
}
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
if ($this->input->post('userSubmit')) {
//check if user uploads picture
if (!empty($_FILES['picture']['name'])) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['file_name'] = $_FILES['picture']['name'];
//load upload library and initialize configuration
$this->upload->initialize($config);
if ($this->upload->do_upload('picture')) {
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
} else {
$picture = '';
}
} else {
$picture = '';
}
// prepare array of posts data
$data = $this->article_m->array_me(array(
'title',
'slug',
'content',
'category_id',
'picture',
'pubdate'
));
$insertPosts = $this->article_m->save($data, $post_id);
redirect('admin/article');
//storing insertion status message
if ($insertPosts) {
$this->session->set_flashdata('success_msg', 'Post has been added Successfully.');
} else {
$this->session->set_flashdata('error_msg', 'error occured while trying upload, please try again.');
}
}
// Load view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/components/page_head', $this->data);
$this->load->view('admin/_layout_main', $this->data);
$this->load->view('admin/components/page_tail');
}

How can i display error messages in CodeIgniter

Controller:
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id)) {
$this->form_validation->set_rules('year_name', 'Year Name', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Add Year',
'page_name' => 'year/add_year',
'admin_username' => $this->session->userdata('username')
);
$this->load->view('admin/template', $data);
} else {
$this->year_model->insert($_POST);
redirect('admin/Year');
}
} else {
redirect('admin/Login');
}
}
Model:
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
} else {
$error = "Year Name Already Exits";
return $error;
}
}
View:
<div class="text-danger">
//display error message
</div>
MY Question: How can i display model error message in view............................................................
use below updated code for your solution
Model :
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
} else {
$error = "Year Name Already Exits";
return $error;
}
return TRUE;
}
add_year
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id)) {
$this->form_validation->set_rules('year_name', 'Year Name', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Add Year',
'page_name' => 'year/add_year',
'admin_username' => $this->session->userdata('username')
);
$this->load->view('admin/template', $data);
} else {
$ret = $this->year_model->insert($_POST);
if(!$ret){
$this->session->set_flashdata('error_view',$ret);
}
redirect('admin/Year');
}
} else {
redirect('admin/Login');
}
}
in view
<?php
echo $this->session->flashdata('error_view');
?>
Use this Code
Note : please set your table and field name in is_unique function !
Controller:
public function add_year() {
$session_id = $this->session->userdata('id');
if (!empty($session_id))
{
$this->form_validation->set_rules('year_name', 'Year Name', 'required|is_unique[table_name.field_name]');
if ($this->form_validation->run() == FALSE) {
$res['error']='<div class="alert alert-danger">'.validation_errors().'</div>';
}
else {
if( $this->year_model->insert($_POST)==true)
{
redirect('admin/Year');
}
}
} else
{
redirect('admin/Login');
}
}
Model
public function insert($data) {
$result = $this->db->get_where('year', array('year_name' => $data['year_name']))->row_array();
if (empty($result)) {
$insert_data = array('year_name' => $data['year_name']);
$this->db->insert('year', $insert_data);
return true;
} else {
return false;
}
}
View File
<div class="panel-body">
<?php if(validation_errors()) { ?>
<div class="alert alert-danger"><?php echo validation_errors(); ?></div>
<?php } ?>

codeinighter where field = data from form

I'm trying to match up suppliers from a postcode search:
Model code:
function get_suppliers(){
$this->db->from('suppliers');
$this->db->where('postcode', $data);
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0) {
foreach($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
Controller code:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
echo("postcode entered");
$data['rows'] = $this->site_model->get_suppliers($data);
print_r($data);
}
}
Obviously ignore the printers and echo thats just me bring to see whats going on I'm pretty sure i need to just change the $data in model to something just not sure what(tried heaps of things)
Model:
function get_suppliers($postcode = '*') // <-- Capture the postcode
{
$this->db->from('suppliers');
$this->db->where('postcode', $postcode); // <-- pass it in here
$this->db->select('name,type,site,contact,number');
$q = $this->db->get();
if($q->num_rows() > 0)
{
foreach($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Controller:
public function index()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('postcode','Postcode', 'required|numeric|exact_length[4]');
$data = array(
'postcode' => $this->input->post('postcode')
);
if($this->form_validation->run() == FALSE)
{
## reload page ##
$this->load->view('welcome_message');
}
else
{
$this->load->model('site_model');
$this->site_model->add_record($data);
$data['rows'] = $this->site_model->get_suppliers( $data['postcode'] ); // <-- pass the postcode
echo("postcode entered: " . $data['postcode'] . "<pre>");
print_r($data);
}
}
In your model:
function get_suppliers($data = ''){
i.e.: You haven't included $data as the argument

Resources