I need help fetching data from database and display them in view.
My DB name is directory and table usernames that includes:id,title,body,slug,username,platform,gender,age and created_at.
I used foreach to display all posts from database, but i want to display now a specific post based on platform.
How can i do it?
This is the code i use to display all usernames from the database ordered by id:
<div class="col-md-6 mb-4">
<div class="card">
<div class="card-body" style="height: 130px;">
<h5 class="card-title"><?php echo $username_data['title']; ?></h5>
<p class="card-text"><?php echo word_limiter($username_data['body'], 24); ?></p>
</div>
<div class="card-footer text-muted">
<div class="row">
<div class="col-6">
<small>Created at: <?php echo $username_data['created_at'];?></small><br>
<strong>Is <?php echo $username_data['gender'];?></strong>
</div>
<div class="col-6 text-right">
View full message
</div>
</div>
</div>
</div>
</div>
This is my model:
<?php
class Usernames extends CI_Controller{
public function index(){
$data['title'] = 'Lastest Posts';
$data['posts'] = $this->post_model->get_usernames();
$this->load->view('templates/header');
$this->load->view('usernames/index', $data);
$this->load->view('templates/footer');
}
public function view($slug = NULL){
$data['post'] = $this->post_model->get_usernames($slug);
$query = $this->db->get('usernames');
if(empty($data['post'])){
show_404();
}
$data['title'] = $data['post']['title'];
$this->load->view('templates/header');
$this->load->view('usernames/view', $data);
$this->load->view('templates/footer');
}
public function create(){
$data['title'] = 'Create Post';
$this->form_validation->set_rules('title','Title','required');
$this->form_validation->set_rules('body','Message','required');
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('age','Age','required');
$this->form_validation->set_rules('gender','Gender','required');
$this->form_validation->set_rules('platform','Platform','required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('usernames/create', $data);
$this->load->view('templates/footer');
} else {
$this->post_model->create_username();
redirect('usernames');
}
}
public function snapchat(){
$data['title'] = 'Lastest Posts';
$data['posts'] = $this->post_model->get_usernames();
$this->load->view('templates/header');
$this->load->view('usernames/snapchat', $data);
$this->load->view('templates/footer');
}
}
Model:
<?php
class Post_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function get_usernames($slug = FALSE){
if($slug === FALSE){
$this->db->order_by('usernames.id', 'DESC');
$query = $this->db->get('usernames');
return $query->result_array();
}
$query = $this->db->get_where('usernames', array('slug' => $slug));
return $query->row_array();
}
public function create_username(){
$slug_link = substr(str_replace(['+', '/', '='], '', base64_encode(random_bytes(16))), 0, 16);
$slug = url_title($this->input->post('title').'-'.$slug_link);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'body' => $this->input->post('body'),
'platform' => $this->input->post('platform'),
'age' => $this->input->post('age'),
'gender' => $this->input->post('gender'),
'username' => $this->input->post('username')
);
return $this->db->insert('usernames', $data);
}
}
Everything is working fine, but i don't know really how to fetch those data.
I need that in this specific page ('telegram.php'), show all rows that includes Telegram from platform.
As mentioned before, my database is structured like this:
directory(DB Name)
usernames(table name)
->id->title->body->slug->user
public function get_usernames_from_platform($platform){
if(!empty($platform)){
$this->db->where('platform',$platform);
$this->db->order_by('usernames.id', 'DESC');
$query = $this->db->get('usernames');
return $query->result_array();
}
return array();
}
Add the method, to your Model and call it to fetch the corresponding data in the corresponding method in your controller.
It seems to be missing its constructor $this->load->model('post_model');
Related
Controller
public function show_sku() {
$this->load->view('templates/header');
$this->load->view('check_sku');
$this->load->view('templates/footer');
}
public function retrieve_data() {
$data['product'] = $this->sku->find_sku();
$this->load->view('templates/header');
$this->load->view('check_sku', $data);
$this->load->view('templates/footer');
}
Routes
$route['check_sku/show_sku'] = 'check_sku/show_sku';
$route['check_sku/retrieve_data'] = 'check_sku/retrieve_data';
View
<?php echo form_open('/check_sku/retrieve_data'); ?>
<div class="form-group">
<?php echo form_label('SKU', 'sku', ''); ?>
<?php echo form_input('sku', '', $options['sku']); ?>
<?php echo form_submit('', 'Check', 'class="btn btn-primary"') ?>
</div>
<?php echo form_close(); ?>
Model
public function find_sku() {
$this->load->library('get_api');
$sku = $this->input->post('sku');
$get_data = $this->get_api->get_data("GET", "http://89.201.137.7:8082/datasnap/rest/artikli/sifra/" . $sku, false);
$response = json_decode($get_data, true);
return $response['result'][0]['artikli'][0];
}
What is the proper way to structure your controller so I don't load the views two times and I don't submit the form by just hitting the route, and so that I pass the data to the view when the form is submitted by clicking the submit.
view section
<div class="content-header-left col-md-6 col-12 mb-1">
<h3 class="content-header-title mb-0 font-14">
<a href="#">
<i class="close icon-arrow-left font-16 px-50 float-left></i>
</a> Manage <?php echo $merchantId; ?>
</h3>
//we have to replace mechantId with fullname in database
</div>
function in controller
class SubMerchantController extends AppController {
public $permission_dashboard=array();
public $plugin = null;
public $modelClass = 'SubMerchant';
public $lang="admin";
public $merchantId="";
public $imageFolder="merchants";
public $module="Multiple Pickup Points";
public $helpers = array('Html','Form','Time','Text');
public function initialize()
{
parent::initialize();
$this->loadModel('Merchants.SubMerchant');
$this->loadModel('Masters.CompanyType');
$this->loadModel('Masters.Plan');
$this->loadModel('UserContact');
$this->loadComponent('Paginator');
$this->loadComponent('Flash');
$this->loadComponent('Search.Prg', [ 'actions' => ['index'] ]);
$this->loadComponent('Common');
$this->loadComponent('Upload');
}
public function beforeRender(Event $event){
$action=isset($this->request->params['action'])?$this->request->params['action']:"";
$loginMerchant=$this->request->session()->read('Auth.FrontUser.id');
if($action=="sortOrder" || $action=="view" || $action=="ajaxPlanData"){
$this->viewBuilder()->layout('ajax');
}elseif($loginMerchant!=""){
$this->viewBuilder()->layout('merchantAfterLogin');
}else{
$this->viewBuilder()->layout('adminAfterLogin');
}
}
public function beforeFilter(Event $event){
$this->CommonAuthCheck();
$merchantId=$this->request->query('merchant_id');
//Login Merchant Check
$loginMerchant=$this->request->session()->read('Auth.FrontUser.id');
if($merchantId==""){
$merchantId=$loginMerchant;
}
if($merchantId<=0){
//$this->redirect('/');
//exit;
}
$this->merchantId=$merchantId;
$this->set('merchantId',$merchantId);
$this->set('modelName', 'SubMerchant');
$this->set('lang', 'admin');
$this->set('module', $this->module);
$this->set('pluginFolder', 'Merchants');
$this->set('imageFolder', $this->imageFolder);
}
public function index(){
$sort=isset($this->request->query['sort'])?$this->request->query['sort']:"";
$direction=isset($this->request->query['direction'])?$this->request->query['direction']:"";
$query = $this->{$this->modelClass}->find('search', $this->{$this->modelClass}->filterParams(array_map('trim',$this->request->query)));
$this->paginate = array(
'limit' => $this->request->query('listing')!=""?$this->request->query('listing'):"10",
'fields'=>array('id','parent_id','full_name','email','brand_name','merchant_code','register_pincode','status','last_login','created','updated'),
'conditions'=>array('parent_id'=>$this->merchantId),
'order'=>array($this->modelClass.'.full_name'=>'asc'),
);
$this->Paginator->settings = $this->paginate;
$this->set('datas',$this->paginate($query));
//debug($this->paginate($query));
//exit;
$searchArray=array(
'status'=>(isset($this->request->data['status']) && $this->request->data['status'])?$this->request->data['status']:"",
'full_name'=>(isset($this->request->data['full_name']) &&
$this->request->data['full_name'])?$this->request->data['full_name']:"",
'email'=>(isset($this->request->data['email']) && $this->request->data['email'])?$this->request->data['email']:"",
'merchant_code'=>(isset($this->request->data['merchant_code']) &&
$this->request->data['merchant_code'])?$this->request->data['merchant_code']:"",
);
$listHeadings=array(
'ID'=>array('field'=>'id','icon'=>SORT_ICON),
'Name'=>array('field'=>'full_name','icon'=>SORT_ICON),
'Email'=>array('field'=>'email','icon'=>SORT_ICON),
'Brand',
'Date'=>array('field'=>'created','icon'=>SORT_ICON),
);
$this->set(compact('searchArray','listHeadings','sort','direction'));
}
database table
phpmyadmin table
Basic CakePHP:
Interacting with Views
https://book.cakephp.org/3/en/controllers.html#interacting-with-views
Example:
function index() -> set data to -> index.ctp
function view() -> set data to -> view.ctp
Concat strings:
simple: echo $name . ' ' . $surname; // John Doe
complex: ```echo sprintf('%s %s', $name, $surname); // John Doe
Set data from controller:
$this->set('full_name', sprintf('%s %s', $name, $surname));
Print full_name in view:
echo $full_name
CakePHP way:
$data = $this->Users->find()->first();
$this->set(compact($data));
// view:
echo $data->full_name
I need help fetching data from database and display them in view.
My DB name is directory and table usernames that includes:id,title,body,slug,username,platform,gender,age and created_at.
I used foreach to display all posts from database, but i want to display now a specific post based on platform.
How can i do it?
This is the code i use to display all usernames from the database ordered by id:
<div class="col-md-6 mb-4">
<div class="card">
<div class="card-body" style="height: 130px;">
<h5 class="card-title"><?php echo $username_data['title']; ?></h5>
<p class="card-text"><?php echo word_limiter($username_data['body'], 24); ?></p>
</div>
<div class="card-footer text-muted">
<div class="row">
<div class="col-6">
<small>Created at: <?php echo $username_data['created_at'];?></small><br>
<strong>Is <?php echo $username_data['gender'];?></strong>
</div>
<div class="col-6 text-right">
View full message
</div>
</div>
</div>
</div>
</div>
This is my model:
<?php
class Usernames extends CI_Controller{
public function index(){
$data['title'] = 'Lastest Posts';
$data['posts'] = $this->post_model->get_usernames();
$this->load->view('templates/header');
$this->load->view('usernames/index', $data);
$this->load->view('templates/footer');
}
public function view($slug = NULL){
$data['post'] = $this->post_model->get_usernames($slug);
$query = $this->db->get('usernames');
if(empty($data['post'])){
show_404();
}
$data['title'] = $data['post']['title'];
$this->load->view('templates/header');
$this->load->view('usernames/view', $data);
$this->load->view('templates/footer');
}
public function create(){
$data['title'] = 'Create Post';
$this->form_validation->set_rules('title','Title','required');
$this->form_validation->set_rules('body','Message','required');
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('age','Age','required');
$this->form_validation->set_rules('gender','Gender','required');
$this->form_validation->set_rules('platform','Platform','required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('usernames/create', $data);
$this->load->view('templates/footer');
} else {
$this->post_model->create_username();
redirect('usernames');
}
}
public function snapchat(){
$data['title'] = 'Lastest Posts';
$data['posts'] = $this->post_model->get_usernames();
$this->load->view('templates/header');
$this->load->view('usernames/snapchat', $data);
$this->load->view('templates/footer');
}
}
Model:
<?php
class Post_model extends CI_Model{
public function __construct(){
$this->load->database();
}
public function get_usernames($slug = FALSE){
if($slug === FALSE){
$this->db->order_by('usernames.id', 'DESC');
$query = $this->db->get('usernames');
return $query->result_array();
}
$query = $this->db->get_where('usernames', array('slug' => $slug));
return $query->row_array();
}
public function create_username(){
$slug_link = substr(str_replace(['+', '/', '='], '', base64_encode(random_bytes(16))), 0, 16);
$slug = url_title($this->input->post('title').'-'.$slug_link);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'body' => $this->input->post('body'),
'platform' => $this->input->post('platform'),
'age' => $this->input->post('age'),
'gender' => $this->input->post('gender'),
'username' => $this->input->post('username')
);
return $this->db->insert('usernames', $data);
}
}
Everything is working fine, but i don't know really how to fetch those data.
I need that in this specific page ('telegram.php'), show all rows that includes Telegram from platform.
As mentioned before, my database is structured like this:
directory(DB Name)
usernames(table name)
->id->title->body->slug->username->platform->gender->age->created_at
I am new in CI and I have make login system but I am trying to show user profile data in username and email are show on user profile view page. I am to much try but I cant solve this issue. Here is my code.
Can one tell me about how to show user profile data in profile view page? I have too much trying but no solution is available for showing a user profile data in codeigniter.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class UserLogin extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper(array('form', 'url'));
$this->load->model('login_model');
}
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->view('UserLoginPage');
}
public function userLoginProcess()
{
// $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
// echo "login reached";
$this->form_validation->set_rules('username', 'Username', 'required|alpha|trim');
$this->form_validation->set_rules('password', 'Password','required');
$this->form_validation->set_error_delimiters("<p class='text-danger'>","</p>");
$this->session->set_flashdata("<p class='text-danger'>","</p>");
if ($this->form_validation->run() ){
//username aur password araha hay
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->model('login_model');
//$loginObj session ko check variable haa..!
$loginObj = $this->login_model->login_valid($username,$password);
if($loginObj){
// print_r($loginObj->password);
$this->session->set_userdata('userSessionObj', $loginObj);
//print_r($loginObj);
$this->load->view('userDashboard');
}
else{
// echo "<script>alert('UserName And Passowrd Are Wrong....!!!! ');</script>";
// $this->session->set_flashdata('error', 'Invalid Username and Password');
$this->load->view('UserLoginPage');
// echo "<script language=\"javascript\">alert('Username And Password Are Worng');</script>";
$this->session->set_flashdata('error','<p class="text-danger"> you entered invalid username and password');
} // end of else
} // end of public function
else
{
$this->load->view('userLoginPage');
} // end of else
} //end of function
//logout function Start
public function logout()
{
$this->session->sess_destroy();
$this->session->unset_userdata('username','password');
return redirect("userLogin");
}
//logout function End
public function register()
{
$this->load->view('registered');
} //end of register function
public function preRegister()
{
$this->form_validation->set_rules('username', 'Username', 'required|alpha|trim|min_length[5]|max_length[12]|is_unique[user.username]');
$this->form_validation->set_rules('email', 'email','required|valid_email|is_unique[user.email]');
$this->form_validation->set_rules('password', 'Password','required');
$this->form_validation->set_rules('confirmpassword', 'ConfirmPassword','required|matches[password]');
$this->form_validation->set_error_delimiters("<p class='text-danger'>","</p>");
if($this->form_validation->run())
{
$store = array(
'username' => $this->input->post('username'),
'email' => $this->input->post('email'),
'dateOfbirth' => $this->input->post('dateOfbirth'),
'password' => $this->input->post('password'),
'confirmpassword'=> $this->input->post('confirmpassword'),
'gender' => $this->input->post('gender')
);
$this->login_model->insert_mod($store);
redirect('UserLogin/index');
} // end of if form_validation
else
{
$this->load->view('registered');
} // end of else
} //end of preRegister function
public function employess() // employes of add ka page view kr rha haaaa
{
$this->load->view('userDashboard');
} // employes of add ka page view kr rha haaaa
public function proEmployess()
{
// $this->load->view('addEmployess');
// $this->load->view('addEmployess');
$employessData = array(
// 'id' => $this->input->post('id'),
'name' => $this->input->post('name'),
'address' => $this->input->post('address'),
'department' => $this->input->post('department')
);
$this->login_model->employess_add($employessData);
redirect('UserLogin/employess');
}
public function myProfile(){
// $myProfile = $this->session->userdata();
$this->load->view('headerDashboard.php');
$myProfiledata ['profiles'] = $this->login_model->profileVeiw();
$this->load->view('myProfileView', $myProfiledata);
$this->load->view('footerDashboard.php');
}
// public function myProfile(){
//
// $this->load->view('headerDashboard');
// //$myProfiledata ['datas'] = $this->login_model->veiw_Employess();
// //$employessRecord['datas'] = $this->login_model->veiw_Employess();
// $this->load->view('myProfileView');
// $this->load->view('footerDashboard');
//
// }
}
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_model extends CI_Model{
public function login_valid($username ,$password)
{
$q = $this->db->where(['username'=>$username, 'password'=>$password])
->get('user');
if( $q->num_rows() )
{
//return pori row ho rhe ha jo database sa arhe haaa
return $q->row();
// return $q->row()->id;
// return TRUE;
}
else
{
return FALSE;
}
}
public function insert_mod($store)
{
$this->db->insert('user', $store);
}
public function employess_add($employessData)
{
$this->db->insert('employessRecord',$employessData);
}
public function view_employess(){
$query = $this->db->get('employessrecord');
return $query;
}public function profileVeiw(){
$queries = $this->db->get('user');
//$queries = $this->session->userdata();
// print_r($queries);
return $queries;
}
}
<div class="col-xl-6">
<div class="card" >
<div class="card-header">
<h4>Profile Details</h4>
</div><br>
<?php foreach($profiles->result() as $profile):?>
<div class="col-md-8">
<label for="name">Username:</label>
<?php echo $profile->username;?>
</div><br><br>
<div class="col-md-8">
<label for="address">Email:</label>
<?php echo $profile->email;?>
</div><br><br>
<div class="col-md-8">
<label for="address">Passowrd:</label>
<?php echo $profile->password;?>
</div><br><br>
<div class="col-md-8">
<label for="address">Gender:</label>
<?php echo $profile->gender;?>
</div><br><br>
<?php endforeach; ?>
</div>
</div>
There is opening tag php tag
so you received the data from form and inserted it in database $this->login_model->insert_mod($store) .
when you call myProfile function you get data in $myProfiledata ['profiles'] = $this->login_model->profileVeiw(); here and passed it to view. if this is correct then first try to print $myProfiledata before passing to the view if everything ok there then try to print $profiles on the "myProfileView" view.
$this->session->userdata('userSessionObj');
here you can check the session data
i try to save a form_multiselect but it dont save and the value dont select. I hope you can help me please.
Edit: Its working now but only with a single select. I cant select more as one options.
I try this
view
<div class="form-group">
<label class="col-sm-2 control-label" for="field-1"> Team</label>
<div class="col-sm-4">
<?= form_multiselect('teams_id[]', dd2menu('teams', array('teams_id' => 'title')), set_value('teams_id[]', $item->teams_id), 'class="form-control"') ?>
</div>
</div>
Controller
public function manage($id = NULL) {
$data = array();
if ($id) {
$this->{$this->model}->{$this->_primary_key} = $id;
$data['item'] = $this->{$this->model}->get();
if (!$data['item'])
show_404();
} else {
$data['item'] = new Std();
}
$this->load->library("form_validation");
$this->{$this->model}->custom_select = 'users.*, teams.title as teams';
$this->{$this->model}->joins = array( 'teams' => array('teams.teams_id = users.teams_id', 'inner'));
if ($this->form_validation->run() == FALSE)
$this->load->view($this->module . '/manage', $data);
else {
$this->users_model->teams_id = $this->input->post('teams_id');
$this->{$this->model}->save();
redirect('admin/' . $this->module);
}
}
Model
class Users_model extends CI_model
{
public $_table = 'users';
public $_primary_keys = array('user_id');
}
I cant find the error because its working if i one select. But i can select more as one options.
If found the fix in the other code from NikuNi.
Now its save 1 or 1,2 in the Database.
Controller
if( is_array( $this->input->post('teams_id') ) ) {
$this->{$this->model}->teams_id = join(",", $this->input->post('teams_id'));
} else {
$this->{$this->model}->teams_id = $this->input->post('teams_id');
}
$this->form_validation->set_rules('teams_id[]', 'teams_id', 'trim');