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.
Related
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 am new to CodeIgniter
I have the following code in my Model:
public function saveVar() {
$variable_limit=$this->input->post('var');
$data = array(
'variable_limit'=>'$variable_limit'
);
$this->db->insert('mytable',$data);
}
this should fetch Data from html form and insert a row 'variable_limit' into the table 'mytable', the code doent work I see no change in the mysql database.
Assumed that the first code works, I want to display this data to the view, I wrote this Code in my Controller:
function postVar(){
$this->load->model('tool');
$this->tool->saveVar();
}
I am trying to transfer the data to the model calling 'tool' by calling the saveVar() which is implemented in my model, does this Code work?
Edit: this is the Code in my View:
<form id="myform" action="<?php echo base_url()."tools/file";?>" method="post" onsubmit="return validateData();">
<div> Variable : <input type="number" id="var" name="var" value="<?php echo isset($_POST['var']) ? $_POST['var'] : '' ?>" /></div>
Thanks, Elmoud
Do like this:-
Controller:-
public function postVar(){
$variable_limit=$this->input->post('var');
$data = array(
'variable_limit'=>$variable_limit
);
$this->tool->saveVar($data);
}
Model:-
public function saveVar($data) {
$this->load->model('tool');
$this->db->insert('mytable',$data);
}
Controller:
function postVar(){
$this->load->model('tool');
$this->tool->saveVar();
}
Model
public function saveVar() {
$variable_limit=$this->input->post('var');
$data = array(
'variable_limit'=>$variable_limit
);
$this->db->insert('mytable',$data);
}
It need not use quotes for variables.Just use $variable_limitas such.
Controller:
function postVar(){
$this->load->model('tool');
$this->tool->saveVar();
}
Model:
public function saveVar() {
$data = array(
'variable_limit'=>$this->input->post('var')
);
$this->db->insert('mytable',$data);
}
I am using codeigniter as my PHP framework, and I keep getting this error when I submit my from to post to my database.
You must use the "set" method to update an entry
I am not exactly sure what that means, from the other posts I have looked at, everyone says that the datamapper needs to have a value assigned to the object.
Being that I am new to all this, could someone give me a better explaniation.
Here is my code where it says I have the error:
class Add_book extends CI_Model {
public function add_book($data){
$this->db->insert('ST_ITM', $data);
}
}
?>
Thank you.
You need to do something like this Example Only
class Add_book extends CI_Model {
public function add_book(){
// 'book_name' would be the name of your column in database table
$data = array(
'book_title' => $this->input->post('book_title'),
'book_author' => $this->input->post('book_author'),
'book_name' => $this->input->post('book_name')
);
$this->db->set($data);
$this->db->insert($this->db->dbprefix . 'ST_ITM');
}
}
On view the input would be like example
<input type="text" name="book_name" value="" />
<input type="text" name="book_title" value="" />
<input type="text" name="book_author" value="" />
Best to use a data array in model. and then load model function in success part of form validation Library
To all who arrive here, you do NOT have to use set in your insert queries:
https://www.codeigniter.com/userguide3/database/query_builder.html#inserting-data
$data = array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
);
$this->db->insert('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
The error is a result of misconstructed insert data (must be an array) or failing to write the correct Active Record query like for example not adding the table name before the insert array.
But sir, when do we use set?
When you need to bypass automatic escaping during updates or replacings for example:
$this->db->set('last_login', 'NOW()', FALSE);
$this->db->update(DB_PREFIX .'user', array('login_attempts' => 0));
The third parameter disabled auto-escaping. This gives us the necessary flexibility when writing Active Record queries.
I got this error when i was passing wrong variable into the insert statement.
For example :
function($a){
$this->db->insert($aa); <-- error !!
}
So I solved it by passing in the right variable, which is $a.
Also make sure your insertion array is correctly formatted as $a = array('columnname'=>'value');
For Example I want to insert data, so I have to do code like below -
My View File(Login_form.php)
<label>Username:</label> <input type="text" name="username" value="">
<label>Password:</label> <input type="password" name="password" value="">
My Model File(Model_login.php)
class Model_login extends CI_Model {
public function insert_entry()
{
$data= array(
'username'=>$this->input->post('username'), // here username and password are database fields.
'password'=>$this->input->post('password'),
);
$this->db->insert('login', $data); //here login is my database table's name
}
}
Controller File(Login.php)
class Login extends CI_Controller {
public function index()
{
$this->load->view('Login_form'); //to load view file
}
public function getLoginValues()
{
$this->load->model('Model_login'); //to load Model file
$data=$this->Model_login->insert_entry();//to load method of Model file
}
}
It works fine, check it.
in your model.
public function SetFoo($bar) {
$data = [
'YourColumnName' => 'Yes'
];
// Using Query Builder
$this->set($data);
$this->where('id',$bar);
$this->update();
}
This will throw the above error if you do not add tot he top of the model the following
protected $allowedFields = ['YourColumnName'];
The columns can exist in the model but are not accessible using set update unless its in the allowedfields section (its like a private/public for the code to see the column)
the problem is in your model.
so you have to check if the array $data is empty or not
like this :
class Add_book extends CI_Model {
public function add_book($data){
if ( $data != null)
$this->db->insert('ST_ITM', $data);
}
}
?>
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?
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.