Im trying use "$this->input->post();" of Codeigniter to do not need specify each field in my form. But im getting troubles when try insert into Database.
Look my controller:
public function cadastrar(){
$var = $this->input->post(null, TRUE);
$this->load->model('m_clientes');
$this->m_clientes->inserir($var);
}
My controller is simplified here because i know how to handle database in codeigniter.
The result of this post was:
Array ( [nome] => Raphael [sobrenome] => Schubert [cpf] => 893.528.432-89 [rg] => 4529875231908472 [telefone] => (53) 2980-5792 [celular] => (53) 9 2180-7529 [rua] => Israel de Almeida [numero] => 859 [cep] => 88.312-000 [bairro] => São Vicente [cidade] => ITAJAÍ [estado] => Santa Catarina [email] => rfswdp#gmail.com [tipo] => pf [cnpj] => 34.827.481/2834-78 [inscricaoestadual] => 34120489032814930128 [razaosocial] => Teste [nomefantasia] => Disney [dataaberturaempresa] => 10/21/15 [proprietario] => Marcos Aurelio )
I normaly use this way to insert:
$data = array(
'user_name' => $this->input->post('user_name',TRUE);
'user_phone' => $this->input->post('user_phone',TRUE);
'user_role' => $this->input->post('user_role',TRUE);
);
$this->name_of_model->inserir($data);
And works...
But i was trying to use just $this->input->post(); to get all fields from form. Because my actualy application will have hundreds of fields and i was trying to do not write each line.
So my model actually was:
public function inserir($var){
if($var!=NULL):
print_r($var);
$this->db->insert('tb_usuarios',$var);
endif;
}
But i`m getting and error saying:
Message: Undefined property: Clientes::$db
and
Message: Call to a member function insert() on null
My table name is: "tb_usuarios"
I changed all fields in database to accept NULL to see if i`m get some field name wrong... but not work...
Any tips??
There is no need to catch the POST var inside $var. You can see POST variable inside the model very well. So all you need to do in the controller is:
public function cadastrar(){
$this->load->model('m_clientes');
$this->m_clientes->inserir();
}
,and inside your model:
public function inserir(){
if( count($this->input->post()) > 0):
$this->db->insert('tb_usuarios',$this->input->post());
endif;
}
The fields names in your form must correspond to the column names inside your table.
The message Message: Call to a member function insert() on null means you forgot to load the database library, just like remiheens said.
But my advice is, to use form validation for your fields, so you may be sure all necessary fields are completed using the required data format for each one of them. Although this may require allot of coding, there is no other safe way from errors on database operations. You cannot trust the user to insert the data correctly, that's why you need form validation.
In here $var = $this->input->post(null, TRUE); you use null. null is not valid input name. name = ''
and this will works $this->input->post('user_name',TRUE);
cz of it has input tag name (name = 'user_name').
We use ,TRUE) next to input post field to allows XSS Protection
$var = $this->input->post(null, TRUE); Is Wrong
while you trying this, it shows
Message: Undefined property: Clientes::$db and Message: Call to a member function insert() on null.
will not work
public function cadastrar(){
$var = $this->input->post(null, TRUE);//will never give valid response
$this->load->model('m_clientes');
$this->m_clientes->inserir($var);
}
Works well
public function cadastrar(){
$this->load->model('m_clientes');
$data = array(
'user_name' => $this->input->post('user_name',TRUE);
'user_phone' => $this->input->post('user_phone',TRUE);
'user_role' => $this->input->post('user_role',TRUE);
);
$this->name_of_model->inserir($data);
$this->load->model('m_clientes');
}
This is because your database isn't loaded into codeigniter instance. ($this->db)
Just try to autoload "database" library (config/autoload.php) or load/connect your database in your model with :
$this->load->database();
Don't forget to edit your config/database.php ;)
I handle hundreds of fields everytime but I also validate basically each one. I always do this:
$customer['name'] = $this->input->post('customer_name');
$customer['age'] = $this->input->post('customer_age');
$customer['country'] = $this->input->post('customer_country');
$customer['city'] = $this->input->post('customer_city');
// validations
if(isAgeValid($customer['age']) == FALSE)
{
echo 'Hold on, your age...hmm check it out!';
return;
}
$this->customers_model->add($customer);
The function that handles the insertion only has this:
public function add($data)
{
$data = $this->security->xss_clean($data);
$this->db->insert('customers', $data);
return $this->db->insert_id();
}
Pretty clean and simple. Now, if you don't want to validate the fields or just want to validate some of them and want to insert the others without validation this is what I purpose based on the previous code:
// validations..
if(isAgeValid());
$customer = array();
foreach($_POST as $key => $value)
$customer[$key] = $value;
$this->customers_model->add($customer);
$data = array(
'user_name' => $this->input->post('user_name');
'user_phone' => $this->input->post('user_phone');
'user_role' => $this->input->post('user_role');
);
$this->load->model('name_of_model');
$this->name_of_model->inserir($data);
Model:
public function inserir($data)
{
$this->db->insert('***', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
}
Related
I am creating a web site. So , I have stored data in the database. Now I want to view data from two different tables. Then I tried a method like below. But , it gives me this error -
Trying to get property 'firstname' of non-object (View: D:\wamp64\www\cheapfares\resources\views\invoices\des.blade.php)
But , clearly firstname is in the database table.
How can I Fix this ??
Controller page. ( InvoicesController.blade.php )
public function userinvoice($terms = '',$invoiceNo = '')
{
$invoice = Invoice::where('invoicereference', $invoiceNo)->get()->first();
$tr = DB::table('termsandconditions')
->where('topic', $terms)->get()->first();
$twoar = [];
$twoar['inv'] = $invoice;
$twoar['trms'] = $tr;
return view('invoices.des', ['twoar' => $twoar]);
}
View page. ( des.blade.php )
{{$twoar['inv']->firstname}}
{{$twoar['trms']->topic}}
Route.
Route::get('/invoice/adminuser-invoice/{invoiceno}', [
'uses' => 'InvoicesController#adminuserinvoice',
'as' => 'invoice.adminuser'
]);
Although casting the response to Array might be a suitable solution, the cause of your exception most likely lies in not having a valid entry in the database.
You can improve your code like this to mitigate that:
public function userinvoice($terms, $invoiceNo)
{
// Load invoice, or throw ModelNotFoundException/404 without valid entries.
$invoice = Invoice::where('invoicereference', $invoiceNo)->firstOrFail();
// load the terms.
$terms = DB::table('termsandconditions')
->where('topic', $terms)->first();
return view('invoices.des', compact('invoice', 'terms'));
}
In this example I made $terms and $invoiceNo obligated arguments in the route. To ensure the query will provide proper results. In addition an Invoice entry is now required with firstOrFail(), the terms is optional. Instead of assigning both variables to an array, I'm sending them both to the view so you can assert their value properly without cluttering using array key access.
Your view:
{{$invoice->firstname}}
{{$terms->topic}}
Try this below code:
public function userinvoice($terms = '',$invoiceNo = '')
{
$invoice = Invoice::where('invoicereference', $invoiceNo)->get()->first();
$tr = DB::table('termsandconditions')
->where('topic', $terms)->get()->first();
return view('invoices.des', ['tr'=>$tr,'invoice'=>$invoice]); //Directly pass the mulitple values into the view
}
And your view page like this:
{{$invoice->firstname}}
{{$tr->topic}}
Its may help for you friend.
I'm making a project where a user can publish/post their own stories and read others' stories. Very simple.
This is my controller method named publish:
public function published()
{
$story = array('author' => $this->session->userdata('username'),
'title' => $this->input->post('title'),
'synopsis' => $this->input->post('synopsis'));
$new_storyid = $this->story_model->new_story($story);
if($new_storyid != NULL)
{
$genre = $this->input->post('genre');
for($temp=0;$temp<count($genre);$temp++)
{
$genres[$temp] = array('story_id' => $new_storyid,
'story_genre_name' => $genre[$temp]);
}
$insert_genre = $this->story_model->new_story_genre($genres);
$tag = $this->input->post('tags');
for($temp=0;$temp<count($tag);$temp++)
{
$tags[$temp] = array('story_id' => $new_storyid,
'story_tag_name' => $tag[$temp]);
}
$content_warning = $this->input->post('content_warning');
for($temp=0;$temp<count($content_warning);$temp++)
{
$content_warnings[$temp] = array('story_id' => $new_storyid,
'story_content_warning_name' => $content_warning[$temp]);
}
//$chapter = array('story_id' => $new_storyid,
//'chapter_number' => 1, 'chapter_title' => $this->input->post('chapter_title'),
//'chapter_content' => $this->input->post('chapter_content'),
//'chapter_number' => 1, 'date_added' => mdate('%Y-%m-%d %h-%i-%s',time()));
//$result = $this->story_model->add_chapter($chapter);
//if($result){
//redirect('account/userprofile_published_stories');}
}
}
This is my model methods for the above controller method:
public function new_story($story)
{
$this->db->select('user_id');
$query = $this->db->get_where('users',array('username' => $story['author']))->result();
foreach($query as $row)
{ $userid = $row->user_id; }
$publish = array('user_id' => $userid,
'story_title' => $story['title'],
'synopsis' => $story['synopsis']);
$this->db->insert('story',$publish);
return $this->db->insert_id();
}
public function new_story_genre($genre)
{
foreach($genre as $row)
{
$this->db->insert('story_genre', $row);}
}
public function add_chapter($chapter){
$this->db->where('story_id', $chapter['story_id']);
return $this->db->insert('chapters', $chapter);
}
I haven't added the other 2 functions for my tags and content warning inserts because i am confused right now. It all works fine, my genre is inserted.
My tables looks like this:
Story tables
In inserting a story in my above method, the first thing i do is insert a new story row in my story table and returns the new_storyid variable.
after that with the new storyid i add the genre,tags,content warning then the chapters.
My question is, what should i return in my methods for inserting the genre,tags,contentwarning?
I forgot this part because every model method ive written so far always returns a variable i needed in my controller. My first thought was to return a TRUE/FALSE variable if insert is successful/fail but barring special circumstances since ive already processed the data its 100% sure to insert successfully. Should i be returning TRUE/FALSE and adding an if statement like:
if($insert_genre){
//insert tags here
if($insert_tags){
//insert content warning here
if($insert_content_warning){
//insert chapters here
//redirect to view here
}
}
}
Or can i just not return anything? and if so, is this a proper/right way?
EDIT: I forgot to mention i haven't yet added form_validation rules before all the inserts. So my function will be nested in multiple if statements.
I just edited my model method:
public function new_story_genre($genre){
$inserted = 0;
foreach($genre as $row){
$this->db->insert('story_genre', $row);
$inserted += $this->db->affected_rows();}
if($inserted == count($genre)){
return TRUE;}else{ return FALSE; }
}
Above compares the number of inserted rows with the number of rows passed into the method. Everytime a row is inserted it adds 1 to the inserted variable. So if my controller passes 3 rows into the method, the inserted variable should also be 3 for a successful insert.
I think you are correct in always returning something. Errors can and do happen for whatever reason, and its a good idea to account for them even if you already validated your data (you never know). Coding practices suggest that more than a couple of nested ifs is bad practice. A personal preference of mine is to check for failure rather than success all the way down the chain until the last lines of the function (if it got that far than everything is good to go).
A scheme like this I usually use:
public function something() {
if (!$insert_genre) {
// add flash error message
// redirect to controller
}
if (!$insert_tags) {
// add flash error message
// redirect to controller
}
if (!$insert_content_warning) {
// add flash error message
// redirect to controller
}
// yay, something went right!
}
In this kindof circumstance it is very procedural. The most important conditions should be first, and if C depends on A, then A should be the first condition.
Unrelated:
It is hard to follow some of your text here, but it also seems like you should look into how you are doing the genres. If the entered genre already exists in the database do you really need to add it? Shouldn't you just use a relationship there storing the id in the main table and joining when displaying?
i am trying to SAVE data of Sizes which is coming from with multiple same name input.
Problem is i am not able to save data. Only last value "sizes" is saving in database.
if ($this->EquipmentType->save($this->request->data['EquipmentType'], false)) {
$id = $this->EquipmentType->getLastInsertId();
$this->loadModel('EquipmentTypesSize');
$sizesArray = $this->request->data['EquipmentType']['size'];
foreach($sizesArray as $val){
$data[] = array('EquipmentTypesSize' => array('sizes' => $val));
}
$this->request->data['EquipmentTypesSize']['equipment_type_id'] = $id;
$this->EquipmentTypesSize->set($this->request->data);
$this->EquipmentTypesSize->save($this->request->data['EquipmentTypesSize']);
$this->Session->setFlash('Equipment type has been added successfully ', 'default', 'success');
$this->redirect(array('controller' => 'equipments', 'action' => 'listequipmenttypes', 'admin' => true));
}
I want to save this as
equipment_type_id | size1
equipment_type_id | size2
equipment_type_id | size3
There are several issues - the call to create that Kai mentioned is one of them.
First, here's your code, but I've added comments in places where I see obvious issues (I many not have caught all of them)
<?php
if ($this->EquipmentType->save($this->request->data['EquipmentType'], false)) {
$id = $this->EquipmentType->getLastInsertId();
$this->loadModel('EquipmentTypesSize');
$sizesArray = $this->request->data['EquipmentType']['size'];
foreach($sizesArray as $val){
$data[] = array('EquipmentTypesSize' => array('sizes' => $val));
// WHERE IS THIS $data VARIABLE USED? It seems it's never used?
}
$this->request->data['EquipmentTypesSize']['equipment_type_id'] = $id;
$this->EquipmentTypesSize->set($this->request->data); // NO NEED TO CALL SET HERE - YOU ALREADY PASS DATA IN AS A PARAM TO SAVE
// YOU MUST CALL CREATE BEFORE ADDING A NEW RECORD
$this->EquipmentTypesSize->save($this->request->data['EquipmentTypesSize']);
// I DON'T THINK $this->request->data['EquipmentTypesSize'] HOLDS THE VALUE YOU THINK IT DOES AT THIS POINT
$this->Session->setFlash('Equipment type has been added successfully ', 'default', 'success');
$this->redirect(array('controller' => 'equipments', 'action' => 'listequipmenttypes', 'admin' => true));
}
Now, it's hard to tell exactly what you're wanting to do, but here's my attempt to write what you intended. If it doesn't work, it should hopefully set you on the right track.
if ($this->EquipmentType->save($this->request->data['EquipmentType'], false)) {
$id = $this->EquipmentType->getLastInsertId();
$this->loadModel('EquipmentTypesSize');
$sizesArray = $this->request->data['EquipmentType']['size'];
foreach($sizesArray as $val){
$this->EquipmentTypesSize->create();
$this->EquipmentTypesSize->save(array(
'sizes' => $val,
'equipment_type_id' => $id,
));
}
$this->Session->setFlash('Equipment type has been added successfully ', 'default', 'success');
$this->redirect(array('controller' => 'equipments', 'action' => 'listequipmenttypes', 'admin' => true));
}
Lastly, two things:
Really, you should push as much of that logic into your EquipmentType model as possible. So you might create a saveWithSizes method in your EquipmentType model that holds most of that code.
You should look into Cake's saveAll method (http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array). Ideally, you'd set your form data up so that you could just call saveAll and have Cake handle it all automatically. That may or may not be possible for your situation though.
In laravel, we can get the input value via Input::get('inputname'). I try to change the value by doing this Input::get('inputname') = "new value";. But then, I get the error message saying Can't use function return value in write context.
Is it possible for us change the input value so that when later calling on Input::get('inputname') will get the new amended value?
Thanks.
You can use Input::merge() to replace single items.
Input::merge(['inputname' => 'new value']);
Or use Input::replace() to replace the entire input array.
Input::replace(['inputname' => 'new value']);
Here's a link to the documentation
If you're looking to do this in Laravel 5, you can use the merge() method from the Request class:
class SomeController extends Controller
{
public function someAction( Request $request ) {
// Split a bunch of email addresses
// submitted from a textarea form input
// into an array, and replace the input email
// with this array, instead of the original string.
if ( !empty( $request->input( 'emails' ) ) ) {
$emails = $request->input( 'emails' );
$emails = preg_replace( '/\s+/m', ',', $emails );
$emails = explode( ',', $emails );
// THIS IS KEY!
// Replacing the old input string with
// with an array of emails.
$request->merge( array( 'emails' => $emails ) );
}
// Some default validation rules.
$rules = array();
// Create validator object.
$validator = Validator::make( $request->all(), $rules );
// Validation rules for each email in the array.
$validator->each( 'emails', ['required', 'email', 'min: 6', 'max: 254'] );
if ( $validator->fails() ) {
return back()->withErrors($validator)->withInput();
} else {
// Input validated successfully, proceed further.
}
}
}
If you mean you want to overwrite input data, you can try doing:
Input::merge(array('somedata' => 'SomeNewData'));
Try this,it will help you.
$request->merge(array('someIndex' => "yourValueHere"));
I also found this problem, I can solve it with the following code:
public function(Request $request)
{
$request['inputname'] = 'newValue';
}
Regards
I'm using Laravel 8.
The following is working for me:
$request->attributes->set('name', 'Value');
I used Raham's answer to solve my problem. However, it was nesting the updated data within an array, when I needed it at the same level as other data. I used:
$request->merge('someIndex' => "yourValueHere");
A note other Laravel newbies, I used the merge method to account for an empty checkbox value in a Laravel 7 update form. A deselected checkbox on an update form doesn't return 0, it doesn't set any value in the update request. As a result that value is unchanged in the database. You have to check for a set value and merge a new value if nothing exists. Hope that helps someone.
Just a quick update. If the user doesn't check a box and I need to enter a value in the DB I do something like this in my controller:
if(empty($request->input('checkbox_value'))) {
$request->merge(['checkbox_value' => 0]);
}
I usually save itens status within a code (let's save I have the table: students, to save studentes status, I use the field (students.status)).
But, Everytime I list Users I will not shown the status code (1 or 0 for example). I need show: Registered or Cancelled.
I can simply check it when I list, but, let's say I need do it a lot of times.
Is there anything than can help me doing it? would save a lot of work, every page I'll list the user, or even when I add/edit him or a drop-down menu that should come with those items.
I've checked the models associations, but the solution that I've found works if I have another table with user status saved for example (I honestly don't wanna create it).
Thanks.
This describes how to do what you want: http://www.dereuromark.de/2010/06/24/static-enums-or-semihardcoded-attributes/
If the status can be registered or cancelled then you can use enum data type in your table schema.
You can get the list of status from enum data type for populating drop down like this.
$status = $this->Model->getEnumValues('status');
Before this you need to add following code in your appModel.php
function getEnumValues($columnName=null)
{
if ($columnName==null) { return array(); } //no field specified
//Get the name of the table
$db =& ConnectionManager::getDataSource($this->useDbConfig);
$tableName = $db->fullTableName($this, false);
//Get the values for the specified column (database and version specific, needs testing)
$result = $this->query("SHOW COLUMNS FROM {$tableName} LIKE '{$columnName}'");
//figure out where in the result our Types are (this varies between mysql versions)
$types = null;
if ( isset( $result[0]['COLUMNS']['Type'] ) ) { $types = $result[0]['COLUMNS']['Type']; } //MySQL 5
elseif ( isset( $result[0][0]['Type'] ) ) { $types = $result[0][0]['Type']; } //MySQL 4
else { return array(); } //types return not accounted for
//Get the values
$values = explode("','", preg_replace("/(enum)\('(.+?)'\)/","\\2", $types) );
//explode doesn't do assoc arrays, but cake needs an assoc to assign values
$assoc_values = array();
foreach ( $values as $value ) {
//leave the call to humanize if you want it to look pretty
$assoc_values[$value] = Inflector::humanize($value);
}
return $assoc_values;
}
I hope this will work for you. Thanks
I ended up creating a Helper function for that (not sure if the best way, it's been working fine)
MyHelper.php
class MyHelper extends AppHelper {
public $helpers = array();
public $list = array(0 => 'Cancelled', 1 => 'Registered');
public function __construct(View $View, $settings = array()) {
parent::__construct($View, $settings);
}
public function beforeRender($viewFile) {
}
public function afterRender($viewFile) {
}
public function beforeLayout($viewLayout) {
}
public function afterLayout($viewLayout) {
}
public function translate($id){
return $this->list[$id];
}
}
In view.ctp, intestead of showing the item ID, I just call the translate function, returning the proper name.
To create drop-down menus, it's just call the array list in select options.
<?php
echo "User Status: " . $this->My->translate($this->User->status);
echo $this->Form->input('tipo', array('type' => 'select', 'options' => $this->My->list));
?>
I think I should have used enum too, and using the functions specified, I would have success too.
Thanks for the helps.
You might want to look at model associations. In your case, I would have a students table and a student_statuses table that contains an ID and a status name. Then, when finding students, you can also include their corresponding StudentStatus row.
This relationship would look as follows:
<?php
class Student extends AppModel {
public $belongsTo = array('StudentStatus');
}
<?php
class StudentStatus extends AppModel {
public $hasMany = array('Student');
}
Then when finding students…
<?php
class StudentsController extends AppController {
public function index() {
$this->set('students', $this->Student->find('all'));
}
}
You will get a result like this:
Array
(
[0] => Array
(
[Student] => Array
(
[id] => 1
[name] => Martin Bean
[student_status_id] => 1
[created] => 2013-09-29 21:12:42
[modified] => 2013-09-29 21:12:42
)
[StudentStatus] => Array
(
[0] => Array
(
[id] => 1
[name] => Approved
[created] => 2013-09-23 18:26:06
[modified] => 2013-10-01 18:53:16
)
)
)
)
So you can just print the students’ status in your view as follows:
<?php foreach ($students as $student): ?>
<p>
<?php echo h($student['Student']['name']); ?>
(<?php echo h($student['StudentStatus']['name']); ?>)
</p>
<?php endforeach; ?>
You say you don’t want to create a table for statuses, but the reason you’re having issues is because it’s how relational databases work and also the convention. You’ll save yourself a lot of headaches by doing so, and it’s also extensible if you decide you need to add additional statuses in the future. You may not think you do now, but believe me: one day you will.