I'm currently developing an MLM Website using Codeigniter Framework.
And I am working on registration now. I can register successful with referral user
The problem is every 3 registration using my referral username/id i need to run another query because in 1st and 2nd referral I earned 200. and in 3rd user will refer i will only earn 100.
How can I do that in Codeigniter? anyone done this? please help
Let me throw some light on this
So lets say you make a post for every registration, the post goes to a class names registration and a register method, and the referral id runs as a session (refID). Also, you have a registration model, this is what you should likely do:
class registration extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('registration_model');
}
//ensue to check for the existence of the refID session before processing
function register(){
if($_POST){
//first run form validation
//you should have auto loaded the form_validation library
//and created a rules function that carries the form rules
$rules = $this->rules();
$this->form_validation->set_rules($rules);
if($this->form_validation->run() == FALSE){
//load view here
}else{
//first, get post data
//then get the number of registration done by user using the refID
//if registration is greater than 2, set earnings to 100
//set earnings to 200
//then proceed to insert registration and do something else
//get post data, assumed post data
$name = $this->input->post('name');
$email = $this->input->post('email');
//get number of registrations
$numOfRegs = $this->registration_model->getRegByRefID();
//set the earnings from the number of registrations
$earning = $numOfRegs < 3 ? 200 : 100;
//please note that the for $numOfRegs = 4, $earnings will be 100, as this was not specified in the question
//at this point, you have set the earnings, you can proceed to do whatever you wish to do, perhaps insert the records
//please note that this code block just explains what you can likely do after setting the earnings
$insert = array(
"name" => $name,
"email" => $email,
"earning" => $earning
);
$this->registration_model->insert($array);
// then do anything else
}
}else{
//load view here
}
}
}
Now this is how your registration model will look like this
class Registration_model extends CI_Model{
function __construct(){
parent::__construct();
}
function getRegByRefID(){
$refID = $this->session->refID;
return $this->db->get_where('mydb', array("refID" => $refID))->num_rows();
}
}
I hope this explains what you really wants, and helps you. If you find any difficulty, kindly comment and lets sort it out.
Related
normally I would return a JSON with a message about the status of my function, if error or success, but, this time, I'm with a trouble. I'm developing an application with PHP to register students to join the university, the database has a lot of tables to insert data about the student, things like, parents, student address, student course, course value and much more, so, after the user fill all the form fields and press submit, I do a lot of insert and updates, like 10 inserts in differents tables, my question is, how I can return a message of status after all this operation, if one of my inserts fail, how I can handle it to give to the user a feedback about this? I'm a little new to CodeIgniter, here one example of how I do my inserts in my save function at controller:
$studentData = array(
'FIELD1' => $data1,
'FIELD2' => $data2,
'FIELD3' => $data3
);
$this->mymodel->insert('STUDENTTABLE', $data);
I do so many inserts like this above. how can I return a feedback of every insert and at final of my save function to return a success message?
There are many techniques to know that you inserted successfully or not.
You can use this $this->db->affected_rows() function to know after query it will return you affected row. you can simply use if condition to it to check.
return ($this->db->affected_rows() != 1) ? false : true;
$this->db->insert_id(); this function will return you the last inserted id so depends on that you can do further coding.
The Best Way to find the query execution result is Transactions. I am not adding much description here because you can find it in the user guide of CodeIgniter. Here is the link. I am just adding an example of it so you can get the little idea of it.
$this->db->trans_begin();
// Your query
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
I personally prefer the transaction for insert and update query. It is very useful if you are adding multiple data or doing more than one activity regarding the database.
Now For Passing the Message to the View.
If you use the above technique and return true or false from model to controller then it would be easy to get message according to that.
I am adding sample model, controller and view code for you.
public function your_model_function(){
// Do query
// Return TRUE or FALSE
}
public function your_controller_function(){
$data = $this->input->post(); // Your post data. You can use get also.
$result = $this->your_model->your_model_function($data);
//Normal Pass the variable to the view [OPTION-1]
if($result == TRUE){
$msg = "Successfully Insert.";
}else {
$msg = "Failed To Insert.";
}
$this->load->view('your_view',['msg'=>$msg]); // Change this code as per your requierment.
//Now For Flash Data [OPTION-2]
if($result == TRUE){
$this->session->set_flashdata('feedback', 'Successfully Insert.');
}else {
this->session->set_flashdata('feedback', 'Failed To Insert.');
}
//redirect to your page
return redirect('your_controller/your_controller_function'); // Change this code as per your requierment.
}
View For [Option-1]
<?php echo $msg; ?>
//OR
<?php print_r($msg); ?>
View For [Option-2]
<?php
if ($feedback = $this->session->flashdata('feedback')){
echo $feedback;
}
?>
// Set flash data in your controller
$this->session->set_flashdata('message_name', 'This is my message');
// After that you need to used redirect function instead of load view such as
redirect("admin/signup");
// Get Flash data on view in view page
$this->session->flashdata('message_name');
For more reference, you can visit:this
tutorialspoint
When updating the user's details, the database will update all the information, although when the page refreshes, the previous information is showing and it does not update unless the user has logged out and logged back in. I am new to CodeIgniter. Could someone please help me or tell me what to do, I would really appreciate it. Thanks in advance.
This is my Model:
function updateAccount($submit_userid, $submit_phone, $submit_address, $submit_eaddress) {
$this->db->where("intMemberID", $submit_userid);
$this->db->update("tblMembers", array(
"strPhoneNumber" => $submit_phone,
"strMemberAddress" => $submit_address,
"strEmailAddress" => $submit_eaddress,
));
}
This is my Controller:
class UpdateController extends CI_Controller {
public function updateAccount() {
$this->load->model('userModel');
$data['userdata'] = $this->session->userdata('userobject');
$submit_userid = $this->input->post('userid');
$submit_phone = $this->input->post('phone');
$submit_address = $this->input->post('address');
$submit_eaddress = $this->input->post('eaddress');
$this->userModel->updateAccount($submit_userid, $submit_phone, $submit_address, $submit_eaddress);
$this->load->view('updateView', $data);
}
}
because you show the old data obtained from the last session. read data directly from database and show it in the view
Your user data is being fetched from the session, rather than the database, you have :
$data['userdata'] = $this->session->userdata('userobject');
This data is put into the session on user login, most likely, thus your problem. You need to change source of the data to
$data['userdata'] = $this->userModel->returnAccount($this->user_id);
or whatever method you have for retrieving the data, to fetch it from your database. Do you have any returnAccount methods in your model? I assume you are not the one who wrote it.
I want to have a delete button underneath blogs entered just by the owner of the current profile, I have tried implementing a deleteMyBlog function but no joy so far. whats the best way to go about this?
Here is my view. I know I would need but some delete button here but I'm not sure how to fit around my current foreach loop:
<?foreach($blogs AS $viewData):
$delete = $viewData['id'];
{
$id = $viewData->id;
$title = $viewData->title;
$body = $viewData->body;
$username = $viewData->username;
$date = $viewData->date;
?>
<b> <?=$title?></b>
<p><?=$body?></p>
<p>posted by:<?=$username?></p>
<p>date: <?=$date?></p>
<?=anchor("blog/deleteMyBlog/$delete", 'delete')?>
<hr>
<?
}
?>
My model:
class Blogmodel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
function deleteMyBlog($id)
{
$this->db->where(array('id' => $id));
$this->db->delete('blogs');
}
public function get_last_ten_entries()
{
$query = $this->db->get('blogs', 10);
return $query->result();
}
public function insert_entry()
{
$this->title = $this->input->post('title');
$this->body = $this->input->post('text');
$this->username = $this->session->userdata('username');
$this->date = date("Y-m-d");
$this->db->insert('blogs', $this);
}
}
Controller:
class Blog extends CI_Controller {
public function _construct()
{
parent::__construct();
$this->load->model('Blogmodel','Blog');
$this->load->model("profiles");
}
function deleteMyBlog($id) {
$this->blogs->deleteBlog($id);
redirect('blog');
}
public function index()
{
$username = $this->session->userdata('username');
$viewData['username'] = $username;
$this->load->model('Blogmodel');
if($this->input->post('act') =='create_post')
{
$this->Blogmodel->insert_entry();
}
$viewData['blogs'] = $this->Blogmodel->get_last_ten_entries();
$this->load->view('shared/header');
$this->load->view('blog/blogtitle', $viewData);
$this->load->view('shared/nav');
$this->load->helper('form');// Load the form helper.
// Lets set the stuff that will be getting pushed forward...
$data = array();
$data['form_open']=form_open();
$data['form_title'] = form_input(array('name' => 'title'));
$data['form_text'] = form_textarea(array('name' => 'text'));
$data['form_hidden'] = form_hidden('act','create_post');
$data['form_submit'] = form_submit('submit','Make Post');
$this->load->view('blog/blogview');
$this->load->view('blog/post', $data);
$this->load->view('shared/footer');
}
}
Thanks again guys
Simplest way is with assigning username to a variable, then with the SQL statement.
Delete from tbl where colname='$username'
That's the way I would do it, other people might have different methods. So all respect to those who would use somethin different
You're getting the error because of this bit:
<?foreach($blogs AS $viewData):
$delete = $viewData['id'];
It should be this:
$delete = $viewData->id;
You're using the exact same data a line later correctly, why are you trying to use $viewData which is an object as an array here, but an object 2 lines later. Other than that the rest of what you're doing there should work fine but it is rather dangerous in practice. If I go to your site and type the url to that controller function with a blogId at the end that blog goes away, at no point are you checking that the user actually should be allowed to delete that blog. Obscurity != Security. Meaning that just because you think people won't find the link doesn't mean they won't.
Personally I save the userId of a logged in user to the session and save the session to the database. Then when I do anything to user records I do a check to ensure the user making the change has the authorization to make that change.
So your delete function would be something like this:
function deleteMyBlog($id)
{
$this->db->where('username',$this->session->userdata('username');
$this->db->where('id',$id);
$this->db->delete('blogs');
}
Also you should be using userId's not usernames for saving to other tables, the indexes work better on numerical ID's as far as I know and it's less overall data in the tables. Saving userId 342 to your blogs table takes up less space than saving username bobsyouruncle3421.
For the record, I know this isn't part of the question but actually deleting things from the database has downsides. Not the least of which is screwing up the indexing and slowing down queries in the long run. A far better solution is adding a status or active column to any tables you may want to delete from and giving them a value of 1 for active and 0 for deleted. Then instead of actually deleting the item you change it's active column to 0. When displaying items you add a check for active = 1 to the display query.
This serves two purposes, first you don't mess up the indexing, the record is never removed just modified so the indexes remain intact. Second and nearly important is you never have the possibility of accidentally deleting something you didn't mean to delete, it is never really gone. So you could "undelete" anything at any time.
I am trying to create wish lists.
There are user and product models. A user has a wish list. A wish list has many products.
The reason I am making it user has wishlist and wishlist has products is so I can have a url like wish_lists/add/:product_id
I created a table called wish_lists with id, user_id, and name.
I also created a table called products_wish_lists with wish_list_id and product_id.
I made here is the wishlists controller:
class WishListsController extends AppController
{
var $hasOne = 'User';
var $hasMany = 'Product';
function beforeFilter()
{
parent::beforeFilter();
$this->Auth->deny('add');
}
function add($id)
{
$user = $this->Session->read("Auth.User");
$this->WishList->set(array(
'User.id' => $user['id'],
'Product.id'=>$id,
'WishList.name'=>'default'
));
if($this->WishList->save())
{
$this->Session->setFlash('This product has been added to your wishlist.', 'flash_good');
}
else
{
$this->Session->setFlash('Error: This product was not added to your wishlist.', 'flash_bad');
}
$this->redirect(array("controller"=>"products","action"=>"view",$id));
}
}
When I go to localhost/wish_lists/add/1 It tells me everytime that it saved. but no data is being added to the database.
Not sure what I am doing wrong?
I never do it that way, I always build a $data array to pass as parameter one to the save function.
I'm not sure, therefore, whether that syntax will allow you to specify the model as you have done, i.e. 'Model.field'. In any case, $this->WishList->save() will only save the Wishlist part.
Better, in my opinion, would be:
$saveData = array(
'User'=>array('id'=>$user['id']),
'Product'=>array('id'=>$id),
'WishList'=>array('name'=>'default'));
$this->WishList->saveAll($saveData);
(or something like that, I've been programming ColdFusion for the last three months and my PHP can be a bit addled)
you are setting the array wrong. it should be $data['User']['id'] = 123; $data['Product']['id'] = 321;
$this->Wishlist->saveAll($data);
There is no point saving the name as that can be found from the product table.
you can have a look at the code here for more ideas https://github.com/Infinitas-Plugins/shop
there is a generic component method in the following link that saves products to the cart or wishlist (different db's) as its pretty much the same thing.
https://github.com/Infinitas-Plugins/shop/blob/master/controllers/components/shop.php#L62
When my users log into the website their first name, last name and ID are missing from the session data because my session data is coded to take post data and submit into the session table in my database.
Because user logs in with email and password in my session data only email appears and nothing else does.
How can I make first name, last name and id appear in my session table in my db? I want to some how grab these details from the database when user is logging in and provide it in my $u_data array so it get's posted upload login success.
Here is my code:
<?php
class Login_Model extends CI_Model {
public function checkLogin() {
$this->db->where('email', $this->input->post('email')); //compare db email to email entered in form
$this->db->where('password', $this->hashed()); //compare db password to hashed user password
$query = $this->db->get('users'); //get the above info from 'user' table
if ($query->num_rows() == 1) { //if number of rows returned is 1
$u_data = array( //new variable with session data
'user_id' => $this->db->insert_id(),
'email' => $this->input->post('email'),
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'logged_in' => TRUE
);
$this->session->set_userdata($u_data); //send data from variable to db session
return TRUE;
} else {
return FALSE;
}
}
public function hashed() { //hashing method
// sha1 and salt password
$password = $this->encrypt->sha1($this->input->post('password')); //encrypt user password
$salt = $this->config->item('encryption_key'); //grab static salt from config file
$start_hash = sha1($salt . $password);
$end_hash = sha1($password . $salt);
$hashed = sha1($start_hash . $password . $end_hash);
return $hashed;
}
}
If you're tracking sessions in your DB, two solutions come to mind.
First, you could select the first/last from the user table and insert it into the session table. This requires changes to your application.
Second, you could set up a view for your application, in which the session table is automatically joined with the appropriate user, but that assumes you already have some unique identifier for which user it is in the session (was that the email address?*). This solution would not require any changes to the application code, but would require changes to the DB, which may be the preferred method depending upon your deployment requirements (or it may not :) ).
* as a side note, if you're using email addresses for unique identifiers, be aware that some people share email addresses as you decide if this is the right solution for you.
It'd be as simple as doing something like:
session_start();
$_SESSION['userdata'] = $u_data;
within your CheckLogin method. The session is just a regular PHP array that happens to be automatically preserved for you. You can put anything you want into it, but you do have do put things into it yourself - PHP won't do it for you.
comment followup:
gotcha. So, you simply modify you class to fetch that information from the DB once the login's authenticated. I don't know how your DB class works, but instead of merely checking if there's a matching row, fetch the first/last name, using a query something like this:
select firstname, lastname
from users
where email=$email and password=$password
If you get a result row, you know it's a valid login, and then you just retrieve the name data. I have no idea how your db class works, but it shouldn't be too hard to get it to do that.
When I'm working with Auth systems in CodeIgniter I have made it a practice to include the "user" object globally in views, and also globally in my controllers, by fetching the userdata in the constructor, like so...
<?php
class My_Controller extends Controller {
private $the_user; //global var to store current user data
function My_Controller() {
parent::Controller();
$data->the_user = $this->ion_auth->get_user(); //get user data
$this->load->vars($data); //load into all views as $the_user "$the_user"
$this->the_user=$data->the_user; //load into private class variable "$this->the_user"
}
At that point $the_user variable object is available in all views by default AND $this->the_user is always available to controller functions. It always represents the user currently logged in.
I am using Ion_auth for authentication and fetching the user, so that piece you would have to fill in.
I actually just constructed a "How-to" to implement extended Controller classes so all the Auth logic is automatically inherited to all "protected" Controllers.
The following solved this issue for me. I looked at one of my old questions on here and used my common sense.
I made this edit to my code.
if ($query->num_rows() == 1) { //if number of rows returned is 1
$user = $query->result();
$u_data = array( //new variable with session data
'user_id' => $user[0]->id,
'email' => $this->input->post('email'),
'first_name' => $user[0]->first_name,
'last_name' => $user[0]->last_name,
'logged_in' => TRUE
);