why every user can see Chat conversations in codeigniter - php

I have programmed a simple Chat conversations between 2 users , but the problem is every one can see the conversation , like all the users in the same rooms , but me i want just the conversation private between 2 users like facebook . this is a capture for my script .
my entire code of controller :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Chat extends CI_Controller {
Public function __construct() {
parent::__construct();
$this->load->model('chats');
$this->load->model('regis');
}
public function index() {
}
public function send() {
date_default_timezone_set('Asia/Jakarta');
$date = date('Y-m-d H:i:s');
$message = array(
'sender' => $this->session->userdata('user'),
'time' => $date,
'text' => $this->input->post('message')
);
$this->db->insert('chat', $message);
redirect (base_url('chat'));
}
public function open() {
return $this->chats->main(array('status'=>TRUE));
}
public function maintenance() { return $this->chats->main(array('status'=>FALSE)); }
public function pending() {
if ($this->session->userdata('sesi') == FALSE) {
$this->session->set_flashdata('login', 'You Must Login!');
redirect(base_url());
} else {
$data['orang'] = $this->regis->orang();
$data['status'] = $this->chats->get_stats()->result();
$this->load->view('header');
$this->load->view('pending', $data);
$this->load->view('footer');
}
}
}
my models:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Chats extends CI_Model {
public function __construct() { $this->load->database(); }
public function isi_chat(){ return $this->db->select('*')->order_by('time','ASC')->get('chat'); }
public function main($status) {
$this->db->update('status', $status);
redirect(base_url('chat'));
}
public function get_stats() { return $this->db->get('status'); }
}
my view :
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<br><br><br>
<?= $this->session->flashdata('done'); ?>
<div class="panel panel-default">
<?php foreach($status as $s): ?>
<div class="panel-heading">
<strong><?= $this->session->userdata('nama'); ?></strong>
Exit
<?php
if ($this->session->userdata('akses') == 'ADMIN') {
echo "<i class=\"glyphicon glyphicon-user\"></i> User Pending";
if($s->status == TRUE) {
echo "<i class=\"glyphicon glyphicon-lock\"></i> Maintenance";
} else {
echo "<i class=\"glyphicon glyphicon-ok\"></i> Buka Chat";
}
}
?>
</div>
<?php endforeach ?>
<?php if ($s->status == TRUE): ?>
<div class="panel-body" style="height: 300px; overflow-y: scroll">
<?php foreach ($chat as $c){ ?>
<?php if($c->sender == $this->session->userdata('user')){ ?>
<div class="col-md-12">
<div class="panel panel-success panel-comment pull-right">
<div class="panel-heading" >
<strong style="opacity: .5; font-size: 12px; color: #4BD239">ME : </strong>
<small><?php echo date("d-M-Y H:i:s", strtotime($c->time)); ?></small><br/>
<?= $c->text ?>
</div>
</div>
</div>
<?php } else { ?>
<div class="col-md-12">
<div class="panel panel-warning panel-comment pull-left">
<div class="panel-heading" >
<strong style="opacity: .5; font-size: 12px; color: #DCD15B"><?= $c->sender ?>:</strong>
<small><?php echo date("d-M-Y H:i:s", strtotime($c->time)); ?></small><br/>
<?= $c->text ?>
</div>
</div>
</div>
<?php } ?>
<?php } ?>
</div>
<?php endif ?>
<?php if ($s->status == FALSE): ?>
<div class="panel-body">
<h4 class="text-center" style="color: #FF0000">SORRY<br> MAINTENANCE<br><br></h4>
</div>
<?php endif ?>
</div>
<?php if ($s->status == TRUE): ?>
<div class="row">
<div class="col-md-12 ">
<form method="post" action="chat/send">
<div class="col-md-12">
<div class="input-group">
<input type="text" name="message" class="form-control" placeholder="Masukan Teks">
<span class="input-group-btn">
<input class="btn btn-success" type="submit" value="Send">
</span>
</div>
</div>
</form>
</div>
</div>
<?php endif ?>
</div>
</div>
</div>
now the problem is i want the conversation private between 2 users ! can some one help me please because it's more than 5 days i try to solve this problem without any result . thank you

Related

all db records get updated instead of only 1 CodeIgniter 4

I am working on a school project.
I have a validateUser function in my Users.php controller:
public function validateUser()
{
$data = [];
UserModel::validateUser($this->request->getPost('id_user')); // validate the user
if (session()->get('success'))
{
return redirect()->to('admin_panel');
}
else
{
echo view('templates/header', $data);
echo view('admin_panel2',$data);
echo view('templates/footer');
}
}}
This is my validateUser function in my UserModel.php
public static function validateUser($id_user)
{
$model = new UserModel();
$data = ['id_role' => '2'];
$model->update($id_user,$data);
session()->setFlashdata('success', 'Successfuly Validated');
}
My view
<div class="container">
<div class="row">
<div class="col-12">
<div class="container">
<p></p>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h6 class="panel-title">
<a data-toggle="collapse" href="#collapse1">
<?php
echo "<h3>Users To Validate</h3>";
?>
</a>
<?php
?>
</h6>
</div>
<div id="collapse1" class="panel-collapse collapse">
<div class="panel-body">
<h4></h4>
<ol>
<div class="container">
<div class="row">
<div class="col-12 col-sm8- offset-sm-2 col-md-6 offset-md-3 mt-5 pt-3 pb-3 bg-white form-wrapper">
<div class="container">
<?php if (session()->get('success')) : ?>
<div class="alert alert-success" role="alert">
<?= session()->get('success') ?>
</div>
<?php endif; ?>
<?php foreach ($usersToValidate as $row)
echo '<li class="nav-item">' . $row->firstname . ' ' . $row->lastname . '<a class="nav-link active" href="validate_user?id_user='.$row->id_user.'">Validate</a></li>';
?>
<ul class="nav">
</ul>
</div>
</div>
</div>
</div>
</ol>
</div>
<div class="panel-footer">
</div>
</div>
</div>
</div>
</div>
<div class="container">
<hr>
<?php if (isset($permissions)) : ?>
<div class="col-12">
<div class="alert alert-danger" role="alert">
</div>
</div>
<?php else : ?>
<?php endif; ?>
<?php if (isset($validation)) : ?>
<div class="col-12">
<div class="alert alert-danger" role="alert">
<?= $validation->listErrors() ?>
</div>
</div>
<?php else : ?>
<?php endif; ?>
</div>
</div>
</div>
The problem is that in my 'users' table all 'id_role' records get changed to '2'. I only wish to update a single record in the db.
Any idea what I'm doing wrong ?
I found the issue. I replaced $this->request->getPost('id_user') with getGet('id_user') in my controller function
public function validateUser()
{
$data = [];
UserModel::validateUser($this->request->getGet('id_user')); // validate the user
if (session()->get('success'))
{
return redirect()->to('admin_panel');
}
else
{
echo view('templates/header', $data);
echo view('admin_panel2',$data);
echo view('templates/footer');
}
}

A Database Error Occurred: 1048 cannot insert data

I cannot save my data, eventhough my database already same like the code... What must I do??
A Database Error Occurred Error Number: 1048
Column 'image' cannot be null
INSERT INTO gallery (id_gallery, name, image) VALUES
('5bba4390eb0b8', 'nnn', NULL)
Filename: C:/xampp/htdocs/eat/system/database/DB_driver.php
Line Number: 691
Controller: Gallery.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Gallery extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model("gallery_model");
$this->load->library('form_validation');
}
public function index()
{
$data["gallery"] = $this->gallery_model->getAll();
$this->load->view("admin/gallery/list", $data);
}
public function add()
{
$gallery = $this->gallery_model;
$validation = $this->form_validation;
$validation->set_rules($gallery->rules());
if ($validation->run()) {
$gallery->save();
$this->session->set_flashdata('success', 'Berhasil disimpan');
}
$this->load->view("admin/gallery/new_form");
}
public function edit($id = null)
{
if (!isset($id)) redirect('admin/gallery');
$gallery = $this->gallery_model;
$validation = $this->form_validation;
$validation->set_rules($gallery->rules());
if ($validation->run()) {
$gallery->update();
$this->session->set_flashdata('success', 'Berhasil disimpan');
}
$data["gallery"] = $gallery->getById($id);
if (!$data["gallery"]) show_404();
$this->load->view("admin/gallery/edit_form", $data);
}
public function delete($id=null)
{
if (!isset($id)) show_404();
if ($this->gallery_model->delete($id)) {
redirect(site_url('admin/gallery'));
}
}
}
Model: Gallery_model.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Gallery_model extends CI_Model
{
private $_table = "gallery";
public $id_gallery;
public $name;
public $image;
public function rules()
{
return [
['field' => 'name',
'label' => 'Name',
'rules' => 'required']
];
}
public function getAll()
{
return $this->db->get($this->_table)->result();
}
public function getById($id)
{
return $this->db->get_where($this->_table, ["id_gallery" => $id])->row();
}
public function save()
{
$post = $this->input->post();
$this->id_gallery = uniqid();
$this->name = $post["name"];
$this->image = $this->_uploadImage();
$this->db->insert($this->_table, $this);
}
public function update()
{
$post = $this->input->post();
$this->id_gallery = $post["id"];
$this->name = $post["name"];
if (!empty($_FILES["image"]["name"])) {
$this->image = $this->_uploadImage();
} else {
$this->image = $post["old_image"];
}
$this->db->update($this->_table, $this, array('id_gallery' => $post['id']));
}
public function delete($id)
{
$this->_deleteImage($id);
return $this->db->delete($this->_table, array("id_gallery" => $id));
}
private function _uploadImage()
{
$config['upload_path'] = './upload/gallery/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = $this->id_gallery;
$config['overwrite'] = true;
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
return $this->upload->data("file_name");
}
}
private function _deleteImage($id)
{
$gallery = $this->getById($id);
if ($gallery->image != "default.jpg") {
$filename = explode(".", $gallery->image)[0];
return array_map('unlink', glob(FCPATH."upload/gallery/$filename.*"));
}
}
}
In view there is 3 page: list.php, new_form.php, edit_form.php
list.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view("admin/_partials/head.php") ?>
</head>
<body id="page-top">
<?php $this->load->view("admin/_partials/navbar.php") ?>
<div id="wrapper">
<?php $this->load->view("admin/_partials/sidebar.php") ?>
<div id="content-wrapper">
<div class="container-fluid">
<?php $this->load->view("admin/_partials/breadcrumb.php") ?>
<!-- DataTables -->
<div class="card mb-3">
<div class="card-header">
<i class="fas fa-plus"></i> Add New
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Photo</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($gallery as $gallery): ?>
<tr>
<td width="150">
<?php echo $gallery->name ?>
</td>
<td>
<img src="<?php echo base_url('upload/gallery/'.$gallery->image) ?>" width="64" />
</td>
<td width="250">
<a href="<?php echo site_url('admin/gallery/edit/'.$gallery->gallery_id) ?>"
class="btn btn-small"><i class="fas fa-edit"></i> Edit</a>
<a onclick="deleteConfirm('<?php echo site_url('admin/gallery/delete/'.$gallery->gallery_id) ?>')"
href="#!" class="btn btn-small text-danger"><i class="fas fa-trash"></i> Hapus</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- /.content-wrapper -->
</div>
<!-- /#wrapper -->
<?php $this->load->view("admin/_partials/scrolltop.php") ?>
<?php $this->load->view("admin/_partials/modal.php") ?>
<?php $this->load->view("admin/_partials/js.php") ?>
<script>
function deleteConfirm(url){
$('#btn-delete').attr('href', url);
$('#deleteModal').modal();
}
</script>
</body>
</html>
new_form.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view("admin/_partials/head.php") ?>
</head>
<body id="page-top">
<?php $this->load->view("admin/_partials/navbar.php") ?>
<div id="wrapper">
<?php $this->load->view("admin/_partials/sidebar.php") ?>
<div id="content-wrapper">
<div class="container-fluid">
<?php $this->load->view("admin/_partials/breadcrumb.php") ?>
<?php if ($this->session->flashdata('success')): ?>
<div class="alert alert-success" role="alert">
<?php echo $this->session->flashdata('success'); ?>
</div>
<?php endif; ?>
<div class="card mb-3">
<div class="card-header">
<i class="fas fa-arrow-left"></i> Back
</div>
<div class="card-body">
<form action="<?php base_url('admin/gallery/add') ?>" method="post" enctype="multipart/form-data" >
<div class="form-group">
<label for="name">Title*</label>
<input class="form-control <?php echo form_error('name') ? 'is-invalid':'' ?>"
type="text" name="name" placeholder="gallery name" />
<div class="invalid-feedback">
<?php echo form_error('name') ?>
</div>
</div>
<div class="form-group">
<label for="image">Photo</label>
<input class="form-control-file <?php echo form_error('image') ? 'is-invalid':'' ?>"
type="file" name="image"/>
<div class="invalid-feedback">
<?php echo form_error('image') ?>
</div>
</div>
<input class="btn btn-success" type="submit" name="btn" value="Save" />
</form>
</div>
<div class="card-footer small text-muted">
* required fields
</div>
</div>
</div>
</div>
</div>
<?php $this->load->view("admin/_partials/scrolltop.php") ?>
<?php $this->load->view("admin/_partials/js.php") ?>
</body>
</html>
edit_form.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view("admin/_partials/head.php") ?>
</head>
<body id="page-top">
<?php $this->load->view("admin/_partials/navbar.php") ?>
<div id="wrapper">
<?php $this->load->view("admin/_partials/sidebar.php") ?>
<div id="content-wrapper">
<div class="container-fluid">
<?php $this->load->view("admin/_partials/breadcrumb.php") ?>
<?php if ($this->session->flashdata('success')): ?>
<div class="alert alert-success" role="alert">
<?php echo $this->session->flashdata('success'); ?>
</div>
<?php endif; ?>
<!-- Card -->
<div class="card mb-3">
<div class="card-header">
<a href="<?php echo site_url('admin/gallerys/') ?>"><i class="fas fa-arrow-left"></i>
Back</a>
</div>
<div class="card-body">
<form action="<?php base_url(" admin/gallery/edit") ?>" method="post"
enctype="multipart/form-data" >
<input type="hidden" name="id" value="<?php echo $gallery->gallery_id?>" />
<div class="form-group">
<label for="name">Name*</label>
<input class="form-control <?php echo form_error('name') ? 'is-invalid':'' ?>"
type="text" name="name" placeholder="gallery name" value="<?php echo $gallery->name ?>" />
<div class="invalid-feedback">
<?php echo form_error('name') ?>
</div>
</div>
<div class="form-group">
<label for="name">Photo</label>
<input class="form-control-file <?php echo form_error('image') ? 'is-invalid':'' ?>"
type="file" name="image" />
<input type="hidden" name="old_image" value="<?php echo $gallery->image ?>" />
<div class="invalid-feedback">
<?php echo form_error('image') ?>
</div>
</div>
<input class="btn btn-success" type="submit" name="btn" value="Save" />
</form>
</div>
<div class="card-footer small text-muted">
* required fields
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- /.content-wrapper -->
</div>
<!-- /#wrapper -->
<?php $this->load->view("admin/_partials/scrolltop.php") ?>
<?php $this->load->view("admin/_partials/js.php") ?>
</body>
</html>

How to get the exact value from function shuffle in codeigniter?

Hello im just a newbie in codeigniter and i just want to ask on how to fix this problem...
i just want to make a simple quiz system and i want to shuffle all the questions from my database and display it.. the problem is when i compare the questions choices it gives me a value of unshuffle how can i solve this?
this is my controller to display my questions
public function quiz()
{
if(isset($_SESSION['username'])) {
$this->load->model('quizmodel');
$this->data['questions'] = $this->quizmodel->getQuestions();
$this->load->view('client/quiz', $this->data);
}else{
$this->load->view('home');
}
}
this is the getQuestions function from my quizmodel
public function getQuestions()
{
$this->db->select("cropscience_id, question, choice1, choice2, choice3, answer");
$this->db->from("cropscience");
$query = $this->db->get();
return $query->result();
$num_data_returned = $query->num_rows;
if ($num_data_returned < 1) {
echo "There is no data in the database";
exit();
}
}
this is my quiz view
<div class="panel-body">
<form method="post" action="<?php echo base_url();?>index.php/client_controller/resultdisplay">
<?php shuffle($questions); ?>
<?php foreach($questions as $row) { ?>
<?php $ans_array = array($row->choice1, $row->choice2, $row->choice3, $row->answer);
shuffle($ans_array); ?>
<div class="alert alert-success">
<p><?=$row->question?></p>
<br>
<div class="radio radio-success radio-inline">
<input type="radio" name="<?php echo $row->cropscience_id ?>" value="<?=$ans_array[0]?>" required>
<label for="inlineRadio1"> <?=$ans_array[0]?> </label>
</div>
<div class="radio radio-success radio-inline">
<input type="radio" name="<?php echo $row->cropscience_id ?>" value="<?=$ans_array[1]?>">
<label for="inlineRadio1"> <?=$ans_array[1]?> </label>
</div>
<div class="radio radio-success radio-inline">
<input type="radio" name="<?php echo $row->cropscience_id ?>" value="<?=$ans_array[2]?>">
<label for="inlineRadio1"> <?=$ans_array[2]?> </label>
</div>
<div class="radio radio-success radio-inline">
<input type="radio" name="<?php echo $row->cropscience_id ?>" value="<?=$ans_array[3]?>">
<label for="inlineRadio1"> <?=$ans_array[3]?> </label>
</div>
</div>
<?php } ?>
<div align="center" >
<div class="btn btn-primary btn-rounded">
<i class="fa fa-check"></i><input class="btn btn-primary btn-rounded" type="submit" value="Submit!">
</div>
</div>
</form>
</div>
this is my resultdisplay function from my controller
public function resultdisplay()
{
if(isset($_SESSION['username'])) {
$this->load->model('quizmodel');
$qID = $this->quizmodel->getQuizID();
$this->data['checks'] = $this->input->post($qID);
$this->load->model('quizmodel');
$this->data['results'] = $this->quizmodel->resultsScore();
$this->load->view('client/result_display', $this->data);
}else{
$this->load->view('home');
}
}
this is my result_display view
div class="wrapper wrapper-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<h1 style="color: white;">Results</h1>
</div>
<div class="panel-body">
<?php $score = 0; ?>
<?php $array1= array(); ?>
<?php $array2= array(); ?>
<?php $array3= array(); ?>
<?php $array4= array(); ?>
<?php $array5= array(); ?>
<?php $array6= array(); ?>
<?php $array7= array(); ?>
<?php $array8= array(); ?>
<?php $count = 0; ?>
<?php foreach($checks as $checkans) { ?>
<?php echo $checkans; ?>
<?php $array1[$count] = $checkans;
$count++; ?>
<?php }?>
<br><br>
<?php foreach($results as $res) { ?>
<?php $array2[] = $res->answer;
$array3[] = $res->cropscience_id;
$array4[] = $res->question;
$array5[] = $res->choice1;
$array6[] = $res->choice2;
$array7[] = $res->choice3; ?>
<?php } ?>
<?php for ($x=0; $x <= $array3[$x]; $x++) { ?>
<?php echo $array4[$x]; ?>
<?php if ($array2[$x] != $array1[$x]) { ?>
<div class="alert alert-danger">
<p><i class="fa fa-times"></i></p>
<p><span style="background-color: #FF9C9E"><?=$array1[$x]?></span></p>
<p><span style="background-color: #ADFFB4"><?=$array2[$x]?></span></p>
</div>
<?php } else { ?>
<div class="alert alert-success">
<p><i class="fa fa-check"></i></p>
<p><span style="background-color: #ADFFB4"><?=$array1[$x]?></span></p>
</div>
<?php $score = $score + 1 ?>
<?php } ?>
<?php } ?>
<div align="center">
<input type="hidden" name="score" value="<?=$score?>">
<input type="button" class="btn btn-primary" data-toggle="modal" data-target="#scoremodal" value="View Your Score">
<!-- Score Modal Body -->
<div class="modal inmodal fade" id="scoremodal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-body" align="center">
<h2>Your Score is: </h2>
<h1><?=$score?>/100</h1>
</div>
<div class="modal-footer">
<?php echo form_open('client_controller/save_score'); ?>
<form method="get">
<div align="center">
<input type="hidden" name="score" value="<?=$score?>">
<input type="submit" class="btn btn-primary" value="Ok">
</div>
</form>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
this is my getQuizID() function model
public function getQuizID()
{
$this->db->select("cropscience_id");
$this->db->from("cropscience");
$query = $this->db->get();
}
this is my resultsScore() function model
public function resultsScore()
{
$this->db->select("cropscience_id, question, choice1, choice2, choice3, answer");
$this->db->from("cropscience");
$query = $this->db->get();
return $query->result();
$num_data_returned = $query->num_rows;
}
please help thank you
make a query like this:
$this->db->order_by('id', 'RANDOM');
or
$this->db->order_by('rand()');
$query = $this->db->get('cropscience');
return $query->result_array();

I need to display 3 unique products in each div

I need to display 3 unique products in each div, like this: Sample output
How can I get the different products in one loop? At present in the below code, I'm getting the same product 3 times.
<?php
foreach ($rows as $display) {
?>
<div class="col-md-4 col-sm-6">
<div class="section-title">
<div class="pull-right pr-icon">
<i class="fa fa-diamond"></i> Top Suppliers
</div>
<div class="main-title">
<b> Selected Products</b>
</div>
<div class="sub-title">
Source the latest items
</div>
</div>
<div class="row">
<div class="col-md-4">
<img src="<?php echo 'data:image;base64,'.$display->image; ?>" class="img-responsive image product-item" />
<div class="product-description">
<p class="text-center"><?php echo $display->name; ?></p>
<p class="desc-btn">VIEW</p>
</div>
</div>
</div>
</div>
<?php
}
?>
From controller:
public function index()
{
$this->load->database();
$data['rows']=$this->homemodel->fetchData();
$this->load->view('home',$data);
$this->load->library('image_lib');
}
Model code:
<?php
class homemodel extends CI model {
function __construct()
{
parent::__construct();
}
public function fetchData()
{
$query=$this->db->select('*');
$this->db->from('display');
$query = $this->db->get();
return $query->result();
}
}
?>
<?php
$chunkedArray = array_chunk($rows, 3); //productList Array, number of chunks/parts
foreach($chunkedArray as $newRow) {
echo '<div class="row">';
foreach ($newRow as $display) {
?>
<div class="col-md-4 col-sm-6">
<div class="section-title">
<div class="pull-right pr-icon">
<i class="fa fa-diamond"></i> Top Suppliers
</div>
<div class="main-title">
<b> Selected Products</b>
</div>
<div class="sub-title">
Source the latest items
</div>
</div>
<div class="row">
<div class="col-md-4">
<img src="<?php echo 'data:image;base64,'.$display->image; ?>" class="img-responsive image product-item" />
<div class="product-description">
<p class="text-center"><?php echo $display->name; ?></p>
<p class="desc-btn">VIEW</p>
</div>
</div>
</div>
</div>
<?php
}
echo '</div>';
}
?>
array_chunk would do the work..
know more on array_chunk here

My way for: only admin can register and all login system- but it's good? codeigniter

Below I will show you a few of my classes:
Login_model, where I set session.
<?php
class Login_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
public $details;
function validate_user( $login, $password )
{
$this->db->from('user');
$this->db->where('login',$login );
$this->db->where( 'password', $password);
$login = $this->db->get()->result(); // = "select * from user where login = '" . $login . "' and password = '" . $password . "' "
if ( is_array($login) && count($login) == 1 )
{
$this->details = $login[0];
$this->set_session();
return true;
}
else return false;
}
function set_session()
{
$this->session->set_userdata( array(
'user_id'=>$this->details->user_id,
'login'=>$this->details->login,
'isAdmin'=>$this->details->isAdmin,
'isLoggedIn'=>true
)
);
}
}
Login Controller where i fight with isLoggedIn. Did I won the fight? Is this good way?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Login_model');
}
function index()
{
if( $this->session->userdata('isLoggedIn')) redirect('home');
else redirect('login/check_user');
}
public function check_user()
{
if( $this->session->userdata('isLoggedIn')) redirect('home');
//get the posted values
$username = $this->input->post("txt_username");
$password = $this->input->post("txt_password");
//set validations
$this->form_validation->set_rules("txt_username", "Username", "trim|required");
$this->form_validation->set_rules("txt_password", "Password", "trim|required");
if ($this->form_validation->run() == FALSE)
{
//validation fails
$this->load->view('login_view');
$this->load->view('footer');
}
else
{
//validation succeeds
if ($this->input->post('btn_login') == "Login")
{
//check if username and password is correct
$usr_result = $this->Login_model->validate_user($username, $password);
if ($usr_result) //active user record is present
{
redirect("home");
}
else
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Invalid username and password!</div>');
redirect('login/check_user');
}
}
else
{
redirect('login/check_user');
}
}
}
public function do_logout()
{
$this->session->sess_destroy();
redirect('login/check_user');
}
}
home_view and here is question. Can I in this way check in view value isAdmin? I thinked also about new view for admin with button "signup" and check isAdmin in Controller, but then I have more views and views for admin is almost this same as for user, because difference is only button signup. The user registration is blocked that only the admin can go in there if someone typed in the browser corresponding url, he will not enter, but I have if in view. This is good? I'm just learning mvc model.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sesja gminy</title>
<link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.css"); ?>" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-6 col-sm-6">
<h1>Zalogowałeś się, oto Twoja strona startowa</h1>
</div>
<div class="col-lg-2 col-sm-2">
<ul class="nav nav-pills pull-right" style="margin-top:20px">
<button name="cancel" type="reset" class="btn btn-default"> Wyloguj się</button>
</ul>
</div>
<?php if( $this->session->userdata('isAdmin')==1 ) { ?>
<div class="col-lg-2 col-sm-2 ">
<ul class="nav nav-pills pull-right" style="margin-top:20px">
<li>Signup</li>
</ul>
</div>
<?php } ?>
</div>
<div class="row">
<ul>
<?php foreach ($result as $item): ?>
<div class="col-sm-4">
<div class="col-sm-12 text-center">
<h4><b/>Sesja : <?php echo $item->description ?></b><br>
Data sesji to: <?php echo $item->session_date ?></h4>
<button type="submit" name class="btn btn-primary form-control">Wybierz</button>
<hr/>
</div>
</div>
<?php endforeach;?>
</ul>
</div>
</div>
Home Controller, without Home_model, because there I only get data from database.
<?php
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Home_model');
if( !$this->session->userdata('isLoggedIn') )
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Proszę się zalogować, aby móc przejśc na stronę startową!</div>');
redirect('login/check_user');
}
}
public function index()
{
$data['result']= $this->Home_model->get_all_session();
$this->load->view('home_view', $data);
$this->load->view('footer');
}
}
To sum up, what is bad in my code?
In scale 1-10 is 7/10? :)
Thanks for your response and your precious time
IN Controller
class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Home_model');
if( !$this->session->userdata('isLoggedIn') )
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Proszę się zalogować, aby móc przejśc na stronę startową!</div>');
redirect('login/check_user');
}
}
public function index()
{
$data['result']= $this->Home_model->get_all_session();
$data['isAdmin']=$this->session->userdata('isAdmin');
$this->load->view('home_view', $data);
$this->load->view('footer');
}
}
IN View
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sesja gminy</title>
<link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.css"); ?>" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-6 col-sm-6">
<h1>Zalogowałeś się, oto Twoja strona startowa</h1>
</div>
<div class="col-lg-2 col-sm-2">
<ul class="nav nav-pills pull-right" style="margin-top:20px">
<button name="cancel" type="reset" class="btn btn-default"> Wyloguj się</button>
</ul>
</div>
<?php if( $isAdmin==1 ) { ?>
<div class="col-lg-2 col-sm-2 ">
<ul class="nav nav-pills pull-right" style="margin-top:20px">
<li>Signup</li>
</ul>
</div>
<?php } ?>
</div>
<div class="row">
<ul>
<?php foreach ($result as $item): ?>
<div class="col-sm-4">
<div class="col-sm-12 text-center">
<h4><b/>Sesja : <?php echo $item->description ?></b><br>
Data sesji to: <?php echo $item->session_date ?></h4>
<button type="submit" name class="btn btn-primary form-control">Wybierz</button>
<hr/>
</div>
</div>
<?php endforeach;?>
</ul>
</div>
</div>

Categories