Models in codeigniter - codeigniter

In CodeIgniter, I designed a page, which there is a login form, and a simple home page.
The validation I did client side validation only.
view login.php :-
<form name="login" id="login" action="<?php echo base_url() ?>login/success" onsubmit="return validatelogin()" method="post">
... HTML
<input type="text" id="username" name="username" />
<input type="password" id="passwrd" name="passwrd">
Javascript validation in the view page "login.php",
function validatelogin(){
var x=document.forms["login"]["username"].value;
var y=document.forms["login"]["passwrd"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
if (y==null || y=="")
{
alert("Password field must be filled out");
return false;
}
if(x!="monisha" && y!="monisha"){
alert("Username and Password incorrect");
return false;
}
return true;
}
Controller - login.php :-
class Login extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('session');
}
function index(){
$this->load->view('login');
}
function success() {
$data = array('username' => "monisha");
$this->session->set_userdata($data);
redirect ('home');
}
}
I created the table "login", which is having the username and password fields.
I need to validate it using the database and the database query. Can anybody please assist me on what all changes I have to do in controller file, and the view page, to get this done.?

Learn form validation in CI first! http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html
You need to change this accordingly.
In Controller:
$this->load->helper(array('form')); #no need to do this if already loaded
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required||is_unique[table_name.column_name]');
$this->form_validation->set_rules('passwrd', 'Password', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('view_name');
}
else
{
redirect('controller/function', 'refresh');
}
In view page:
<?php echo validation_errors(); ?>

Related

Get specific row from database with codeigniter

I'm new to this so i have this silly question.I want to make a login form and when the user logs in i want to show all his information in the screen(username attack defence...).The thing is i don't know how to call the specific function i've made because in my controller calls function index() by default and not the function guser().
login view
<h2>Login</h2>
<?php if($error==1){ ?>
<p>Your Username/password did not match </p>
<?php } ?>
<form action="<?=base_url()?>index.php/Users/login" method="post">
<p>Username: <input name="user" type="text" /> </p>
<p>Password: <input name="password" type="password" /> </p>
<p><input type="submit" value="Login" /></p>
</form>
users controller
<?php
class Users Extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('User');
}
function index(){
$data['users']=$this->User->get_users();//sto model post tha kalesei tin sinartisi get_posts
$this->load->view('Post_index',$data);
}
function guser($id){
$data['user']=$this->User->get_user($id);
$this->load->view('Post_index',$data);
}
function login(){
$data['error'] = 0; // simenei oti den exei errors
if($_POST){
$user=$this->input->post('user',true);//pairnei to username p edose o xristis(einai idio me to $_POST)
$password=$this->input->post('password',true);//pairnei to password p edose o xristis
//$type=$this->input->post('charact',true);
$user1=$this->User->login($user,$password);//,$type);
if(!$user1){
$data['error']=1;
}else{
$this->session->set_userdata('id',$user1['id']);
$this->session->set_userdata('user',$user1['user']);
$this->session->set_userdata('name',$user1['name']);
$this->session->set_userdata('money',$user1['money']);
$this->session->set_userdata('attack',$user1['attack']);
$this->session->set_userdata('defence',$user1['defence']);
$this->session->set_userdata('level',$user1['level']);
$this->session->set_userdata('xp',$user1['xp']);
redirect(base_url().'index.php/Users');
}
}
$this->load->view('Login',$data);
}
function registerSam(){
if($_POST){
$data=array(
'user'=>$_POST['user'],
'name'=>$_POST['name'],
'password'=>$_POST['password'],
'charact'=>"Samurai",
'money'=>400,
'attack'=>10,
'defence'=>5,
'level'=>0,
'xp'=>0
);
$userid=$this->User->create_user($data);
}
}
function registerKnight(){
if($_POST){
$data=array(
'user'=>$_POST['user'],
'name'=>$_POST['name'],
'password'=>$_POST['password'],
'charact'=>"Knight",
'money'=>400,
'attack'=>5,
'defence'=>10,
'level'=>0,
'xp'=>0
);
$userid=$this->User->create_user($data);
}
}
}
?>
user model
<?php
class User Extends CI_Model{
function create_user($data){
$this->db->insert('unityusers',$data);
}
function login($user,$password){
$where=array(
'user'=>$user,
'password'=>$password,
);
$this->db->select()->from('unityusers')->where($where);
$query=$this->db->get();
return $query->first_row('array');
}
function get_user($id){
$this->db->select()->from('unityusers')->where(array('id'=>$id));
$query=$this->db->get();
return $query->first_row('array');
}
function get_users($num=20,$start=0){// tha paroume 20 posts k tha arxisoume apo to proto
$this->db->select()->from('unityusers')->limit($num,$start);
$query=$this->db->get();
return $query->result_array();
}
}
?>
Although you have accepted the answer I like to point out some basic functionality for you to more improved code.
Different technique to load the data to view from controller:
function index(){
$users = $this->User->get_users();
$this->load->view('Post_index',['users' => $users, 'any_other_data' => $any_other_data ... and so on]);
}
When you get post data in the controller then you should check for a validation first inside your login function. And in login functionality it will be more useful. setting-validation-rules
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
Loading a model and it's function. You don't need to use uppercase in this as give below.
$this->load->model('user');
$this->user->get_users();
Your registration Function registerSam you don't need to create an array of post data Codeigniter will provide the functionality to get all your post data at once. To remove unnecessary data from that array use unset.
$your_post_array = $this->input->post();
To call a specific function made, you can access it via a browser using the link
BASE_URL/index.php/ControllerName/MethodName
So, in your case to call the guser method, the url would be
BASE_URL/index.php/users/guser
Hope that helps.
You have an error in guser function on the controller. You don't need to passs any argument to the function. You can get ID of user from the session, which was actually added in session once the user has entered correct credentials.
Also after login, you need to redirect user to guser function instead of users. Because as per your controller users function dosen't exist.
Change From
redirect(base_url().'index.php/Users');
To
redirect(base_url().'index.php/guser');
Please check below for solution.
function guser(){
$data['user']=$this->User->get_user($this->session->userdata('id'));
$this->load->view('Post_index',$data);
}
Let me know if it not works.

How to use x-editable with CodeIgniter?

I would like to understand using x-editable in my CodeIgniter first project. I tried to read x-editable docs but I'm beginner in JavaScript too so I can't understand
I make simple controller to collect data from JavaScript but I didn't complete it or data not updated in database.
$('#username').editable({
type: 'text',
pk: 1,
url: '/post',
title: 'Enter username'
});
How to get submitted data in controller or model to process database update query
I want to passing data submitted from x-editable to model to update it in database.
You can follow this simple steps
Assume that $userId = 5 ; $username = "admin";
Consider you html look like this
<a type="text" name="username" onclick="setEditable(this);" data-pk="<?php echo $userId ;?>" data-placeholder="Enter Username" data-name="username" data-type="text" data-url="<?php echo site_url();?>user/updateUserName" data-value="<?php echo $username ;?>" data-prev="admin" data-title="Enter Username"><?php $username; ?></a>
In Javascript code write following
$.fn.editable.defaults.mode = 'inline';
function setEditable(obj) {
$(obj).editable({
emptytext: $(obj).attr('data-value'),
toggle: 'dblclick',
mode: 'inline',
anim: 200,
onblur: 'cancel',
validate: function(value) {
/*Add Ur validation logic and message here*/
if ($.trim(value) == '') {
return 'Username is required!';
}
},
params: function(params) {
/*originally params contain pk, name and value you can pass extra parameters from here if required */
//eg . params.active="false";
return params;
},
success: function(response, newValue) {
var result = $.parseJSON(response);
$(obj).parent().parent().find('.edit-box').show();
$(obj).attr('data-value', result.username);
$(obj).attr('data-prev', result.username);
},
error: function(response, newValue) {
$(obj).parent().parent().find('.edit-box').hide();
if (!response.success) {
return 'Service unavailable. Please try later.';
} else {
return response.msg;
}
},
display: function(value) {
/*If you want to truncate*/
var strName = strname !== '' ? strname : $(obj).attr('data-value');
var shortText = '';
if (strName.length > 16)
{
shortText = jQuery.trim(strName).substring(0, 14).split("").slice(0, -1).join("") + "...";
}
else {
shortText = strName;
}
$(this).text(shortText);
}
});
$(obj).editable('option', 'value', $(obj).attr('data-value'));
}
In Controller site
<?php
class User extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function updateUserName()
{
$this->load->model('user_model');
if ($this->input->is_ajax_request()) {
$valueStr = $this->input->get_post('value') ? $this->input->get_post('value') : '';
$new_nameStr = trim($valueStr);
$result_arr['username'] = $new_nameStr;
$userId = $this->input->get_post('pk') ? $this->input->get_post('pk') : '';
$data['username'] = $new_nameStr;
$result_arr['username'] = $new_nameStr;
$this->user_model->userUpdateFunction($data, $userId);
}
echo json_encode($result_arr);
exit;
}
}
You can change editable mode , i have set inline only
First of all, this question is about AJAX and JavaScript/jQuery, not Codeigniter.
Basically, the code that you wrote is about posting data with AJAX. First, you need to create a controller and model, then you can post data with AJAX. I'm adding a sample code:
Controller file:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Sample extends CI_Controller {
function __construct() {
parent::__construct();
$this ->load ->model('modelfolder/sample_model');
}
public function index() {
$this->sample_model->sampleFunction();
}
}
Model File:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Sample_model extends CI_Model {
function sampleFunction() {
$data = array('fieldName' => $this->input->post('userName', TRUE));
$this->db->where('id', $this->input->post('userId', TRUE));
$this->db->update('tableName', $data);
return true;
}
}
routes.php File:
$route['demoPost'] = 'controller_folder/sample';
View File's HTML part:
<form id="sampleForm">
<input type="text" name="userId" />
<input type="text" name="userName" />
</form>
View File's AJAX part:
$(document).ready(function(){
$("#sampleForm").submit(
function(){
$.ajax({
type: "POST",
url: "<?php echo site_url('demoPost'); ?>",
data: $("#sampleForm").serialize(),
});
});
});

Magento 1.8.0.0: Add custom payment method redirecting to a new page

I'm working locally with magento 1.8.0.0. I succeeded to create a custom payment method. The method is appearing to the list of payment method at the "Payment Information" during the checkout. The problem is that when I select it, it automatically brings a credit card form, which is not what I want. What I want is to select it and once I click the "continue" button I get redirected to another php page containing my own form.
Solution by OP.
For you who want to redirect to the gateway and want the gateway to redirect back to your controller's action method, here is how things work:
In the file app/code/local/Yourcompany/Yourmodule/Model/PaymentMethod.php ,do as follow:
class Yourcompany_Yourmodule_Model_PaymentMethod extends Mage_Payment_Model_Method_Abstract{
protected $_code = "yourmodule";
protected $_isGateway = true;
protected $_canAuthorize = true;
protected function _getCheckout() {
return Mage::getSingleton('checkout/session'); }
public function getOrderPlaceRedirectUrl() { return Mage::getUrl(yourmodule/index/youraction', array('_secure' => true)); }}
In the line return Mage::getUrl(yourmodule/index/youraction', array('_secure' => true)); , "index" means that my controller php file is named IndexController.php. You may change the name as you wish.
In the file app/code/local/Yourcompany/Yourmodule/controllers/IndexController.php , you may code as follow:
class Yourcompany_Yourmodule_IndexController extends Mage_Core_Controller_Front_Action{
public function indexAction() {
$this->loadLayout();
$block = $this->getLayout()->createBlock('Mage_Core_Block_Template','yourmodule',array('template' => 'yourmodule/redirect.phtml'));
$this->getLayout()->getBlock('content')->append($block);
$this->renderLayout(); }
/*In the response action, you may code like this*/
public function responseAction() {
$status=$_REQUEST['param1'];
$orderNo=$_REQUEST['param2'];
if(somecondition)
{
/*update order status */
$ordera = Mage::getModel('sales/order')->loadByIncrementId($orderNo);
$ordera->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, true)->save();
$this->_redirect("checkout/onepage/success");
}
else
{
$this->_redirect("checkout/cart/");
}
} }
The indexAction() is redirecting to a template redirect.phtml file. This file will collect some parameters to send to the gateway (order number, customer name, total money, etc.). You may put that phtml file here:
app/design/frontend/base/default/template/yourmodule/redirect.phtml
Its content may be coded as follow:
<?php
$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getSingleton('sales/order')->loadByIncrementId($orderId);
$order_amount=$order->getGrandTotal();
$customerData = Mage::getSingleton('customer/session')->getCustomer();
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling(); //oder getDefaultShipping
$address = Mage::getModel('customer/address')->load($customerAddressId);
$customer_name=$address->getFirstname().' '.$address->getLastname();
$customer_email=$customerData->getEmail();
?>
<form name="myjs" method="post" action="http://yourgatewayaddreshere">
<input type="hidden" name="customername" value="<?php echo $customer_name; ?>">
<input type="hidden" name="customermail" value="<?php echo $customer_email; ?>">
<input type="hidden" name="TotalMoney" value="<?php echo $order_amount; ?>">
</form>
<script type="text/javascript">
document.myjs.submit();
</script>

CodeIgniter update page - Simple CRUD website assistance required

After looking through the forums and starting to try to create a basic CRUD website I am currently struggling to have a page that updates the articles as follows. If someone could kindly tell me where I am going wrong, I will be most greatful. I am getting a 404 error at 'news/input'
model (at news_model.php)
public function update($id, $data)
{
$this->db->where('id', $id);
$this->db->update('news', $data);
}
controller (news.php)
public function update($id){
$data = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('slug'),
'text' => $this->input->post('text'));
if($this->news_model->exists($id)) {
$this->news_model->update($id, $data);
}
else {
$this->news_model->insert($data);
}
}
html (views/news/input.php)
<h2>Update a news item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/update') ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="slug">Slug</label>
<input type="input" name="slug" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Update an item" />
You get a 404 because your news controller seems to have no method 'input'. Try adding something like this:
public function input(){
// load the form
$this->load->view('/news/input');
}
Note that for updating data you will need to fetch and pass it into the view first, then render the (filled out) form using set_val() and other CI functions.
Currently you're "hardcoding" the HTML form which makes populating and maintaining state (when validation fails) difficult. I suggest you play through the forms tutorial on the CI website.
Edit:
To create a update/insert (upsert) controller change as follows:
Controller:
function upsert($id = false){
$data['id'] = $id; // create a data array so that you can pass the ID into the view.
// you need to differntiate the bevaviour depending on 1st load (insert) or re-load (update):
if(isset($_POST('title'))){ // or any other means by which you can determine if data's been posted. I generally look for the value of my submit buttons
if($id){
$this->news_model->update($id, $this->input->post()); // there's post data AND an id -> it's an update
} else {
$this->news_model->insert($id, $this->input->post()); // there's post data but NO id -> it's an insert
}
} else { // nothing's been posted -> it's an initial load. If the id is set, it's an update, so we need data to populate the form, if not it's an insert and we can pass an empty array (or an array of default values)
if($id){
$data['news'] = $this->news_model->getOne($id); // this should return an array of the news item. You need to iterate through this array in the view and create the appropriate, populated HTML input fields.
} else {
$data['news'] = $this->news_model->getDefaults(); // ( or just array();) no id -> it's an insert
}
}
$this->load->view('/news/input',$data);
}
And amend the $id to the action-url in your view:
<?php echo form_open('news/upsert/'.$id) ?>

codeigniter get returned data variable from model in controller and use it in conditional statement

what is wrong with my search implementation, here what i wish to achieve.
view page(form) -> controller(form data variable) -> model(query database and pass to controller) if there's a result return TRUE else return FALSE -> controller(get data from model) if true display data in table else if FALSE display a no results returned message.
here are my pages:
view:
<form action="<?php echo site_url('retrieve')?>" method="post">
<input type="text" name="id">
....
</form>
model:
public function retrieve($id)
{
$search = "SELECT * FROM table";
$result = $this->db->conn_id->prepare($search);
$result->execute();
if($result->rowCount()>0){
return $query_result = $result->fetchAll(PDO::FETCH_ASSOC);
}
}
controller:
public function retrieve_info()
{
$id = $this->input->post('id'),
$this->load->model('search_model');
$this->search_model->retrieve($id);
$data['query_result'] = $this->search_model->retrieve($id);
$this->load->view('display',$data);
}
First the form action is linking to the retrieve function in the controller. However, from your example there is no retrieve function in your controller, only in your model.
view:
<form action="<?php echo site_url('retrieve')?>" method="post">
<input type="text" name="id">
....
</form>
model:
public function retrieve($id)
{
$search = "SELECT * FROM table";
$result = $this->db->conn_id->prepare($search);
$result->execute();
if($result->rowCount()>0){
return $query_result = $result->fetchAll(PDO::FETCH_ASSOC);
}
}
controller:
public function retrieve()
{
if($_POST){
$id = $this->input->post('id'),
$this->load->model('search_model');
$data['query_result'] = $this->search_model->retrieve($id);
$this->load->view('display',$data);
}else {
//form failed to submit via post
}
}

Resources