how to create dynamic array in codeigniter php mysql - php

I really need help on this.
I have an array that takes data from my input radio buttons. But the problem is these input buttons may not follow the exact numbers because of my where clause in the select statement.
<form method="post" action="<?php echo base_url();?>index.php/Question/resultdisplay">
<?php foreach($questions as $row) {
?>
<?php $ans_array = array($row->correct, $row->wrong, $row->wrong1, $row->wrong2);
shuffle($ans_array);
?>
<p><?=$row->quiz_question?></p>
<input type="radio" name="quizid<?=$row->id?>" value="<?=$ans_array[0]?>" required/><?=$ans_array[0]?><br/>
<input type="radio" name="quizid<?=$row->id?>" value="<?=$ans_array[1]?>"/><?=$ans_array[1]?><br/>
<input type="radio" name="quizid<?=$row->id?>" value="<?=$ans_array[2]?>"/><?=$ans_array[2]?><br/>
<input type="radio" name="quizid<?=$row->id?>" value="<?=$ans_array[3]?>"/><?=$ans_array[3]?><br/>
<?php
}
?>
<br/>
<input type="submit" value="Finish"/>
</form>
public function resultdisplay()
{
$this->data['checks'] = array(
'ques1' => $this->input->post('quizid1'),
'ques2' => $this->input->post('quizid2'),
'ques3'=> $this->input->post('quizid3'),
'ques4'=> $this->input->post('quizid4'),
'ques5'=> $this->input->post('quizid5'),
'ques6'=> $this->input->post('quizid6'),
'ques7'=> $this->input->post('quizid7'),
'ques8'=> $this->input->post('quizid8'),
'ques9'=> $this->input->post('quizid9'),
'ques10'=> $this->input->post('quizid10'),
'ques11'=> $this->input->post('quizid11'),
);
$this->load->model('quizmodel');
$this->data['results'] = $this->quizmodel->getQuestions();
$this->load->view('result_display', $this->data);
}
I want the array to be dynamic. because if the data in the database is more than eleven(11) then the user will not get result for the rest of the quiz.

If you change your resultdisplay() function round to first fetch the questions and then look for an answer to each question...
public function resultdisplay()
{
$this->load->model('quizmodel');
$this->data['results'] = $this->quizmodel->getQuestions();
$this->data['checks'] = [];
for ( $i = 1; $i <= count($this->data['results']); $i++ ) {
$this->data['checks'][] = $this->input->post('quizid'.$i);
}
$this->load->view('result_display', $this->data);
}
This will end up with an array (with a numeric index - you can change that by changing $this->data['checks'][$keyName]= with whatever you want as $keyName). Any missing answers will have null, again you can change this if needed at :null;.

Related

How can I "link" two objects (like a keyword and its synonyms) in a php function?

I'm creating a form using php, html, css, and javascript.
On this form, the person needs to choose a few keywords and its synonyms.
It looks like this:
<form action="create.php" class="col-md-10 offset-md-1" method="post">
<div class="form-group" id="duplicateKeyWordAndSynonym">
<label for="keyWord">Type a keyword.</label>
<textarea class="form-control" id="terms" name="terms[]"></textarea> <br/>
<label for="synonym">Type the synonyms of your keyword.</label>
<textarea class="form-control" id="synonym" name="synonym[]"></textarea> <br/>
</div>
<button class="glass-button" type="button" id="add">click here to add more keywords and
synonyms.</button>
</form>
<script>
//https://api.jquery.com/click/
$("#add").click(function () {
//https://api.jquery.com/append/
$("#duplicateKeyWordAndSynonym").append('here is the code to duplicate the keywords and
synonyms part.');
});
</script>
Now, I have to connect my keywords to my synonyms on "create.php" so I can send this to the back-end.
I have tried a few things, but nothing seems to work.
This was my first try:
for ($i = 0; $i < count($terms); $i++) {
echo "TERM".$terms[$i];
echo "\nSynonym ".$synonym[$i];
$list[$terms[$i]] = $synonym[$i];
}
Last thing I tried was this:
for ($i = 0; $i < count($terms); $i++) {
echo "TERM".$terms[$i];
echo "\nSYNONYMS ".$synonims[$i];
$list->add("keyword" => $terms[$i],
"synonym" => $synonims[$i]);
}
It didn't work. What should I do?
======================================
Edit: Thanks for your comments, guys! This is how I solved the problem:
class Keyword{
public $keyword;
public $synonyms;
public function setKeyword($keyword){
$this->keyword = $keyword;
}
public function getKeyword(){
return $this->keyword;
}
public function setSynonyms($synonyms){
$this->synonyms = $synonyms;
}
public function getSynonyms(){
return $this->synonyms;
}
}
$terms = $_POST['terms'];
$synonym = $_POST['synonym'];
$arrayKeywords = array();
for ($i = 0; $i < count($terms); $i++) {
$keyword = new Keyword();
$keyword->setKeyword($terms[$i]);
$keyword->setSynonyms($synonym[$i]);
$arrayKeywords[] = $keyword;
}
You can submit the form in two ways:
1- in javascript, by putting in the script ( document.getElementById("myForm").submit(); ) where myForm is the id form .
2- in php, at the button level put type="submit" instead of "button".
You can retrieve the data in the page "create.php" by $_POST['terms'] and $_POST['synonym']

How to store values of the index in an array?

I have an array that looks like this
Array ( [0] => test1 [1] => test4 [2] => test2 )
I got this value from my database using Codeigniter built-in function
And whenever I try to insert this value back in my database, it's inserting the index instead of the value itself
The error I'm getting is
As you can see, instead of storing test1, test4, test2 in the fields under username, it is storing the index which are 0, 1, 2.
How to fix this please?
References:
#MichaelK
TABLE:
Project Table
User Table
Project-User Table
VIEW
<div class="panel-body">
<?php echo form_open('admin/add_recommended'); ?>
<div class="form-group col-lg-12">
<label>Recommended Employees:</label>
<?php echo form_error('skillsRequired'); ?>
<?php
foreach ($users as $row) {
$user[] = $row->username;
}
print_r($user);
echo form_multiselect('user[]', $user, $user, array('class' => 'chosen-select', 'multiple style' => 'width:100%;'));
?>
</div>
</div>
<div class="panel-footer">
<?php echo form_submit(array('id' => 'success-btn', 'value' => 'Submit', 'class' => 'btn')); ?>
<?php echo form_close(); ?>
</div>
CONTROLLER
public function add_recommended() {
$this->form_validation->set_rules('skillsRequired', 'Skills Required', 'min_length[1]|max_length[55]');
$lid = $this->admin_model->getID();
foreach ($lid as $id) {
$last_id = $id['projectID'];
$data['users'] = $this->admin_model->getUsers($last_id);
}
$this->load->view('admin/projects/rec-employee', $data);
if ($this->form_validation->run() === FALSE) {
//$this->load->view('admin/projects/rec-employee');
} else {
$users = $this->input->post('user');
print_r($users);
foreach ($users as $user) {
$data = array(
'projectID' => $last_id,
'username' => $user
);
$id = $this->admin_model->insert('projectemp', $data);
}
if ($id) {
$this->session->set_flashdata('msg', '<div class="alert alert-success" role="alert">Success! New Project has been added.</div>');
redirect('admin/add_recommended');
}
}
}
RENDERED VIEW
why you use $data['users'] in controller. Where $users contains index value. You try this
//CONTROLLER
$data = $this->admin_model->getUsers($last_id); //last id is the latest id.
//VIEW
foreach ($data as $row) {
$user[] = $row->username;
}
Boy these are too many comments for a small problem.
First of all #blakcat7, I hope you won't mind If I suggest a little change in your DB Schema. Use indexes and proper normalization it always helps. I have simulated your case on my machine.
It is your user table, I have added an ID with in this table.
Its your project table, just changed some field names, you can use your own
This is your table to create your join, Although you could have used user_id or posted_by field in projects table which could solve your problem too
Now Where i see it, you have users in your database table, you also have added projects but now you want to assign or associate that project with the user.
Make it simple just create a view where you can see both projects and users
Rendered by the Controller function
public function assignProject()
{
$data['projects']=$this->admin_model->getAll('projects');
$data['users']=$this->admin_model->getAll('user');
if($_POST)
{
$this->admin_model->assignUser($_POST);
$data['success']='User Assigned';
$this->load->view('assignProjects',$data);
}
else
{
$this->load->view('assignProjects',$data);
}
}
The view rendered by following markup
<form action="" method="post">
<div class="form-group">
<label>Project</label>
<select name="project" class="form-control">
<?php for($i=0;$i<count($projects);$i++){?>
<option value="<?php echo $projects[$i]['id']?>"><?php echo $projects[$i]['title']?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<label>Users</label>
<select name="user" class="form-control">
<?php for($i=0;$i<count($users);$i++){?>
<option value="<?php echo $users[$i]['id']?>"><?php echo $users[$i]['username']?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Assing User</button>
</div>
</form>
Just hit Assign User and the following function in the Model will save it in the project-user table
public function assignUser($data)
{
$record=array(
'user_id'=>$data['user'],
'project_id'=>$data['project'],
);
$this->db->insert('user_projects',$record);
}
Remember, always use an Index (ID) field in your tables, would make your DB iteration life simpler
OKAY EVERYONE, THANKS Y'ALL FOR YOUR HELP. IT REALLY MEANS SO MUCH TO ME. AFTER LIKE 2 DAYS OF STRUGGLE I FINALLY FIXED MY PROBLEM. ^_^
Special thanks to Michael K for helping me point out the problem and Malik Mudassar for giving me the idea how to do it.
Controller
public function add_recommended() {
$lid = $this->admin_model->getID();
foreach ($lid as $id) {
$last_id = $id['projectID'];
}
$data['users'] = $this->admin_model->getUsers($last_id);
$this->load->view('admin/projects/rec-employee', $data);
if ($_POST) {
$users = $this->input->post('recommended');
foreach ($users as $user):
$data = array(
'projectID' => $last_id,
'userID' => $user
);
$id = $this->admin_model->insertRecEmp($data);
endforeach;
$this->session->set_flashdata('msg', '<div class="alert alert-success" role="alert">Success! New Project has been added.</div>');
redirect('admin/add_project');
}
}
Model
public function getUsers($id) {
$this->db->select('*');
$this->db->from('users_skills e');
$this->db->join('projects_skills p', 'e.skillsID = p.skillsID');
$this->db->join('users u', 'u.userID = e.userID');
$this->db->where('p.projectID', $id);
$this->db->group_by('e.userID');
$this->db->order_by('e.percentage', 'desc');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$result[] = $row;
}
return $result;
}
return false;
}
public function getID() {
$this->db->select_max('projectID');
$this->db->from('projects');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function insertRecEmp() {
$this->db->insert('projects_users', $data);
}
View
<form action="add_recommended" method="post">
<select name="recommended[]" class="chosen-select" multiple title='Select Skills' multiple style="width: 100%;">
<?php for ($i = 0; $i < count($users); $i++) { ?>
<option value="<?php echo $users[$i]->userID ?>"><?php echo $users[$i]->username ?></option>
<?php } ?>
</select>
</form>
I completely changed my database and my PHP function for multi select

Pushing value on a global array in php

I am facing a problem in pushing value to a global array.
A user uploads multiple documents. Everytime he uploads a document, a webservice is called which returns 'id' and 'type' (which is working fine). I need to store it in a array so that I can encode it into JSON and send it when the user clicks on Submit button.
My code is:
//global variable
<?php
$idarray = array();
$typearray = array();
?>
//form
<form method="post">
<input type="submit" name="upload" value="Upload">
<input type="submit" name="submit" value="Submit">
</form>
<?php
if(isset($_POST['upload']))
{
include 'webservice_call.php';
$url='http://localhost:8080/MyProject/getEntityRequest';
$response=curl_get_call($url); //this function is inside webservicecall.php
$json_string = json_decode($response);
$id=$json_string->gstdtls->entcd; //this is working fine
$ty=$json_string->gstdtls->stcd; //this is working fine
func1($idarray, $typearray, $id, $ty);
}
if(isset($_POST['submit']))
{
$docls=array();
global $idarray;
global $typearray;
for ($i=0; $i < sizeof($idarray); $i++) {
$docls[] = array (
'id' => $idarray[$i],
'ty' => $typearray[$i],
);
}
$json_formatted['docls']=$docls;
echo json_encode($json_formatted);
}
function func1($idarray, $typearray, $a, $b){
array_push($idarray, $a);
array_push($typearray, $b);
}
?>
When the user finally submits, it should give me the content of an array in a encoded format. Which is not happening. I know I am not using the global array in the way it should be used.
what u need is to store values somewhere like database or session instead of an array when you call upload and when you call submit button retrieve those values and convert them to json and echo them .
Here is a example of that using session
<?php
$json_formatted=array();
if (!session_start()) {
session_start();
}
?>
<?php
if(isset($_POST['upload']))
{
$_SESSION["idarray"][]=rand(0,5);
$_SESSION["typearray"][]=rand(0,5);
}
if(isset($_POST['submit']))
{
$docls=array();
$idarray=$_SESSION["idarray"];
$typearray=$_SESSION["typearray"];
for ($i=0; $i < sizeof($idarray); $i++) {
$docls[] = array (
'id' => $idarray[$i],
'ty' => $typearray[$i],
);
}
$json_formatted['docls']=$docls;
echo "<pre>";
print_r(json_encode($json_formatted));
echo "</pre>";
session_destroy();
}
function func1($idarray1, $typearray1, $a, $b){
array_push($idarray, $a);
array_push($typearray, $b);
}
?>
<form method="post">
<input type="submit" name="upload" value="Upload">
<input type="submit" name="submit" value="Submit">
</form>

Can't update data using Mysql and Codeigniter

i want to update my array data from table monitordata, but the data wont update i dont know where's the problem. there's no error in this code too :(
this is my controller
public function ubah($id) {
$data_lama = $this->monitor_m->get($id);
$this->data->tglmonitor = $data_lama->tglmonitor;
$this->data->detail = $this->monitor_m->get_record(array('monitor_data.idMonitor'=>$id),true);
$this->template->set_judul('SMIB | Monitoring')
->render('monitor_edit',$this->data);
}
public function ubahku($id) {
$id = $this->input->post('idMonitor_data');
if($this->input->post('idinven')!=NULL){
$idMonitor = $this->input->post('idMonitor');
$kondisi = $this->input->post('kondisi');
$nobrg = $this->input->post('nobrg');
$keterangan = $this->input->post('keterangan');
$kdinven = $this->input->post('kdinven');
$idinven = $_POST['idinven'];
for($i = 0; $i < count($idinven); $i++){
$data_detail = array(
'idMonitor' => $this->input->post('idMonitor'),
'idinven'=> $idinven[$i],
'kdinven'=> $kdinven[$i],
'nobrg'=> $nobrg[$i],
'kondisi'=> $kondisi[$i],
'keterangan' => $keterangan[$i]);
//print_r($data_detail);
$where = array('idMonitor_data' => $id);
$this->monitordata_m->update_by($where,$data_detail);
}
} redirect('monitorcoba');
}
This is my model monitordata_m
class Monitordata_m extends MY_Model {
public function __construct(){
parent::__construct();
parent::set_table('monitor_data','idMonitor_data');
}
This is MY_Model model i put in core folder.
public function update_by($where = array(), $data = array()) {
$this->db->where($where);
if ($this->db->update($this->table,$data)){
return true;
}
return false;
}
And this is my view
<?php echo form_open(site_url("monitorcoba/ubahku"),'data-ajax="false"'); ?>
<input data-theme="e" style="float: right;" data-mini="true" data-inline="false" data-icon="check" data-iconpos="right" value="Simpan" type="submit" />
<div data-role="collapsible-set" data-mini="true">
<?php foreach ($detail as $items): ?>
<div data-role="collapsible">
<?php echo form_hidden('idMonitor_data', $items['idMonitor_data'] ); ?>
<?php echo form_hidden('idMonitor', $items['idMonitor'] ); ?>
<h4><?php echo '[ '.$items['kdinven'].' ] '.$items['namabrg'] ?> </h4>
<?php echo form_hidden('kdinven', $items['kdinven'] ); ?>
<?php echo form_hidden('idinven', $items['idinven'] ); ?>
<div data-role="controlgroup">
<?php echo form_label ('Kondisi : ');
echo " <select name='kondisi' data-mini='true'>
<option value=".$items['kondisi'].">".$items['kondisi']."</option>
<option value=''>--Pilih--</option>
<option value='Baik'>Baik</option>
<option value='Rusak'>Rusak</option>
<option value='Hilang'>Hilang</option>";
echo "</select>";
echo form_input('keterangan',#$keterangan,'placeholder="Masukan Keterangan Tambahan"','class="input-text"');
?>
<?php echo form_close(); ?>
even if i use update_by it doesnt work. it's been 2 weeks and i have no clue :( i've tried all of the answer that i found in google but still.. so please help me.
This is the DATABASE result and POST_DATA for method ubahku
You have defined a method named update_by, but you are calling $this->monitordata_m->update($id,$data_detail);. Definitely it should not work. please call $this->monitordata_m->update_by($id,$data_detail); from your controller & check what will happen.
Firstly, Please correction $this->monitordata_m->update($id,$data_detail); to $this->monitordata_m->update_by($id,$data_detail); because your function name is update_by in your monitordata_m model.
Secondly, in your monitordata_m model update_by function have 2 param like $where = array() $data = array(), $where is a array but you calling in controller only $id. Your $id is not array. $where is like that $where = array('id' => $id) //id is where field name from db table
So, ubahku($id) method in your controller call $where in update_by function:
$where = array('id' => $id); // 'id' means "where field name"
$this->monitordata_m->update_by($where,$data_detail);
So, thank you so much for everyone who answer my question. so the problem was when i update the data, system only detect "kondisi[]" and "keterangan[]" as an array because i use this "[]" for both of it, so i just have to add "[]" in the end of every name in html form / views. so system will detect every input as an array. i hope you understand what i'm saying, sorry for my bad english. thank you this case is closed :)

Saving multiple checkbox data by foreach in MySQL using codeigniter

I have two tables ::: tbl_product and tbl_featured_product. I did view all product (from tbl_product) information in view pages by checkbox system. So that I can submit data to tbl_featured_product by checked as I need.
I can view all information to a view page in checkbox.. BUT can't save them in database. saving only last one row. please help me out to save multiple data in same time:::
view:::
<?php foreach($all_product as $values) { ?>
<input type="checkbox" name="product_name[]" value="<?php echo $values->product_name;?>" /> <?php echo $values->product_name;?> <br>
<input hidden="hidden" name="product_id[]" value="<?php echo $values->product_id;?>" />
<input hidden="hidden" name="product_price[]" value="<?php echo $values->product_price;?>" />
<?php } ?>
<input type="submit" name="btn" value="Save">
My Controller:::::
public function save_featured_product()
{
$data=array();
if ($this->input->post()) {
$data['featured_id']=$this->input->post('featured_id',true);
$data['product_id']=$this->input->post('product_id',true);
$data['product_name']=$this->input->post('product_name',true);
$data['product_price']=$this->input->post('product_price',true);
$this->sa_model->save_featured_product_info($data);
$sdata=array();
$sdata['message']='Save product Information Successfully !';
$this->session->set_userdata($sdata);
redirect('super_admin/add_featured_product');
}
My Model ::::
public function save_featured_product_info($data)
{
$this->db->insert('tbl_featured_products',$data);
}
Please let me know the solutions from your side. Thank you
Your problem is that the input $this->input->post('product_name') are arrays, so you need to insert one row for each, like:
(in the model)
public function save_featured_product_info($data)
{
if (isset($data['product_name']) && is_array($data['product_name'])):
foreach ( $data['product_name'] as $key=>$value ):
$this->db->insert('tbl_featured_products', array(
'product_id'=>$data['product_id'][$key],
'product_name'=>$data['product_name'][$key],
'product_price'=>$data['product_price'][$key],
'featured_id'=>$data['featured_id'] // assuming this are the same for all rows?
));
endforeach;
endif;
}
Do something like this, you may need to do some changes accordingly:
function save_featured_product_info($data){
if( isset( $data['product_id'] ) && is_array( $data['product_id'] ) ){
foreach( $data['product_id'] as $key => $each ){
$temp[] = array(
'featured_id' =>$data['featured_id'][$key],
'product_id' =>$data['product_id'][$key],
'product_name' =>$data['product_name'][$key],
'product_price'=>$data['product_price'][$key],
);
}
if( isset( $temp ) ){
$this->db->insert_batch('tbl_featured_products', $temp);
}
}
}
You're trying to save arrays, you either need to implode the values or loop and save them individually or batch insert them
$this->db->insert_batch('your_table', $temp);

Categories