how to use insert_batch to add multiple data in database by using for loop please help me as i am very new to codeigniter.
My controller
class Student extends CI_Controller {
public function _construct()
{
parent::_construct();
//call model
$this->load->model("StudentModel","m");
}
function index()
{
$this->load->view("index");
}
function savedata()
{
$data = array(
array(
'studentname' => 'Reddy' ,
'gender' => 'Male' ,
'phone' => '456879'
),
array(
'studentname' => 'Yalla' ,
'gender' => 'Female' ,
'phone' => '12345678'
)
);
//mean that insert into database table name tblstudent
$this->db->insert_batch('tblstudent',$data);
//mean that when insert already it will go to page index
redirect("Student/index");
}
function edit($id)
{
$row=$this->m->getonerow($id);
$data['r']=$row;
$this->load->view('edit',$data);
}
function update($id)
{
$id=$this->input->post('id');
$data=array(
'studentname' => $this->input->post('studentname'),
'gender' => $this->input->post('gender'),
'phone' => $this->input->post('phone')
);
$this->db->where('id',$id);
$this->db->update('tblstudent',$data);
redirect("Student/index");
}
function delete($id)
{
$id=$this->db->where('id',$id);
$this->db->delete('tblstudent');
redirect("Student/index");
}
}
Model
class StudentModel extends CI_Model{
function _construct()
{
parent::_construct();
}
function gettable()
{
$query=$this->db->get('tblstudent');
return $query->result();
}
function getonerow($id)
{
$this->db->where('id',$id);
$query = $this->db->get('tblstudent');
return $query->row();
}
}
First of all you don't have to add direct access to database in controller. For all database access code you have to create model.
in your above code you added database access code in direct controller,which is logically wrong as per MVC architecture.
Below is code as per MVC and all database access code resides in Model.
Your main question for batch insert is in function insert()
of model.Please go through it.
<?php
class Student extends CI_Controller {
public function _construct()
{
parent::_construct();
//call model
$this->load->model("StudentModel","m");
}
function index()
{
$this->load->view("index");
}
function savedata()
{
$stdarray = array();
$stdarray[] = array('studentname' => 'Reddy' ,'gender' => 'Male' ,'phone' => '456879');
$stdarray[] = array('studentname' => 'Yalla' ,'gender' => 'Female' ,'phone' => '12345678');
//mean that insert into database table name tblstudent
$this->db->insert_batch('tblstudent',$data);
$this->m->insert($stdarray);
//mean that when insert already it will go to page index
redirect("Student/index");
}
function edit($id)
{
$row=$this->m->getonerow($id);
$data['r']=$row;
$this->load->view('edit',$data);
}
function update($id)
{
$updateArray = array();
$updateArray['studentname'] = $this->input->post('studentname');
$updateArray['gender'] = $this->input->post('gender');
$updateArray['phone'] = $this->input->post('phone');
$whereArray = array();
$whereArray['id'] = $id;
$this->m->updateRow($updateArray,$whereArray);
redirect("Student/index");
}
function delete($id)
{
$whereArray = array();
$whereArray['id'] = $id;
$this->m->deleteRow($whereArray);
redirect("Student/index");
}
}
?>
Model:
class StudentModel extends CI_Model{
function _construct()
{
parent::_construct();
}
function gettable()
{
$query=$this->db->get('tblstudent');
return $query->result();
}
function getonerow($id)
{
$this->db->where('id',$id);
$query = $this->db->get('tblstudent');
return $query->row();
}
function insert($insrtArray)
{
$success = $this->db->insert_batch('tblstudent', $insrtArray);
}
function updateRow($updateArray,$whereArray)
{
if(!empty($whereArray))
{
foreach ($whereArray as $key => $value) {
$this->db->where($key,$value);
}
}
$this->db->update('tblstudent',$updateArray);
}
function deleteRow($whereArray)
{
if(!empty($whereArray))
{
foreach ($whereArray as $key => $value) {
$this->db->where($key,$value);
}
}
$this->db->delete('tblstudent');
}
}
?>
Important: morever you have to use escape function for all inputa which are direct send to database for maintain security from SQL injection.
Related
I have a $send variable in my model. I want to use it on the controller. But I get an error. How can I call it to the controller?
Model:
public function register_user($send)
{
if($this->emailVerify()) {
$send = array(
'tipo' => 'Error.'
);
return true;
} else {
return false;
}
Controller:
public function __construct()
{
parent::__construct();
$this->send;
}
public function register()
{
$this->load->model('users');
$this->users->register_user();
$this->load->view('signup', $this->send);
}
You can declare a private variable, say send in your model and make getter and setter in your model class in an encapsulated way to get the value in the controller, like below:
Snippet:
Model:
<?php
class Yourmodel extends CI_Model{
private $send;
function __construct() {
parent::__construct();
$this->send = [];
}
public function register_user($send){
if($this->emailVerify()) {
$this->send = array(
'tipo' => 'Error.'
);
return true;
}
return false;
}
public function setSendValue($value){
$this->send = $value;
}
public function getSendValue(){
return $this->send;
}
}
Controller:
<?php
class Controller extends CI_Controller{
private $send;
public function __construct(){
parent::__construct();
$this->send = [];
}
public function register(){
$this->load->model('users');
if($this->users->register_user()){
$this->send = $this->users->getSendValue();
}
$this->load->view('signup', $this->send);
}
}
Replace your code modal and controller as follows:
You need not to declare $send in modal definition, as you are not passing any value while calling the same modal function.
modal positive return can be array $send itself
Catch value of modal function
Modal :
public function register_user()
{
if($this->emailVerify()) {
$send = array(
'tipo' => 'Error.'
);
return $send;
} else {
return false;
}
Controller:
public function __construct()
{
parent::__construct();
$this->send;
}
public function register()
{
$this->load->model('users');
$send = $this->users->register_user();
//print_r($send); // You will get data here
$this->load->view('signup', $this->send);
}
Model
public function register_user($send = "")
{
if($this->emailVerify()) {
$send = array(
'tipo' => 'Error.'
);
return $send;
} else {
return false;
}
Controller
public function __construct()
{
parent::__construct();
$this->send;
}
public function register()
{
$this->load->model('users');
$sendRes = $this->users->register_user(); //now you can use this $send response variable
$this->load->view('signup', $this->send);
}
I'm quite new to php and there's no error appearing but appereantly, can't update my data in the database.
The controller
public function update_user_view() {
$this->load->helper('form');
$user_id = $this->uri->segment('3');
$query = $this->db->get_where("users",array("user_id"=>$user_id));
$data['records'] = $query->result();
$data['old_user_id'] = $user_id;
$this->load->view('user_edit',$data);
}
public function update_user(){
$this->load->model('user_model');
$data = array(
'user_id' => $this->input->post('user_id'),
'name' => $this->input->post('name'),
'nickname' => $this->input->post('nickname'),
'email' => $this->input->post('email'),
'hadd' => $this->input->post('hadd'),
'gender' => $this->input->post('gender'),
'cpnum' => $this->input->post('cpnum'),
'comment' => $this->input->post('comment')
);
$old_user_id = $this->input->post('old_user_id');
$this->user_model->update($data,$old_user_id);
$query = $this->db->get("users");
$data['records'] = $query->result();
$this->load->view('user_view',$data);
}
the model
<?php
class User_model extends CI_Model {
function __construct() {
parent::__construct();
}
public function insert($data) {
if ($this->db->insert("users", $data)) {
return true;
}
}
public function delete($user_id) {
if ($this->db->delete("users", "user_id = ".$user_id)) {
return true;
}
}
public function update($data,$old_user_id) {
$this->db->set($data);
$this->db->where("user_id", $old_user_id);
$this->db->update("users", $data);
}
}
?>
Just do
$this->db->where("user_id", $old_user_id);
$this->db->update("users",$data);
Remove $this->db->set($data); from update method of model. This is not required as update query data section is used to set table records.
I get the error :
Fatal error: Call to undefined method select::form() in public_html/opunletter/application/controllers/Welcome.php on line 44.
when i run this. what might be the reason.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index()
{
//load the database
$this->load->database();
//load the model
$this->load->model('select');
//load the method of model
$data['h']=$this->select->select();
$data['a']=$this->select->archieve();
$data['n']=$this->select->latest();
$id=$this->input->get("id");
$data['f']=$this->select->load($id);
//return the data in view
$this->load->view('welcome_message', $data);
}
public function login()
{
$this->load->view('userlogin');
}
public function submit()
{
$data = array(
'from' => $this->input->post('from'),
'to' => $this->input->post('to'),
'title' => $this->input->post('title'),
'openletter' => $this->input->post('openletter')
);
$this->load->model('select');
//Transfering data to Model
$this->select->form($data);
}
} ?>
My model
<?php
class Select extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//we will use the select function
public function Select()
{
//data is retrive from this query
$query = $this->db->get('country');
return $query;
}
public function archieve()
{
//data is retrive from this query
$query = $this->db->query("SELECT * FROM country WHERE archieve=1;");
return $query;
}
public function latest()
{
//data is retrive from this query
$query = $this->db->query("SELECT * FROM country WHERE latest=1;");
return $query;
}
public function load($id)
{
//data is retrive from this query
$query = $this->db->select('*')
->from('country')
->where('open_id', $id)
->get();
return $query;
}
public function form($data){
// Inserting in Table(students) of Database(college)
$query = $this->db->insert('user_openletter', $data);
return $query;
}
}
?>
I have implemented the login logic in an MVC application; I want to see if the user has filled the username and passowrd incorrectly and if so I want to show a notifictaion in the view; so I'm passing this information via $data['er']; but for some reason it is not catching this data:
Please let me know if my question is clear or not; and if any clarification is needed, please let me know which part is ambiguous
My code:
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$GLOBALS['er'] = False;
}
public function index() {
$data['er']=$GLOBALS['er'];
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
public function validate_credentials() {
$this->load->model('user_model');
$query = $this->user_model->validate();
if ($query) {
$data = array(
'username' => $this->input->post('username'),
);
$this->session->set_userdata($data);
redirect('project/members_area');
} else {
$GLOBALS['er'] = TRUE;
$this->index();
}
}
}
Don't use GLOBALS you can just use a private variable in your class.
Create the variable above your __construct function like private $er
In your __contruct function set the default value
Set and get in your public function using $this->er
Implemented in your code:
class Login extends CI_Controller {
private $er;
public function __construct() {
parent::__construct();
$this->er = FALSE;
}
public function index() {
$data['er']= $this->er;
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
public function validate_credentials() {
$this->load->model('user_model');
$query = $this->user_model->validate();
if ($query) {
$data = array(
'username' => $this->input->post('username'),
);
$this->session->set_userdata($data);
redirect('pmpBulletin/members_area');
//die(here);
} else {
$this->er = TRUE;
$this->index();
}
}
}
My small project with CodeIgniter (wich is only to get familiar with it. It's actually like their tutorial's example) it stoped working, giving me no output or errors even that in the index.php is set to developement...
So I tried to debug it myself with some echo's
And I found that here stops logging
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
echo 'This is echoed';
$this->load->model('news_model');
echo 'This wont be echoed';
}
/*(class continues)*/
}
And my news_model.php looks like this:
<?php
class News_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_news($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get('news'{});
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}
public function set_news()
{
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
}
Any idea what I'm doing wrong?
-EDIT-
public function __construct()
{
echo '__construct()';
$this->load->database();
echo 'after__construct()';
}
None of them are echoed...
find 1
$this->db->get('news'{}); // try to del {}
first parameters is table name
The second and third parameters enable you to set a limit and offset clause
Original codeignitor tutorial has this:
public function get_news($slug = FALSE)
{
if ($slug === FALSE)
{
$query = $this->db->get('news'); // <----------------------------
return $query->result_array();
}
$query = $this->db->get_where('news', array('slug' => $slug));
return $query->row_array();
}