How to insert dynamic data in Codeigniter? - php

I just want to insert dynamic generated input field data into database . My db table having three fields , id(Auto Increment), product_name and rate . I'm trying to insert bulk data into database using dynamically generated input fields where I can add/remove input fields manually.
I created the input fields as
<input class="form-control" placeholder="Product Name" name="prodname[]" type="text">
<input class="form-control" placeholder="Product Rate" name="prodrate[]" type="text">
This is my controller below
function Act_AddProducts() {
if ( $this->input->post( 'prodname' )&&$this->input->post( 'prodrate' )) {
foreach ( $this->input->post( 'prodname' ) as $key => $value ) {
$this->ProductModel->add_products( $value );
}
}
Model function is below
function add_products($val)
{
if($this->db->insert('tbl_product_master', array('product_name' => $val)))
{
return true;
}
else
{
return false;
}
}
Now the value is inserting into db but one at a time. So please help me to identify the issue with code. Also I don't really understand how to insert prodrate[] value into the same insert query.

Hope this will help you
Your controller Act_AddProducts should be like this :
function Act_AddProducts()
{
$prodnames = $this->input->post( 'prodname' );
$prodrates = $this->input->post( 'rate' );
if ( ! empty($prodnames) && ! empty($prodrates) )
{
foreach ($prodnames as $key => $value )
{
$data['product_name'] = $value;
/* make sure product_rate columns is correct i just guess it*/
$data['product_rate'] = $prodrates[$key];
$this->ProductModel->add_products($data);
}
}
}
Your model add_products should be like this :
function add_products($data)
{
if ( ! empty($data))
{
$this->db->insert('tbl_product_master', $data);
}
}

just pass input value to the model as it is, then use foreach inside model
function add_products($val)
{
foreach ( $val as $key => $value ) {
$this->db->insert('tbl_product_master', array('product_name' => $value );
}
}

TRY THIS
controller
function Act_AddProducts() {
$product_rate = $data = array();
$product_rate = $this->input->post( 'prodrate' );
$product_name = $this->input->post( 'prodname' )
if ( !empty($this->input->post( 'prodname' ))&&!empty($this->input->post( 'prodrate' ))) {
foreach ( $product_name as $key => $value ) {
$data['product_name'] = $value;
$data['product_rate'] = $product_rate[$key];
$this->ProductModel->add_products($data);
}
}
model
function add_products($data)
{
$product_name = $data['product_name'];
$product_rate = $data['product_rate'];
if($this->db->insert('tbl_product_master', array('product_name' => $product_name,'product_rate' => $product_rate)))
{
return true;
}
else
{
return false;
}
}

This is just for your reference.... A simple sample code for dynamic insert.
defined('BASEPATH') OR exit('No direct script access allowed');
class Checking extends CI_Controller {
public function index()
{
echo "<form method='post' action='". base_url("Checking/save") ."'>";
for($i=0;$i<=5;$i++)
{
echo "<input type='text' name='input_text[]'>";
}
echo "<button type='submit'>Submit</button></form>";
}
public function save(){
foreach($this->input->post("input_text") as $Row){
$this->db->insert("checking",array("input_text"=>$Row['input_text']));
}
}
}
create a controller as Checking.php, and run this .. you will get idea
For database
CREATE TABLE `checking` (
`ch` int(11) NOT NULL AUTO_INCREMENT,
`input_text` varchar(255) DEFAULT NULL,
PRIMARY KEY (`ch`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8

If you want upload bulk record then use insert_batch instead of simple insert
your Controller should be
function Act_AddProducts()
{
$product_rate = $_POST['prodrate'];
$product_name = $_POST['prodname'];
if(!empty($product_rate) && !empty($product_rate)){
$data_array = array();
foreach ($product_rate as $key => $value )
{
$tmp_array = array();
$tmp_array['product_name'] = $value;
$tmp_array['product_rate'] = $product_rate[$key];
$data_array[] = $tmp_array;
}
$this->ProductModel->add_products($data_array);
}
model should be
function add_products($data)
{
if($this->db->insert_batch('tbl_product_master', $data))
{
return true;
}
else
{
return false;
}
}

Related

instantiate get form data in a class php

I have a simple php form submitting a query into a few classes. The idea of app is to pass in a band name and check a venue to see if that band is playing. If that band is playing it the app will echo out the band and the date that band is playing. I have managed to get the app to work when its all one php file but i am having trouble spitting the single php file into separate classes.
html form :
<form action = "Ass1.php" method = "GET">
<b>Enter band name : </b>
<input type="text" name="bandName" />
<input name="submit" type="submit" value="Click" />
</form>
The entire php file that works:
<?php
class Concert {
public $Artist = '';
public $Date = '';
function SetConcert( $NewArtist = '', $NewDate = '' ) {
$this->Artist = $NewArtist;
$this->Date = $NewDate;
}
function GetArtist() {
return $this->Artist;
}
function GetDate() {
return $this->Date;
}
}
class Venue {
public $VenueName = '';
public $ConcertsInVenue = array();
function SetVenueName( $NewVenue = '' ) {
$this->VenueName = $NewVenue;
}
function GetVenueName() {
return $this->VenueName;
}
function AddConcert( $NewArtist = '', $NewDate = '' ) {
$NewConcert = new Concert;
$NewConcert->SetConcert( $NewArtist, $NewDate );
$this->ConcertsInVenue[] = $NewConcert;
}
function ListConcertsInVenue( $SearchQuery = '' ) {
//Assume Results Will Be Filtered
$ListAllConcerts = FALSE;
//If Search Query Is Blank, List All Concerts
if( $SearchQuery == '' ){
$ListAllConcerts = TRUE;
}
echo 'Concerts In '.$this->VenueName.':';
//Loop Through All Concerts In This Venue
foreach( $this->ConcertsInVenue as $tmpConcert ){
if( $SearchQuery == $tmpConcert->GetArtist() || $ListAllConcerts == TRUE ){
echo '<p>';
echo $tmpConcert->GetArtist().', ';
echo $tmpConcert->GetDate();
echo '</p>';
}
}
}
}
//Create New Venue Object
$tmpVenue = new Venue;
//Set Venue Name
$tmpVenue->SetVenueName( 'Wembley' );
//Add Concerts To Venue
$tmpVenue->AddConcert( 'Rollin\' Empire', '05-02-2018' );
$tmpVenue->AddConcert( 'Metallica', '06-02-2018' );
$tmpVenue->AddConcert( 'Led Zeppelin', '07-02-2018' );
$tmpVenue->AddConcert( 'Rollin\' Empire', '19-02-2018' );
//Search For Artist In Venue ( Leave Blank To List All )
$tmpVenue->ListConcertsInVenue($_GET['bandName']);
?>
Ive tries creating 3 classes Venue.class.php Concert.class.php and app.class.php and its not working
concert.class.php
<?php
include ("Venue.class.php");
class Concert {
public $Artist = '';
public $Date = '';
function SetConcert( $NewArtist = '', $NewDate = '' ) {
$this->Artist = $NewArtist;
$this->Date = $NewDate;
}
function GetArtist() {
return $this->Artist;
}
function GetDate() {
return $this->Date;
}
}
?>
Venue.class.php
<?php
include ("Concert.class.php");
class Venue {
public $VenueName = '';
public $ConcertsInVenue = array();
function SetVenueName( $NewVenue = '' ) {
$this->VenueName = $NewVenue;
}
function GetVenueName() {
return $this->VenueName;
}
function AddConcert( $NewArtist = '', $NewDate = '' ) {
$NewConcert = new Concert;
$NewConcert->SetConcert( $NewArtist, $NewDate );
$this->ConcertsInVenue[] = $NewConcert;
}
function ListConcertsInVenue( $SearchQuery = '' ) {
//Assume Results Will Be Filtered
$ListAllConcerts = FALSE;
//If Search Query Is Blank, List All Concerts
if( $SearchQuery == '' ){
$ListAllConcerts = TRUE;
}
echo 'Concerts In '.$this->VenueName.':';
//Loop Through All Concerts In This Venue
foreach( $this->ConcertsInVenue as $tmpConcert ){
if( $SearchQuery == $tmpConcert->GetArtist() || $ListAllConcerts == TRUE ){
echo '<p>';
echo $tmpConcert->GetArtist().', ';
echo $tmpConcert->GetDate();
echo '</p>';
}
}
}
}
?>
app.php
<?php
include ("Venue.class.php");
include ("Concert.class.php");
//Create New Venue Object
$tmpVenue = new Venue;
//Set Venue Name
$tmpVenue->SetVenueName( 'Wembley' );
//Add Concerts To Venue
$tmpVenue->AddConcert( 'Rollin\' Empire', '05-02-2018' );
$tmpVenue->AddConcert( 'Metallica', '06-02-2018' );
$tmpVenue->AddConcert( 'Led Zeppelin', '07-02-2018' );
$tmpVenue->AddConcert( 'Rollin\' Empire', '19-02-2018' );
//Search For Artist In Venue ( Leave Blank To List All )
$tmpVenue->ListConcertsInVenue($_GET['bandName']);
?>
Would I need to create a new class in app.php to handle the form input and pass it to the other classes?

Inserting data from session using codeigniter

I'm just practicing using session in Codeigniter and i've got a Problem here's my controller
public function ajax_Addfees()
{
if($this->input->is_ajax_request())
{
$input = $this->input->post();
if($this->session->userdata('html')){
$html = $this->session->userdata('html');
}
$id = explode($input['fno']);
$html[$id] = ['amount' => $input['amount'], 'oldamount' => $input['deduction']];
$this->session->set_userdata('html', $html);
}
}
public function savetuition()
{
$this->Tuition_model->savefees();
redirect('tuitionsetup_con');
}
This is my model
public function savefees()
{
$fees = $this->session->userdata('html');
$feeslist = [];
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
array_push($feeslist, [
'amount' => $value['amount'],
'oldamount' => $value['oldamount'],
'f_no' => $key,
'sy_no' => $this->session->userdata('sy'),
'level_no' => $this->session->userdata('lvl'),
'id' => $this->session->userdata('id')
]);
$this->db->insert_batch('tuition', $feeslist);
} }
}
Well what I'm trying to do is to save data from session->set_userdata('html') to my database using codeigniter.
There's no error but it doesn't save data to database
You need to modify your model as:
public function savefees() {
$fees = $this->session->userdata('html');
$feeslist = array();
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
$feeslist[$key]["amount"] = $value['amount'];
$feeslist[$key]["oldamount"] = $value['oldamount'];
$feeslist[$key]["f_no"] = $key;
$feeslist[$key]["sy_no"] = $this->session->userdata('sy');
$feeslist[$key]["level_no"] = $this->session->userdata('lvl') ;
$feeslist[$key]["id"] = $this->session->userdata('id') ;
}
}
$this->db->insert_batch('tuition', $feeslist);
}

How to get return value when a table was drop by using MYSQL with Codeigniter?

I'm trying to create tables using method in CI3.0.4 for this process I want to check the return value after a table was drop,create,set foreing key or not?
This function can check only when drop is true when I try to drop tables but that table is not existing in database my drop() still return true the same
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Dbforges extends Main_Controller
{
public $respond = array();
protected $column = '';
public function __construct()
{
parent::__construct();
$data = array(
"fid" => "bigint(50) AUTO_INCREMENT,",
"fk_c_id" => "bigint(50),",
"fk_group_id" => "bigint(50),",
"fk_user_id" => "bigint(50),",
"fk_product_id" => " bigint(50),",
"feaddata" => " decimal(10,2) NOT NULL,",
"credit" => "decimal(10,2) NOT NULL,",
"b_debit" => "decimal(10,2) NOT NULL,",
"b_credit" => "decimal(10,2) NOT NULL,",
"description" => " varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,",
"PRIMARY KEY" => "(`fid`),",
"KEY `fk_c_id` " => "(`fk_c_id`),",
"KEY `fk_group_id` " => "(`fk_group_id`),",
"KEY `fk_user_id` " => "(`fk_user_id`),",
"KEY `fk_product_id` " => "(`fk_product_id`)"
);
if ($this->drop("feadback") == false) {
$this->respond[] = 'nod';
} else {
$this->respond[] = 'd';
}
if ($this->AddTables("feadback", $data) == false) {
$this->respond[] = 'noc';
} else {
$this->respond[] = 'c';
}
if ($this->Add_Foreignkey("feadback", "fk_c_id", "cat", "c_id") == false) {
$this->respond[] = 'nfk';
} else {
$this->respond[] = 'fk';
}
echo json_encode(array("res"=>$this->respond));
}
public function index()
{
}
public function AddTables($table, $data)
{
if (!empty($table) && !empty($data)) {
foreach ($data as $k => $col) {
$this->column .= $k . ' ' . $col;
}
if ($this->db->query("CREATE TABLE IF NOT EXISTS $table ($this->column) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT= 0;") == true) {
return true;
} else {
return false;
}
}
}
protected function drop($table = false)
{
if ($table) {
if ($this->db->query("DROP TABLE IF EXISTS $table;") == true) ;
return true;
} else {
return false;
}
}
public function Add_Foreignkey($fkTable, $fk, $refTables, $referal)
{
if ($this->db->query("ALTER TABLE $fkTable ADD CONSTRAINT $fkTable.$fk FOREIGN KEY ($fk) REFERENCES `$refTables` ($referal) ON DELETE CASCADE ON UPDATE CASCADE;") == true) {
return true;
} else {
return false;
}
}
}
?>
Thanks for help
Try This
public function drop($table = false)
{
if ($table) {
if ($this->db->query("DROP TABLE IF EXISTS $table;") == true){
$query = $this->db->query("SHOW TABLES LIKE '".$table."'");
if($query->num_rows() != null)
{
return true;
}
else{
return false;
}
}
}
else
{
return false;
}
}
i hope its work for you.

Model not updating correct

When I update my database row. It for some reason update all the values as the same as last input which is very strange.
How can I get it working so all rows do not get updated with the value all the same?
This is how my database works.
$group = 'config'.
$key = example:'config_name'.
$value = what ever is typed in $key.
In my model I use foreach ($data as $key => $value) { It is very strange that it updates all values with the last input value.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_website_setting extends CI_Model {
public function editWebsite($group , $data, $website_id = 0) {
foreach ($data as $key => $value) {
// Make sure only keys belonging to this group are used
if (substr($key, 0, strlen($group)) == $group) {
if (!is_array($value)) {
$this->db->set('group', $group);
$this->db->set('value', $key);
$this->db->set('value', $value);
$this->db->set('website_id', $website_id);
$this->db->update($this->db->dbprefix . 'setting');
} else {
$this->db->set('group', $group);
$this->db->set('value', $key);
$this->db->set('value', $value);
$this->db->set('website_id', $website_id);
$this->db->update($this->db->dbprefix . 'setting');
}
}
}
}
}
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Website_settings extends Controller {
public function __construct() {
parent::__construct();
$this->lang->load('admin/setting/setting', 'english');
}
public function index() {
$this->document->setTitle($this->lang->line('heading_title'));
$data['entry_name'] = $this->lang->line('entry_name');
$data['entry_owner'] = $this->lang->line('entry_owner');
if (!empty($this->input->post('config_name'))) {
$data['config_name'] = $this->input->post('config_name');
} else {
$data['config_name'] = $this->settings->get('config_name');
}
if (!empty($this->input->post('config_owner'))) {
$data['config_owner'] = $this->input->post('config_owner');
} else {
$data['config_owner'] = $this->settings->get('config_owner');
}
$this->load->library('form_validation');
$this->form_validation->set_rules('config_name', 'Website Name');
$this->form_validation->set_rules('config_owner', 'Your Name');
if ($this->form_validation->run() == FALSE) {
return $this->load->view('setting/website_settings', $data);
} else {
$this->load->model('admin/setting/model_website_setting');
$this->model_website_setting->editWebsite('config', $this->input->post());
$this->session->set_flashdata('success', 'You have updated settings!');
redirect('admin/setting/website');
}
}
}
If i were you i would use the built in update_batch and will not place an update on every loop.
foreach ($data as $key => $value) {
// Make sure only keys belonging to this group are used
if (substr($key, 0, strlen($group)) == $group) {
if (!is_array($value)) {
// this is where you do the logic
// if the value is the same do not insert in the update array
// if the value is not the same then insert it on the update array
$update[] = array(
'group' => $group,
'value' => $key,
'website_id' => $website_id
);
} else {
$update[] = array(
'group' => $group,
'value' => $key,
'website_id' => $website_id
);
}
}
}
$this->db->update_batch($this->db->dbprefix . 'setting', $update , 'website_id');
sample on how to use update batch on your code not tested.

Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database

Codeigniter when i submit more than one option of form_multiselect(), Only just the last one that saved on database.
in my view :
<label>Trimestres :</label>
<div class="controls" >
<?php $options = array(
'trim1' => ' Premier trimestre (Janv,Fév,Mars)',
'trim2' => ' Deuxiéme trimestre (Avril,Mai,Juin)',
'trim3' => ' Troisiéme trimestre (Juill,Aout,Sept)',
'trim4' => ' Quatriéme trimestre (Oct,Nov,Déc)',
);
echo form_multiselect('trimestres', $options , $this->input->post('trimestres') ? $this->input->post('trimestres') : $participant_sport->trimestres, 'id="trim"'); ?>
</div>
</div>
in my controller :
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
The function array_from_post() is defined on application\core\MY_Model.php :
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
in my model :
public function get_new()
{
$participant_sport = new stdClass();
$participant_sport->matricule = '';
$participant_sport->nom = '';
$participant_sport->prenom = '';
$participant_sport->beneficiaire = '';
$participant_sport->sexe = '';
$participant_sport->telephone = '';
$participant_sport->date_naissance = '';
$participant_sport->date_inscription_sport = '';
$participant_sport->trimestres = '';
$participant_sport->sport_montant_paye = '';
$participant_sport->sport_debut_periode = '';
$participant_sport->sport_fin_periode = '';
return $participant_sport;
}
Any help Please? i think that must be an array but i don't know how to do it?
i thing that i must do something like that :
foreach($_POST["strategylist[]"] as $s) {
# do the insert here, but use $s instead of $_POST["strategylist[]"]
$result=mysql_query("INSERT INTO sslink (study_id, strategyname) " .
"VALUES ('$id','" . join(",",$s) . "')")
or die("Insert Error: ".mysql_error());
}
to insert more than one option selected in one row but i don't know how to do it in codeigniter
the get() function :
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
If select name (in HTML tag) is trimestres it will always remember last selection. Use trimestres[] as a name to get array with all selected values`
<select name="trimestres[]" multiple …
By the way:
I don't know how array_from_post() works but it has to change trimestres[] values to one string to save all of them in one column. It is hard to search/add/delete one value if all values are in one string. It is "SQL Antipattern". You could do another table in database for trimestres - one value in one row.
Edit:
It will change all arrays into string with elements connected by ,. Not tested.
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
// print_r($this->input->post($field));
if( is_array( $this->input->post($field) ) ) {
$data[$field] = join(",", $this->input->post($field));
} else {
$data[$field] = $this->input->post($field);
}
// print_r($data[$field]);
}
return $data;
}
Edit:
Not tested.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
// explode to array
// print_r($this->data['participant_sport']->trimestres); // test before explode
// $this->data['participant_sport']['trimestres'] = explode(",", $this->data['participant_sport']['trimestres']);
$this->data['participant_sport']->trimestres = explode(",", $this->data['participant_sport']->trimestres);
// print_r($this->data['participant_sport']->trimestres); // test after explode
} else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// rest of code
}
There is a easy way to solve this problem that I found today.
you have to serialize the $_POST['trimestres'] array just after array_form_post .
the this array will save to database as a serialize string.
public function inscriresport ($id = NULL)
{
// Fetch a participant or set a new one
if ($id) {
$this->data['participant_sport'] = $this->participantsport_m->get($id);
count($this->data['participant_sport']) || $this->data['errors'][] = 'participant non trouvé';
}
else {
$this->data['participant_sport'] = $this->participantsport_m->get_new();
}
// Process the form
$this->participantsport_m->array_from_post(array('matricule', 'nom', 'prenom', 'beneficiaire', 'sexe', 'telephone', 'date_naissance', 'date_inscription_sport', 'trimestres' ,'sport_montant_paye', 'sport_debut_periode', 'sport_fin_periode'));
$data['trimestres'] = serialize($_POST['trimestres']);
$this->participantsport_m->save($data, $id);
redirect('admin/agent/profile/3608');
}
// Load the view
$this->data['subview'] = 'admin/agent/inscriresport';
$this->load->view('admin/_layout_main', $this->data);
}
When you just need this data back form database just use php unserialize() function .
Hope it will help to do this easily ....
-thanks

Categories