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?
Related
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.
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.
I want to select some data in the CodeIgnigher PHP application from the database and want to make some change and insert to another table. I would like to insert as as many as selected records into the IN table. Currently I am getting only one row inserted into the out table.
Can you please point, what is being done wrong here.
My tables are. Out_Table (id, name..) and In_Table (id, name, quantity..).
My Model Code is:
<?php
class ShoppingListM extends CI_Model {
public function getData() {
$query = $this->db->get('products');
return $query->result();
}
function SaveForm($form_data) {
$this->db->insert('SLists', $form_data);
if ($this->db->affected_rows() == '1') {
return TRUE;
}
return FALSE;
}
}
?>
View Code:
<div class="divTable">
<fieldset>
<!-- these will be affected by check all -->
<div class="divRow">Product Name | Quantity | Packages</div>
<div class="divRow"><input type="checkbox" size="100" class="checkall"> Check all</div>
<br>
<?php foreach ($records as $rec) {
?>
<div class="divRow"><input type="checkbox">
<input size="5" type="hidden" value="<? echo $rec->id; ?>" name="id"></input>
<input size="20" type="text" value="<? echo $rec->name; ?>" name="name"></input>
<input size="5" type="text" value="" name="quantity"></input>
<select name="package">
<option name="case">Case</option>
<option name="box">Box</option>
<option name="box">Single Bottle</option>
</select>
</div>
<br>
<?
}
?>
</fieldset>
</div>
<div><input type="submit" name="submit"/></div>
</form>
Controller Code:
class ShoppingListController extends CI_Controller {
public function index() {
//$data['val'] = array("test1", "test2", "test3");
// $this->load->model('HomeModel');
//$data['records'] = $this->HomeModel->getData();
$this->load->model('ShoppingListM');
$data['records'] = $this->ShoppingListM->getData();
$this->form_validation->set_rules('name', 'Name', 'required|max_length[255]');
$this->form_validation->set_rules('qty', 'qty', '');
$this->form_validation->set_rules('package', 'Package', 'required|max_length[128]');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('ShoppingListV', $data);
}
else // passed validation proceed to post success logic
{
// build array for the model
$form_data = array(
'name' => set_value('name'),
'quantity' => set_value('quantity'),
'package' => set_value('package')
);
// run insert model to write data to db
// run insert model to write data to db
if ($this->ShoppingListM->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('ShoppingListController/success'); // or whatever logic needs to occur
}
else
{
echo 'An error occurred saving your information. Please try again later';
// Or whatever error handling is necessary
}
}
well i cannt see where is in_table/out_table in the code u provided yet.
to insert many rows what u want insert_batch
example from doc
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
or u can loop all ur rows from in_table and insert them one by one if its a maintaince job that u dont care about multiple queries
$data= $this->db->get('Out_table');
try
{
if ( $data->num_rows == 0)
throw new Exception('table empty');
foreach( $data->result() as $row)
{
//modifiy the row as u want
$modified=$row;
$q=$this->db->insert('in_table',$modified);
if( ! $q )
throw new Exception('failed to insert row id:'.$row->id);
}
echo $data->num_rows.'rows inserted';
}
catch (Exception $e)
{
echo $e->getMessage();
// Stop method execution with return, or use exit
return;
}
please help me how to display data to the view page after insert query into database.
view page(member_view.php):
<form action="<?php member_controller/insert_info; ?>" method="post">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="submit" name="submit">
</form>
<?php
if($res){
foreach($res as $data){
echo $data['fname'];
echo $data['lname'];
}
}
?>
controller page(member_controller.php):
<?php
class Member_Controller extends CI_Controller {
public function insert_info(){
$data = array('fname' => $this->input->post('fname'),
'lname' => $this->input->post('lname'),
);
$this->load->model('member_model');
$this->member_model->member_posting($data);
$data['username'] = $session_data['username'];
$retrieved_info['res'] = $this->member_model->member_posting($data);
$this->load->view('member_view',$data, $retrieved_info)
}
}
model page(member_model):
<?php
class Member_Model extends CI_Model{
public function member_posting($data=array()){
extract($data);
$query = "INSERT INTO member_table (fname, lname)values ('$fname', '$lname')";
$result = $this->db->conn_id->prepare($query);
$result->execute();
if($result){
$query = "SELECT * FROM member_table WHERE fname = '$fname' AND lname='$lname'";
$result = $this->db->conn_id->prepare($query);
$result->execute();
return $res = $result->fetchAll(PDO::FETCH_ASSOC);
}
}
}
and here would be the pattern:
view(submit form)---->controller(get vars and send to model) --->
model(insert to db and perform select query)--->controller(get the select query results from model)--->view(display the results)
please help me, im just new to codeigniter, hope i can learn from you guys.
This is the way you need to follow.........
View file:member_view.php
<form action="<?php echo ROOT_FOLDER ?>/member_controller/insert_info" method="post">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="submit" name="submit">
</form>
Controller file: member_controller.php
<?php
class Member_Controller extends CI_Controller {
public function insert_info()
{
$data = array(
'fname' => $this->input->post('fname'),
'lname' => $this->input->post('lname'),
);
$this->load->model('member_model');
$this->member_model1->member_posting($data);
$retrieved_info = array();
$retrieved_info['res'] = $this->member_model2->member_posting($data);
$this->load->view('member_view',$data, $retrieved_info)
}
}
Model file: member_model1.php
class Member_Model extends CI_Model{
public function member_posting_inserting($data){
$this->insert_helper('member_table',$data);
}
public function member_posting_retrieving($data){
$query = "SELECT * FROM member_table WHERE fname = '$data['fname']' AND lname='$data['lname']'";
$res=$this->db->query($query);
if($res->num_rows()>0){
return $res->result("array");
}
return array();
}
}
Insert helper function...............
public function insert_helper($table_name, $data_array){
$this->db->insert($table_name,$data_array);
return $this->db->insert_id();
}
This
$this->load->view('member_view',$data, $retrieved_info)
in your case won't do the trick. Read about the views here: http://ellislab.com/codeigniter/user-guide/general/views.html
2nd parameter is data array. 3rd parameter can be TRUE or FALSE, deciding if the view has to be rendered or returned as string.
This should do the trick:
$this->load->view('member_view', $retrieved_info);
Edit:
Just noticed your member_posting() doesn't return anything. It should return $res;
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.