getting the id when the data is saved into the database using codeigniter - codeigniter

Hi i have this form when save, saved into the database. I want that when the data is saved into the database i will get the id on it then displaying it to the next page.
Here's my controller below in my function add_new
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Create_album extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('session');
$this->load->model('admin_model', 'am');
$this->load->library('form_validation');
if(!$this->session->userdata('logged_in')){
redirect('login');
}
}
public function detail($id){
return $id;
$this->data['item'] = $this->am->getItem($id);
print_r($this->data['item']);exit;
}
public function add_new(){
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'Create New Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'title'=>$this->input->post('title'),
'description'=>$this->input->post('description')
);
$this->am->saveAlbum($array);
$id = $this->db->id;
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
foreach($this->data['item'] as $item){
$itemId = $item->id;
}
return $itemId;
redirect('create_album/detail/id/'.$itemId);
}
}
public function index(){
$this->data['title'] = 'Create Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}
}
my model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Admin_model extends CI_Model{
public function getItem($id){
return $this->db->select('item.id,
item.parent_id,
item.title,
item.description,
item.filename
'
)
->from('item')
->where('item.id', $id)
->get()->result_object();
$this->db->get('item');
}
}
?>
Can someone help me figured this out? i want to get the ID when the data is saved. Any help is muchly appreciated. Thank you

Simply use this
$this->db->insert_id(); // Returns your row id.
Here how your controller should look like
public function add_new(){
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'Create New Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'title'=>$this->input->post('title'),
'description'=>$this->input->post('description')
);
$this->am->saveAlbum($array);
$id = $this->db->id;
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
foreach($this->data['item'] as $item){
$itemId = $item->id;
}
return $itemId;
redirect('create_album/detail/id/'.$this->db->insert_id()); // here?
}
}

Think you're probably looking for the insert_id() query helper function. You can see info about it in the Codeigniter docs.

When PHP hits return in a function it does just that, return a value, and it exits the function. Code following the return will not be executed. Read about it on the docs page
Example:
public function detail($id){
return $id;
echo 'here';
}
You will never get 'here' to echo, since you have already returned a value in your function().
Again this applies twice in your code, once here:
return $itemId;
redirect('create_album/detail/id/'.$this->db->insert_id());
and again here:
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
If you want the insert id you are going to have to return it from $this->am->saveAlbum(); Assign that to a variable and pass it to your redirect.
There are quite a few other issues, but that should help to get you started.

Related

Codeigniter: Display an image stored in DB

How do I get an image stored in a field of my database, and put it into a variable for using it in an email message like a signature?
Here is my code:
//Model user_model
function getImage(){
$this->db->select("image");
$this->db->where("$id", user_id);
$query = $this->db->get("users");
if($query->num_rows()>0){
return result();
}else{
return false;
}
}
//Controller user_controller
function image(){
this->load->model("user_model");
$id = $this->session->userdata('id');
$image = $this->user_model->getImage($id);
echo $image;
}
Here is a example
Model user_model
// Pass the id function
function getImage($id){
$this->db->where($id, 'user_id');
$query = $this->db->get("users");
if($query->num_rows()>0){
return $query->row_array();
}else{
return false;
}
}
Controller user_controller
function image(){
$this->load->model("user_model");
$somedata = $this->user_model->getImage($this->session->userdata('id'));
$data['image'] = $somedata['image'];
$this->load->view('someview', $data);
}
On view
<?php echo $image;?>

Get Username Matches ID

I have tried many ways of getting the username in codeigniter models. that matches the row id. But can not seem to get my model to work.
I have looked at user guide many times all ways get errors.
It shows the row id / user id OK when echo it
But can not seem to make a model to be able to match username with row id and then echo it.
Any suggestion on suitable model function.
when I click on my edit button it shows up in url http://localhost/codeigniter/codeigniter-blog/admin/users/edit/1 which works.
Model
// Not return username that matches id.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_user extends CI_Model {
function getUsername() {
$this->db->select('username');
$this->db->where('user_id');
$query = $this->db->get('user');
return $query->row();
}
}
Controller function.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('user');
if ($this->session->userdata('isLogged') == TRUE) {
return true;
} else {
redirect('/');
}
}
public function index() {
$data['title'] = "Users";
$data['base'] = config_item('HTTP_SERVER');
$data['isLogged'] = $this->user->isLogged();
$this->load->model('users/model_user');
$data['text_enabled'] = "Enabled";
$data['text_disabled'] = "Disabled";
$results = $this->model_user->getUsers();
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'edit' => site_url('users/edit/' . $result['user_id'])
);
}
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_list', $data);
}
function edit($user_id = 0, $user_group_id = 0) {
$data['title'] = "Users";
$data['base'] = config_item('HTTP_SERVER');
$data['isLogged'] = $this->user->isLogged();
$this->load->model('users/model_user');
$data['user_id'] = "Current User ID" . " " . $user_id . ":";
$data['user_group_id'] = "Current User Group ID" . " " . $user_group_id . ":";
$data['username'] = "Current User Name:" . " " . $this->model_user->getUsername();
$data['header'] = $this->load->view('template/common/header', $data, TRUE);
$data['footer'] = $this->load->view('template/common/footer', NULL, TRUE);
return $this->load->view('template/users/users_form', $data);
}
}
'where' requires a second argument, which you would pass as an argument to your model function. so something like this in the model
class Model_user extends CI_Model {
function getUsername($id) {
$this->db->select('username');
$this->db->where('user_id', $id);
$query = $this->db->get('user');
return $query->row();
}
}
this corresponds to an sql query like
SELECT username FROM user WHERE user_id = ?
so in the controller just pass the user id in the argument to the model function
$data['username'] = "Current User Name:" . " " . $this->model_user->getUsername($user_id);
I have found best way to get my username to match user id
On My Model
function getUsername($user_id) {
if (empty($user_id)) {
return FALSE;
}
$this->db->select('username');
$this->db->where('user_id', $user_id);
$query = $this->db->get('user');
if ($query->num_rows() == 1) {
$result = $query->result_array();
return $result[0]['username'];
} else {
return FALSE;
}
}
on Controller function
$this->model_user->getUsername($user_id);

Stacked in Pagination in Codeigniter

i'm new with CI and i tried a lot posibilities to make this run, but still it ain't working. Could you please tell me what i'm doing wrong?
So, Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('model_add','',TRUE);
}
public function _remap($a){
if (isset($a) && !empty($a)):
switch ($a) {
case 'index':
$this->index();
break;
default:
$this->one_news($a);
break;
}
endif;
}
public function index()
{
$this->load->library('pagination');
$home=$this->uri->segment(2);
$limit=2;
$offset=0;
$query=$this->model_add->count_news($limit,$offset);
$config['base_url'] = base_url().'/news/';
$config['total_rows'] = $this->db->count_all('tdt_news');
$config['per_page'] = 2;
$config['uri_segment'] = 2;
$this->pagination->initialize($config);
$data = array('query' => $query,'page'=>$home);
$data['news'] = $query;
$this->load->view('main/header');
$this->load->view('main/news', $data);
$this->load->view('main/footer');
}
}
And the Model:
function count_news()
{
$query=$this->db->query("SELECT * FROM `tdt_news` ORDER BY `id` DESC LIMIT $limit, $offset;");
return $query->result();
}
I'll be very thankful for your help, thank you!
You have a series of errors
your count function in your model is missing parameters
you should reformat the SQL string
alternate and standard syntax in your view
renamed model class to empty string
heres a fixed version,
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('model_add');
}
public function _remap($a){
if (isset($a) && !empty($a)) {
switch ($a) {
case 'index':
$this->index();
break;
default:
$this->one_news($a);
break;
}
}
}
public function index()
{
$this->load->library('pagination');
$home = $this->uri->segment(2);
$limit = 2;
$offset = 0;
$query=$this->model_add->count_news($limit,$offset);
$config['base_url'] = base_url().'/news/';
$config['total_rows'] = $this->db->count_all('tdt_news');
$config['per_page'] = 2;
$config['uri_segment'] = 2;
$this->pagination->initialize($config);
$data = array( 'query' => $query,
'page'=>$home,
'news' => $query);
$this->load->view('main/header');
$this->load->view('main/news', $data);
$this->load->view('main/footer');
}
}
Model:
// with default parameters just in case
function count_news($limit = 50, $offset = 0)
{
// and there is a nicer way to write your query
// it works with multiple dbs thanks to active record
$this->db->order_by('id','desc');
$query = $this->db->get('tdt_news', $limit, $offset);
return $query->result();
}

Codeigniter - Passing multiple parameters

I am trying to pass multiple parameters to my model from my controller. It seems that the $scholId that I am trying to pass won't go through to the model after I submit the form. However, the $userId goes through to the database just fine. Is there something wrong with $this->uri->segment(4) that won't pass through correctly?
function apply()
{
$this->load->helper('form');
$this->load->library('form_validation');
$scholId = $this->uri->segment(4);
$userId = '2'; //User query -> this will be taken from session
$this->data['scholarship'] = $this->scholarship_model->getScholarship($scholId);
$this->data['title'] = "Apply";
$this->form_validation->set_rules('essay', 'Essay', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $this->data);
$this->load->view('student/page_head', $this->data);
$this->load->view('student/form', $this->data);
$this->load->view('templates/footer', $this->data);
}else{
// Validation passes
$this->users_model->applySchol($userId,$scholId);
redirect('/scholarships');
}
}
you need to check up the segment whether it exists or not before passing it Like:
if ($this->uri->segment(4) === FALSE)
{
$schoId = 0; //or anything else so that you know that does not exists
}
else
{
$schoID= $this->uri->segment(4);
}
or simply:
$product_id = $this->uri->segment(4, 0);
//which will return 0 if it doesn't exists.

$db undefined when using model from helper in codeigniter

I want to have a simple helper which records one hit in my database. I have created a $CI instance and attempt to access the model like this...
$CI->load->model('stats_model');
$CI->stats_model->set_hit();
But i get an error in the model..
Severity: Notice
Message: Undefined property: Stats_model::$db
Filename: models/stats_model.php
Line Number: 16
Line 16 is a simple...
$this->db->select('*');
I got the idea to do this from this link http://blog.avinash.com.np/2010/07/01/talk-to-the-database-from-a-helper-codeigniter/
I have tried $CI->db... instead of $this->db in the model but still no luck, any ideas?
HELPER
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
function check_hit() {
//stuff that uses CI
$CI = & get_instance();
$CI->load->library('user_agent');
if ($CI->agent->is_robot()) {
return FALSE;
} else {
//check for a 12 hour cookie
$check = $CI->input->cookie('stat');
if ($check == false) {
//insert a database entry
$CI->load->model('Stats_model');
$CI->Stats_model->set_hit();
//set a cookie
$cookie = array(
'name' => 'stat',
'value' => '1',
'expire' => '43200'
);
// $CI->input->set_cookie($cookie);
}
}
}
check_hit();
?>
MODEL
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Stats_model extends Model {
function Stats_model() {
// Call the Model constructor
parent::Model();
}
function set_hit() {
$date = date('Y-m-d');
$this->db->select('unique_visitors');
$this->db->from('daily_stats');
$this->db->where('date', $date);
$query = $this->db->get();
$date_rows = $query->num_rows();
$result = $query->row();
$visits = $result->unique_visitors;
$visits++;
$data = array(
'unique_visitors' => $visits,
'date' => $date
);
if ($date_rows == 1) {
$this->db->where('date', $date);
$this->db->update('daily_stats', $data);
} else {
$this->db->insert('daily_stats', $data);
}
}
}
?>
This part was a little confusing for me a while back. This seemed to work.
//load the CI instance
$this->ci =& get_instance();
//run a db get
$this->ci->db->get('mytable');

Resources