undefined variable: id while clicking a dynamic image in homepage using CodeIgniter - php

Controller:
public function latestnews()
{
$data['news'] = $this->New_model->getById($id);
$this->load->view('news',$data);
}
Model:
public function getById($id)
{
return $this->db->get_where($this->_table, ["new_id" => $id])->row();
}
View:
<?php
if (isset($news) and $news) {
foreach($news as $new) {
?>
<div class="col-sm-12">
<div class="section">
<img src="<?php echo site_url('uploads/'.$new->image); ?>" />
</div>
<p><?php echo $new->description;?> </p>
</div>
<?php
}
}
?>
How and where to define the variable id?
While clicking a dynamic image,it should be opened in another page containing details but instead showing Undefined variable: id

In the latestnews() function you have no $id defined.
Try to call the latestnews() function with the right $id parameter.

you can write function like this,
function latestnews($id)
{

Controller:
function single_news($id) { // This $id variable comes from URL Ex: example.com/single_news/15. So $id = 15
$this->data['news_data'] = $this->new_model->getNewsByID($id);
$this->load->view('single-news', $this->data); // Create New View file named single-news.php
}
Model:
function getNewsByID($id) {
$this->db->where('id', $id);
$q = $this->db->get('news');
if($q->num_rows() > 0) {
return $q->row();
}
return false;
}
View: (Single News Page)
<div>
<img src="<?php echo site_url('uploads/'.$news_data->image); ?>" />
</div>

Related

How to display the values of database table in CodeIgniter?

I am creating a sample image test where in I want to display all of the images in a database table in CodeIgniter. The question is, how will I able to display the values of the database table using CodeIgniter?
Here is the code of my model:
<?php
class Image_model extends CI_Model{
/*Sample test function for the image dropdown list*/
public function getImages()
{
$query = $this->db->select('main_image_url'));
$this->db->get('product_master');
return $query->result();
}
/*End sample test function*/
}
?>
Here is the code of my controller:
<?php
if(! defined('BASEPATH')) exit('No direct script access allowed');
class Sample_image_dropdown extends MX_Controller{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['main_view'] = 'sample_view/image_dropdown_view';
$this->load->view('sample_view/image_dropdown_view', $data);
}
public function display_all_images()
{
$this->load->model('sample_model/image_model');
$data['images'] = $this->image_model->getImages();
$data['main_view'] = "sample_view/image_dropdown_view";
$this->load->view('sample_view/image_dropdown_view', $data);
}
}
?>
Here is the code of my view:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
<select name="" id="">
<option value="all">All Image</option>
<option value="with-image">With Image</option>
<option value="no-image">Without Image</option>
</select>
<input type="submit" value="Search">
</div>
<?php if (isset($images)):?>
<?php foreach ($images as $image):?>
<table>
<tr>
<td>
<th>
Images
</th>
</td>
</tr>
<tr>
<td>
<img src="<?php echo "$image->main_image_url";?>">
</td>
</tr>
</table>
<?php endforeach; ?>
<?php endif; ?>
</body>
</html>
You made a mistake in your model and in the controller, I mentioned the changes please note down and try,
Model File
class Image_model extends CI_Model{
/*Sample test function for the image dropdown list*/
public function getImages()
{
$query = $this->db->select('main_image_url');
$this->db->from('product_master');
$query = $this->db->get();
return $query->result();
}
/*End sample test function*/
}
Controller File,
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['main_view'] = 'sample_view/image_dropdown_view';
$this->display_all_images();
}
public function display_all_images()
{
$this->load->model('sample_model/image_model');
$data['images'] = $this->image_model->getImages();
$data['main_view'] = "sample_view/image_dropdown_view";
$this->load->view('sample_view/image_dropdown_view', $data);
}
I assume you are storing images in directory at the time of uploading at
uploads/abc.png
then you can get data from db (which you are already doing)
and in view :
<img src="echo dir_path./$image->main_image_url;" />
or if you are storing whole path in DB then :
<img src="echo $image->main_image_url;" />

Getting a single User Picture from sql DB (CodeIgniter)

So I'm in the middle of creating an E-Commerce site for a class. On my Profile page I'm planning to display various info stored in the db. Right now I'm only messing with the user photo. I have a function in the model that gets the Users photo from the column 'Image_Path' in DB 'users'. My problem is that for each profile view it shows the same photo. I think its return the whole array of pictures and maybe just sets it as the first one?
here is the model
<?php
class Profile_Model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
// public function get_profile_picture()
// {
//
// $query = $this->db->get('users');
// return $query -> result();
// }
public function get_single_profile($id){
//get whole table
$this->db->select('Username');
$this->db->select('Image_Path');
$this->db->from('users');
$this->db->where('User_ID', $id);
$query = $this->db->get();
return $query->result();
}//end get_single_profile
//for uploading profile pics
public function set_profile_pic(){
}
}//CLASS
?>
The Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Profile extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('session'); //needed to use global session variables
$this->load->helper('language');
$this->load->model('Profile/Profile_Model');
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$data['profilepicture'] = $this->Profile_Model->get_single_profile();
$this->load->view('Profile/Profile', $data);
}// echo session variable logged_in
else{
redirect( base_url().'Login'); //redirect to user profile view after verification)
}
}//END Index
public function logout(){
$this->session->sess_destroy();
redirect(base_url(). 'Login');
}//END LOGOUT
public function display_profile_pic(){
$data['profilepicture'] = $this->Profile_Model->get_profile_picture();
$this->load->view('Product/Product', $data);
}
}//END CLASS
The View
<!DOCTYPE html>
<html>
<head>
<title><?php echo $_SESSION['logged_in']?></title>
<style type="text/css">
.container {
width: 15%;
text-align: center;
clear:both;
}
.container input {
width: 100%;
clear: both;
}
.logout {
position: fixed;
bottom: 10%;
right: 10%;
}
.aboutme{
position:fixed;
right:50%;
bottom:50%;
}
.shopbutton{
position:fixed;
right:17%;
top:10%;
}
.checkout{
position:fixed;
right:10%;
top:10%;
}
</style>
</head>
<body>
<h3>Logged In As: <?php echo $_SESSION['logged_in']?> </h3>
**where the picture is displayed
<?php foreach ($profilepicture as $row)
{
echo '<img src='.base_url().'../'.$row->Image_Path.' style="Height: 300px; Width:200px;"><br>';
} ?>
<form action=" <?php echo base_url().'Profile';?>" method='post'>
<input type='submit' value='Upload Picture'>
</form>
<div class = 'aboutme'>
<p>About Me</p>
</div>
<div class = 'logout'>
<form action= '<?php echo base_url().'Profile/logout';?>' method='post'>
<input type="submit" value="Log Out">
</form>
</div>
<div class = 'checkout'>
<form action = '<?php echo base_url().'Cart/display_cart';?>' method='post'>
<input type='submit' value='Check Out'>
</form>
</div>
<div class = 'shopbutton'>
<form action = '<?php echo base_url().'Product/display_products';?>' method='post'>
<input type='submit' value='Shop'>
</form>
</div>
</body>
</html>
First, try changing the select portion of your query. It should be like:
$this->db->select('Image_Path, Username');
if it still not working, try to echo your last query in get_single_profile()
echo $this->db->last_query();
exit;
Changed my Model function to:
public function get_single_profile($id){
//get whole table
$this->db->select('Image_Path');
$this->db->from('users');
$this->db->where('Username', $id);
$query = $this->db->get();
echo $this->db->last_query();
return $query->result();
}//end get_single_profile
And My Controller Index To:
public function index()
{
if($this->session->userdata('logged_in'))
{
$data['profilepicture'] = $this->Profile_Model->get_single_profile($this->session->userdata('logged_in') );
$this->load->view('Profile/Profile', $data);
}// echo session variable logged_in
else{
redirect( base_url().'Login'); //redirect to user profile view after verification)
}
}//END Index
in the model I changed the Username from the table and set it to $id, In the controller I used a previously defined session variable to set $id to the session...I think

Codeigniter displaying message

I dont know whats wrong with my code..
I am trying to display message from database, but i keep on getting error that $results are not defined.
Controller
public function getMessages()
{
$this->load->model('get_message');
$data['results']= $this->get_message->getMessage();
$this->load->view('home_view', $data);
}
Model
<?php
class get_message extends CI_Model{
function getMessage(){
$query = $this->db->query("SELECT * FROM messages");
return $query->result_array();
}
}
View
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Home</h1>
<h2>Welcome <?php echo $username; ?>!</h2>
<div id="Main">
<?php
foreach($results->result() as $row){
echo $row ->id;
echo $row ->user_username;
echo $row ->text;
echo $row ->posted_at;
echo "<br/>";
}
?>
</div>
Logout
</body>
</html>
EDIT: here is what my code looks like now
Controller
public function index()
{
$this->load->model('get_message');
$data['results']= $this->get_message->getMessage();
$this->load->view('home_view', $data);
}
Model
<?php
class get_message extends CI_Model{
function getMessage(){
$query = $this->db->query('SELECT * FROM messages');
return $query->result_array();
}
}
view
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Home</h1>
<div id="Main">
<?php
foreach($results as $row){
echo $row['id'];
echo $row['user_username'];
echo $row['text'];
echo $row['posted_at'];
echo "<br/>";
}
?>
</div>
</body>
</html>
This code works. if it doesn't you are doing something else wrong.
In the controller you send data as result
$data['result']= $this->get_message->getMessage();
Access in view like this:
foreach($result as $row){
}
You used as results in foreach instead of result
You are passing wrong element to the view.
$data['result']= $this->get_message->getMessage();
^
Should be
$data['results']= $this->get_message->getMessage();
^
Also in Model,
return $query->result();
Should be:
return $query;
And in view,
foreach($results as $row){
Should be
if ($results->num_rows()) { // IN CASE, THE RESULT HAS NO ROWS.
foreach($results->result() as $row) {
View :
Your code
foreach(**$results** as $row){
}
?>
change to
foreach(**$result** as $row){
}
?>
Try to get result in some other variable in your controller function -
public function getMessages()
{
$this->load->model('get_message');
$data['msgesult']= $this->get_message->getMessage();
$this->load->view('home_view', $data);
}
And then in view -
<div id="Main">
<?php
foreach($msgesult as $row){
echo $row['id'];
echo $row['user_username'];
echo $row['text'];
echo $row['posted_at'];
echo "<br/>";
}
?>
</div>
This should work.

codeigniter ajax load table

I have write a some codeigniter code, when I click button add a data, and the table will ajax reload, not reload the page. How to modify my code? Thanks
This is my controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Big_category extends CI_Controller {
function __construct() {
...
}
function index() {
if($this->session->userdata('logged_in')) {
$this->page(0);
} else {
show_404('page');
}
}
function page($page) {
....
$data['pagelist']=$this->pagination->create_links();
$data["main_content"] = "big_category_view";
$this->load->view('template', $data);
}
This is my model
class Big_category_model extends CI_Model
{
...
function get_big_category($limit, $start)
{
$this->db->limit($limit, $start);
$query = $this->db->get_where('category1', array('c1_status' => 1)); //SELECT * FROM category1
return json_encode($query->result());
}
This is my view
...
<? $data = json_decode($all_big_category); ?>
<? foreach($data as $key => $value): ?>
<tr class="modify_tr">
<td><?=($key+1)?></td>
<td id="td_id_<?=$value->c1_id?>" class="modify_td">
<span id="c1_id_<?=$value->c1_id?>"><?=$value->c1_name?></span>
<form class="form-search td_id_<?=$value->c1_id?>">
<input type="text" name="input_c1_id" id="input_c1_id_<?=$value->c1_id?>">
<button class="btn modify" id="button_c1_id_<?=$value->c1_id?>" c1-id="<?=$value->c1_id?>" type="button"><i class="icon-edit"></i></button></td>
</form>
<td><button class="btn btn-danger"><i class="icon-remove-sign"></i></button></td>
</tr>
<? endforeach ?>
</table>
<?=$pagelist?>
...
Here is a simple technique of how you can achieve this.
Layout(Template)
<html>
<body>
<div><!--other stuff here--></div>
<div id = 'form_id'>
<?php echo $content?>
</div>
</body>
</html>
Controller
function index()
{
if($this->input->is_ajax_request()){
//load form here
$this->load->view('form');
}else{
//this will load the form for the first time
//pass third parameter as TRUE so it will returned as string
//assigned to index content which will be displayed in layout
$data['content'] = $this->load->view('form',$data , TRUE);
//load template here
$this->load->view('template', $data);
}
}
JQuery
$.ajax({
type : 'POST',
url : '<?php echo site_url('controllername/index')?>',
data : '' // query string
success : function(formagain){
$('#form_id').html(formagain);
//this will replace the content of div with new form
}
});

redirect() function doesn't work

I have create a web application using CodeIgniter making at first a login interface. Here are the controller I used but I think something doesn't work but I don't know what.The home page, where the user is granted, it doesn't show.Unfortunately I didn't have a debugger to check what doesn't work. maybe there is a problem to handle the session but really I don't know what can be. maybe you are smarther than me to find the error
Login Controller
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('User','user'); /* This call the model to retrieve data from db */
}
public function index()
{
if(!file_exists('application/views/_login.php'))
{
show_404();
}
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<h4 style="text-align:center;">','</h4>');
$this->form_validation->set_rules('username','username','trim|required|xss_clean');
$this->form_validation->set_rules('password','password','trim|required|xss_clean|callback_pass_check');
if($this->form_validation->run() == FALSE)
{
/* Data to pass to view */
$data['title'] = "User Access";
$data['author'] = "Salvatore Mazzarino";
$data['year'] = date('Y');
$this->load->view('templates/_header',$data);
$this->load->view('_login',$data);
$this->load->view('templates/_footer',$data);
}
else
{
redirect('home', 'refresh');
}
}
public function pass_check($pass)
{
$result = $this->user->find_user($this->input->post('username'),$pass);
if(!empty($result))
{
foreach ($result as $row)
{
$session_array = array('id'=> $row->id, 'username'=> $row->username); /* Create a session passing user data */
$this->session->set_userdata('logged_in', $session_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('pass_check',"Invalid username or password!</br>Try again, please!");
return FALSE;
}
}
}
/* END OF FILE */
Home Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
session_start();
}
public function index()
{
if($this->session->userdata('logged_in'))
{
$data['title'] = "Management Emergency";
$data['author'] = "Salvatore Mazzarino";
$data['year'] = date('Y');
$this->load->view('templates/_header', $data);
$this->load->view('_home',$data);
$this->load->view('templates/_footer',$data);
}
else
{
redirect('login', 'refresh');
}
}
public function logout()
{
$this->session->unset_userdata('logged_in');
session_destroy();
redirect('home','refresh');
}
}
/* END OF FILE */
The model in the login controller works very well so It isn't a problem of query. Before adding session everything works but when I added session stopped to worked so I think that can be a problem or redirect() or session
Home View
<div data-role = "page">
<div data-role = "header" data-position = "inline">
<?php echo heading($title,1) ?>
</div>
<div class = "menu-content">
<ul data-role = "listview" data-inset="true">
<li data-role = "list-divider">Emergency MenĂ¹</li>
<li class = "menu-item">
<a href="">
<div class = "image-wrapper">
<img src="/assets/images/user.png" class = "ui-li-icons" />
</div>
Add patient
</a>
</li>
<li class = "menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/home.png" class = "ui-li-icons" />
</div>
Show all hospital
</a>
</li>
<li class = "menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/favorite.png" class="ui-li-icons" />
</div>
Find patients
</a>
</li>
<li class="menu-item">
<a href="#">
<div class = "image-wrapper">
<img src="/assets/images/email.png" class="ui-li-icons" />
</div>
Send medical infos
</a>
</li>
</ul>
Login View
<div data-role ="dialog">
<div data-role = "header" data-theme="e">
<?php echo heading($title,1) ?>
</div>
<div data-role ="content">
<?php
$var = validation_errors();
if(!empty($var))
{
echo form_error('username');
echo form_error('password');
}
else
{
echo heading('911 - First Aid',2,'style="text-align:center; color:red;"');
echo form_open('login');
?>
<div data-role ="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="name" value="" placeholder="Username"/>
</div>
<div data-role ="fieldcontain" class="ui-hide-label">
<label for="password">Password</label>
<input type="password" name="password" id="password" value="" placeholder="Password"/>
</div>
<div data-role ="fieldcontain">
<input type="submit" value="Login" data-theme ="b"/>
</div>
</form>
<?
}
?>
There is a problem with CodeIgniter retaining it's session data after a redirect. Your if($this->session->userdata('logged_in')) in your home.php controller will evaluate false every time because the session is resetting. You could use the native php sessions to skip over this problem.
See: http://codeigniter.com/wiki/Native_session/. Good luck!
UPDATE
Apparently, this is only true of CodeIgniter 1.7.2 when used with IE6. It doesn't affect most browsers.
open the application/config/autoload.php file and add the 'url' in the helper array;
$autoload['helper'] = array('url');
i hope this will help you to fix the problem.

Categories