Insert one row using different models/pages - CodeIgniter - php

I'm new to CodeIgniter and I'm building a simple I/O website. I have only one database, say test and only one table results, that looks like this:
screenshot of the table "results"
I have two views personal.php and songs.php. In the first one I collect the data values to be inserted into the fields 2,3, and 4, and the rest of the values are collected in the second view. They are then inserted into the table via their relevant models, personal_model and songs_model.
Now obviously, they will be inserted into 2 different rows which is not what I want. What is the trick here? How should I manage it? So far I have thought of getting the last ID but I have no idea how to do it. Thanks in advance!
personal.php (first view)
<?php echo validation_errors(); ?>
<?php echo form_open('data/personal'); ?> //passes the data to the controller that loads the personal_model.php
"some input fields"
<button type="submit" name="submit">Submit Data</button>
songs.php (second view)
<?php echo validation_errors(); ?>
<?php echo form_open('data/songs'); ?> //passes the data to the controller that loads the songs_model.php
"some input fields"
<button type="submit" name="submit">Submit Rating</button>
personal_model.php (first model)
<?php
class Personal_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function insert_personal()
{
$this->load->helper('url');
$data = array(
'age' => $this->input->post('user_age'),
'education' => $this->input->post('user_edu'),
'twitter' => $this->input->post('user_twitter'),
'facebook' => $this->input->post('user_facebook')
);
return $this->db->insert('results', $data);
}
}
songs_model.php (second model)
<?php
class Ratings_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function insert_ratings()
{
$this->load->helper('url');
#$this->load->database();
$data = array(
'score' => $this->input->post('rating'),
'song1' => $this->input->post('rnd1'),
'song2' => $this->input->post('rnd2')
);
return $this->db->insert('results', $data);
}
}

Your Controller Function should be like this.
public function personal()
{
$lastInsertedID = $this->Personal_model->insert_personal();
$this->session->set_userdata("personalID",$lastInsertedID);
}
Set the last inserted id into session in your above controller function which should be return from your Personal_model. Here is code.
public function insert_personal()
{
$this->load->helper('url');
$data = array(
'age' => $this->input->post('user_age'),
'education' => $this->input->post('user_edu'),
'twitter' => $this->input->post('user_twitter'),
'facebook' => $this->input->post('user_facebook')
);
$this->db->insert('results', $data);
return $this->db->insert_id();
}
Then update your existing row in your insert_ratings function instead of insert record. Here is code.
public function insert_ratings()
{
$data = array(
'score' => $this->input->post('rating'),
'song1' => $this->input->post('rnd1'),
'song2' => $this->input->post('rnd2')
);
$personalID = $this->session->userdata("personalID");
$this->db->where("id",$personalID);
$this->db->update('results', $data);
return $this->db->affected_rows();
}
Then no new record will insert into table while submit your song.php form it will update the existing one.

Related

Pre-populate update form with data from the database

UPDATE:
If, in the view, I do <?php echo $customer->first_name; ?> it outputs the first-name correctly.
On the same view file 'value' => set_value($customer->first_name) outputs nothing.
I am making a "Customers" CRUD application in CodeIgniter 3. I have an update form that I want to pre-populate with the data corresponding to the customer, already existent in he database.
The model looks like this:
class Customer extends CI_Model {
/*Lots
of
code*/
public function getAllCustomers($customer_id) {
$query = $this->db->get_where('customers', array('id' => $customer_id));
if ($query->num_rows() > 0) {
return $query->row();
}
}
}
The controller looks like this:
class Home extends CI_Controller {
/*Lots
of
code*/
public function edit($customer_id){
$this->load->model('Customer');
$customer = $this->Customer->getAllCustomers($customer_id);
$this->load->view('update', ['customer'=>$customer]);
}
}
In the view file (update.php) I have:
<?php echo form_input('first_name', '', [
'type' => 'text',
'id' => 'first_name',
'class' => 'form-control',
'value' => set_value($customer->first_name),
'placeholder' => 'First name',
]);
?>
The customer's first_name, although existent in the the database column called "first_name" does not pre-populate the form.
Why is this?
always debug using$this->db->last_query() to check your query executing correctly
if last_query() doesnot return nothing make sure your set 'save_queries' => TRUE in app/config/database.php
your query might return more than one result
change your model like this
public function getAllCustomers($customer_id) {
$q = $this->db->get_where('customers', array('id' => $customer_id));
log_message("error",$this->db->last_query()); //use this to get the complied query for debugging purpose
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
return FALSE;
}
if you are sure that your query might return only one result then check $customer_id has data in it
public function getAllCustomers($customer_id) {
if($customer_id){
$q = $this->db->get_where('customers', array('id' => $customer_id),1); //specify the limit if you want to get only one row
log_message("error",$this->db->last_query()); //use this to get the complied query for debugging purpose
if ($q->num_rows() > 0) {
return $q->row();
}
}
return FALSE;
}
That's how to do it:
<?php echo form_input('first_name', set_value('first_name', $customer->first_name),[
'id' => 'first_name',
'class' => 'form-control'
]);
?>

a database error occurred column 'title' cannot be null

here is my site_model code
get all data from database and insert data into database using Html form
please help i don't know where i do mistake
class Site_model extends CI_Model
{
public function __construct()
{
}
// get all data from database
public function get_records()
{
$query = $this->db->get('user_data');
return $query->result();
}
// add records into database by form
public function add_record($formData)
{
$this->db->insert('user_data', $formData);
}
}
than i load model into controller and get values in an array. and after create an array to send form values into database
class Site extends CI_Controller
{
var $data = array();
public function __construct()
{
parent::__construct();
$this->load->model('Site_model');
}
public function index()
{
//get data into array from model
$data = $this->data;
$data['user_info'] = $this->Site_model->get_records();
// get data from html form and send to database
$formData = array(
'title' => $this->input->post('post_title'),
'description' => $this->input->post('post_descrip')
);
// send record to model
$this->Site_model->add_record($formData);
$this->load->view('crud_viw', $data);
}
}
my view code look like this
<!DOCTYPE html>
<html>
<head>
<title>Crud</title>
</head>
<body>
// Html form to send values to database
<form method="post">
<input type="text" placeholder="Title" name="post_title"></input>
<input type="text" placeholder="Description" name="post_descrip"> </input>
<button type="submit">Submit</button>
</from>
</body>
</html>
Change your index method as below. You only have to enter data when post event occur
public function index()
{
//get data into array from model
$data = $this->data;
$data['user_info'] = $this->Site_model->get_records();
if($this->input->post()){ //<--- add this condition
// get data from html form and send to database
$formData = array(
'title' => $this->input->post('post_title'),
'description' => $this->input->post('post_descrip')
);
// send record to model
$this->Site_model->add_record($formData);
}
$this->load->view('crud_viw', $data);
}
in your database your column "title" should be not null..so mark "title" as not null in database..
Hope it helps..
The simple way to prevent getting the a database error occurred column 'title' cannot be null is use ternary operator(?:).If you have not posted value it will inserts empty string.
$formData = array(
'title' => isset($this->input->post('post_title'))?$this->input->post('post_title'):" ",
'description' => isset($this->input->post('post_descrip'))?$this->input->post('post_descrip'):" "
);
Hope it works.

codeigniter update method not working

I am new to codeigniter and trying to write an update function to update information in my database. I've gone through a few tutorials but for some reason my code is not working! Any tips or assistance would be greatly appreciated. I'm just testing with two fields right now, name and email, and I get a blank page when I go to my update view.
Here is my model method:
function get_by_id($id){
return $this->db->get_where('table',array('id'=>$id));
}
function update($id){
$attributes=array(
'name'=> $this->input->post('Name'),
'email'=> $this->input->post('Email')
);
return $this->db->where('id',$id)
->update('table',$attributes);
}
And here is my relevant controller code:
function edit(){
$data['row']=$this->Mymodel->get_by_id($id)->result();
$data['name']= 'Name';
$data['email']='Email';
$this->load->view('updateview', $data);
}
function update($id){
$this->load->model('Mymodel');
$this->Mymodel->update($id);
if($this->input->post()){
redirect('kittens/view/'.$id, 'refresh');
}
And here is my update view:
<?php echo form_open('kittens/update/')
echo form_hidden('id', $row[0]->id);
foreach($attributes as $field_name){
echo '<p>' . $field_name;
echo form_input($field_name, $row[0]->$field_name) . '</p>';
}
echo form_submit('', 'Update');
echo form_close();
?>
Any help would be appreciated! Not sure what specific part is giving me the trouble!
Use the following template:
Controller:
public function updateData(){
....
$data = array(
"columnName" => $columnValue
);
$whereValue = $someNumber;
$this->model_name->updateTable($data, $wherevalue);
...
}
Model:
public function updateTable($data, $whereValue){
$this->db->where('columnName', $whereValue);
$this->db->update('tableName', $data);
}
the first thing is that the model "MyModel" isn't loaded on the "edit" method in the controller.
If you're planning to use that specific model in every function of your controller you should load it in the constructor (so you don't have to load it every time).
Using$this->input->post('Name') in a model is a bad idea. You should receive that data in the controller process it (if you have to) and then send it to the method in the model.
I don't know if you can "chain" the db methods like this in codeigniter:
$this->db->where('id',$id)->update('table',$attributes);
try this:
$this->db->where('id',$id);
$this->db->update('table',$attributes);
Hope that helps
////////////model for update/////////////
public function update_customer_contacts($where, $data){
return $this->db->update('customer_contacts', $data, $where);
}
///////////////////update customer///////////////////
public function update_customer()
{
$data = array(
'company_name'=>$this->input->post('company_name'),
'address' =>$this->input->post('address'),
'telephone' =>$this->input->post('telephone'),
'fax' =>$this->input->post('fax'),
'email' =>$this->input->post('email'),
'website' =>$this->input->post('website'),
);
$res= $this->customer_model->update_customer(array('customer_id' => $this->input->post('customer_id')), $data);
;
echo json_encode($this->input->post());
}

Codeigniter approach to save all posted values in bidimensional array

I have a multiform and I need to insert several values to 4 user,news,feed,lat (maybe 6) tables that are related by some ID this is because an event needs all this information.
my form:
<form method="post" action="<?php echo base_url();?>controller/save" name="event"/>
<label>User Name</label>
<!--#####FOR TABLE USER#####-->
<input type="text" name="name">
<input type="text" name="name">
<!--#####FOR TABLE NEWS#####-->
<input type="text" name="title">
<input type="submit" value="body"/>
<!--#######################
OTHER TABLE FIELDS ...
#######################
-->
<input type="submit" value="save"/>
</form>
Now I would like to pass a bidimensional array to event model and then depending on value insert to corresponding table
controller event.php
class Event extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->model('event_model');
}
public function save()
{
/** Is it possible to fill this bidimensional array with for loops???? **/
$arr_data = array(
array("person", $this->input->post("name") , $this->input->post("address")),
array("news" , $this->input->post("title") , $this->input->post("body" )),
array("feed" , $this->input->post("id_feed") , $this->input->post("main" )),
array("lat" , $this->input->post("lat1" , $this->input->post("lat" ))
);
$this->event_model->insert_tables($arr_data);
}
}
Now How to receive the array in model and do the insert how to declare event_model?
class Event_model extends CI_Model {
function Event_model ()
{
parent::__construct();
}
function insert_tables($arr_data) {
if( "person" )
$this->db->insert(person_tb ,
}
}
Is it necessary to use implode or something, Is there a better way to do this multiple inserting?
I would do something like this...
$person = array('name' => $this->input->post("name"), 'address' => $this->input->post("address"));
$news = array('title' => $this->input->post("title"), 'body' => $this->input->post("body"));
$feed = array('id' => $this->input->post("id_feed"), 'main' => $this->input->post("main"));
$lat = array('lat1' => $this->input->post("lat1"), 'lat' => $this->input->post("lat"));
if($this->person_model->insert($person)) {
$person_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
if($this->news_model->insert($news)) {
$news_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
if ($this->feed_model->insert($feed)) {
$feed_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
if($this->lat_model->insert($lat)) {
$lat_id = $this->db->insert_id();
} else {
// handle the problem of not having an id for this entity...
}
Sounds really complicated...why not have a model for each entity and pass the right fields to the right model? Or create a library that inserts/updates each of your models?

how to get the value of form input box in codeigniter

value of FORM INPUT Help!!
//this is just a refrence of $nm and $fid from test_model//
$data['fid']['value'] = 0;
$data['nm'] = array('name'=>'fname',
'id'=>'id');
say i have one form_view with
<?=form_label('Insert Your Name :')?>
<?=form_input($nm)?>
and a function to get single row
function get($id){
$query = $this->db->getwhere('test',array('id'=>$id));
return $query->row_array();
}
then in controller.. index($id = 0)
and somewhere in index
if((int)$id > 0)
{
$q = $this->test_model->get($id);
$data['fid']['value'] = $q['id'];
$data['nm']['value'] = $q['name'];
}
and mysql table has something like 1. victor, 2. visible etc. as a name value
but here its not taking the value of name and id from form_input and not showing it again in form_view in same input box as victor etc so to update and post it back to database...
anyone please help!!
and please be easy as I am new to CI!!
Based on your comment to my first answer, here is a sample of a Controller, Model and View to update a user entry pulled from a table in a database.
Controller
class Users extends Controller
{
function Users()
{
parent::Controller();
}
function browse()
{
}
function edit($id)
{
// Fetch user by id
$user = $this->user_model->get_user($id);
// Form validation
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'required');
if ($this->form_validation->run())
{
// Update user
$user['name'] = $this->input->post('name', true);
$this->user_model->update_user($user);
// Redirect to some other page
redirect('users/browse');
}
else
{
// Load edit view
$this->load->view('users/edit', array('user' => $user));
}
}
}
Model
class User_model extends Model
{
function User_model()
{
parent::Model();
}
function get_user($user_id)
{
$sql = 'select * from users where user_id=?';
$query = $this->db->query($sql, array($user_id));
return $query->row();
}
function update_user($user)
{
$this->db->where(array('user_id' => $user['user_id']));
$this->db->update('users', $user);
}
}
View
<?php echo form_open('users/edit/' . $user['user_id']); ?>
<div>
<label for="name">Name:</label>
<input type="text" name="name" value="<?php echo set_value('name', $user['name']); ?>" />
</div>
<div>
<input type="submit" value="Update" />
</div>
<?php echo form_close(); ?>
It's hard to see the problem from your snippets of code, please try and give a little more information as to the structure of your app and where these code samples are placed.
Presume in the last code listing ('somewhere in index') you are getting $id from the form, but you define the ID of the form input box as 'id' array('name'=>'fname','id'=>'id') rather than an integer value so maybe this is where the problem lies.
Where does the $data array get passed to in the third code listing?
From your question I think you want to display a form to edit a person record in the database.
Controller code
// Normally data object is retrieved from the database
// This is just to simplify the code
$person = array('id' => 1, 'name' => 'stephenc');
// Pass to the view
$this->load->view('my_view_name', array('person' => $person));
View code
<?php echo form_label('Your name: ', 'name'); ?>
<?php echo form_input(array('name' => 'name', 'value' => $person['name'])); ?>
Don't forget to echo what is returned from form_label and form_input. This could be where you are going wrong.

Categories