Saving multiple checkbox data by foreach in MySQL using codeigniter - php

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);

Related

Using Iterator and update_user_meta() to Dynamically Add Checkboxes to profile.php and edit-user.php in WordPress Using an Array

So, I've been pulling my hair out over this for longer than I'd care to admit. I am trying to create a bunch of checkboxes in profile.php and user-edit.php for a plugin that is populated by an array. For starters, this works:
//<!-- "HTML" -->
function profile_fields($user) {
$user_id = $user->ID;
<input type='hidden' name="user_id" value="<?php echo $user_id ?>" />
<input type="checkbox" id="some-setting" name='some-setting'
<?php if (get_user_meta( $user->ID, 'somePref', true ) == '1'){ echo 'checked'; } ?> />
<label for="some-setting">TEST 2</label>
//PHP
function update_field_value($user_id) {
if ( isset($_POST['some-settings'], $user_id ) && $_POST['some-settings'] == 'on') {
update_user_meta( $user_id, 'somePref', '1');
} else {
update_user_meta( $user_id, 'somePref', NULL);
}
}
HOWEVER, what I have generates Undefined offset... and Trying to access array offset on value of type null... that I can't trace the origin of when using:
class Some_Class
{
//Array of user specialties to be displayed
var $userSpecialtiesList;
//Array of ids for input fields
var $userSpecialtiesIDs = array();
//Array of meta values for input fields
var $metaValues = array();
//Array of meta value names for use with accessing info
var $metaNames = array();
/**
* initialize
*
* I use this to populate the array and call add_action
*/
function initialize(){
$this->userSpecialtiesList = array(
/* some information here */
);
add_action( 'show_user_profile', array($this, 'extra_profile_fields') );
add_action( 'edit_user_profile', array($this, 'extra_profile_fields') );
add_action( 'personal_options_update', array($this, 'update_field_value') );
add_action( 'edit_user_profile_update', array($this, 'update_field_value') );
}
/**
* extra_profile_fields
* I use this to generate the input fields that the user sees
*/
function extra_profile_fields( $user ) {
$user_id = $user->ID;
//I used this for testing
//$meta_value = get_user_meta( $user->ID, 'somePref', true );
?>
<h3><?php _e("Some Title", "blank"); ?></h3>
<table class="form-table">
<!-- Some unrelated stuff here -->
<tr>
<th><h4><?php _e("Specialties"); ?></h4></th>
<td>
<fieldset>
<!-- Some more unrelated stuff here -->
<?php
$this->generateCheckboxes($user_id);?>
</fieldset>
</td>
</tr>
</table>
<?php
}
/**
* generateID
*
* Partially complete function to generate field ids and meta keys
*/
function generateID($phrase, $arrValue, $style){
//Remove illiegal characters and leave only alphanumeric
$arrValueUpdated = preg_replace('/[^a-zA-Z\d:]/', "", $arrValue);
switch($style){
//Use Dashes
case $style == "-":
case $style == "dash":
return strtolower($phrase) . "-" . strtolower($arrValueUpdated);
//Use camelCase
case $style == "camelCase":
return strtolower($phrase) . ucfirst($arrValueUpdated);
//Default is alltogether
default:
return strtolower($phrase) . strtolower($arrValueUpdated);
}
}
/**
* generateCheckboxes
*
* I use this to generate checkboxes from the array instantiated above
*/
function generateCheckboxes($userID){
foreach($this->userSpecialtiesList as $userSpecialty){
//Create unique id for input fields and add it to array for later
$inputID = $this->myGenerateID("specialty", $userSpecialty, "dash");
array_push( $this->userSpecialtiesIDs, $inputID );
//Create meta key and add it to array of meta keys for use with update_user_meta later
$metaName = $this->myGenerateID("pref", $userSpecialty, "camelCase");
array_push( $this->metaNames, $metaName );
//Create variable for meta values and add it to array for later
$meta_value = get_user_meta( $userID, $metaName, true );
array_push( $this->metaValues, $meta_value );
?>
<div class="my-checkbox-class">
<input type='hidden' name="user_id" value="<?php echo $userID ?>" />
<input type="checkbox" id="<?php echo $inputID; ?>" name='<?php echo $inputID; ?>'
<?php if ($meta_value == '1'){ echo 'checked'; } ?> />
<label for='<?php echo $inputID; ?>'><?php _e($userSpecialty); ?></label>
</div>
<?php }
function update_field_value($user_id) {
$user_id = $_POST['user_id'];
$uslIndex = 0;
foreach($this->userSpecialtiesList as $userSpecialty){
if ( isset($_POST[$this->userSpecialtiesIDs[$uslIndex]], $user_id ) && $_POST[$this->userSpecialtiesIDs[$uslIndex]] == 'on') {
update_user_meta( $user_id, $this->metaNames[$uslIndex], '1');
} else {
update_user_meta( $user_id, $this->metaNames[$uslIndex], NULL);
}
$uslIndex++;
}
}
}
function some_class_func() {
global $some_class_func;
// Instantiate only once.
if( !isset($some_class_func) ) {
$some_class_func = new Some_Class();
$some_class_func->initialize();
}
return $some_class_func;
}
// Instantiate
some_class_func();
In posting this, I obfuscated some of the variable names and removed some unnecessary bits for clarity; I also realize as I went through it that I have some artifacts from re-writing portions of it that may be part of my problem but I've chosen to leave them in.
If I get this on my own then I will post the solution for everyone; in any case though, I offer many thanks in advance for any and all answers / help!
Sometimes its easier to troubleshoot if you separate things out
$postval = isset($this->userSpecialtiesIDs[$uslIndex]) ? $this->userSpecialtiesIDs[$uslIndex] : null;
$user_id = $user_id ?? null;
$condition1 = $user_id && $postval && isset($_POST[$postval]);
$condition2 = $postval && $_POST[$postval] === 'on';
if ($condition1 && $condition2) {
// do the thing
}
and...
if ($user_id && isset($this->metaNames[$uslIndex])) update_user_meta( $user_id, $this->metaNames[$uslIndex], NULL);
Alright, so it seems like my problem was perhaps one of scope so what I did was basically just create an array elsewhere and hand it to the update function. So, I pretty much left initialize(), extra_profile_fields(), and generateID() alone and instead I made the following changes:
//Generate the input tag ID and meta key / name
// and then create the HTML for checkboxes
function generateCheckboxes($userID){
foreach($this->userSpecialtiesList as $userSpecialty){
$inputID = $this->generateID("specialty", $userSpecialty, "dash");
$metaName = $this->generateID("pref", $userSpecialty, "camelCase"); ?>
<div class="prof-checkbox">
<input type='hidden' name="user_id" value="<?php echo $userID ?>" />
<input type="checkbox" id="<?php echo $inputID; ?>" name='<?php echo $inputID; ?>'
<?php if (get_user_meta( $userID, $metaName, true ) == '1'){ echo 'checked'; } ?> />
<label for='<?php echo $inputID; ?>'><?php _e($userSpecialty); ?></label>
</div>
<?php }
}
/**
* generate_array()
* Creates, populates, and returns a multi-dimensional array holding
* the input tag's id, meta key, and text value.
*
* #return $userSpecialtiesArr Array A multi-dimensional array holding the input tag's id ("id"), meta key "meta", and text "text"
*/
function generate_array(){
$userSpecialtiesArr = array();
foreach($this->userSpecialtiesList as $userSpecialty){
$userSpecialtyPKG = array(
"text"=>$userSpecialty,
"id"=>$this->HgenerateID("specialty", $userSpecialty, "dash"),
"meta"=>$this->generateID("pref", $userSpecialty, "camelCase"),
);
array_push($userSpecialtiesArr, $userSpecialtyPKG);
}
return $userSpecialtiesArr;
}
function update_field_value($user_id) {
$user_id = $_POST['user_id'];
//Generate array to hold the neccessary information
$userSpecialtiesArr = $this->generate_array();
//Use an iterator to dynamically add the necessary unique ID and meta key.
foreach($userSpecialtiesArr as $userSpecialty) :
if ( isset($_POST[$userSpecialty['id']], $user_id ) && $_POST[$userSpecialty['id']] == 'on') {
update_user_meta( $user_id, $userSpecialty['meta'], '1');
} else {
update_user_meta( $user_id, $userSpecialty['meta'], NULL);
}
endforeach;
}
Not sure if this'll help anyone, but if not Kinglish also had a pretty great answer and hopefully both can reduce somebody out there pulling out their hair over the same thing.

how to create dynamic array in codeigniter php mysql

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;.

Instead of submit get data on entering page php

I use this snippet to get vehicle data from a external database:
<form method="post" action="<?php echo $_SERVER['REQUEST_URI'] ?>" class="vwe-kenteken-widget">
<p><input type="text" name="open_data_rdw_kenteken" value="<?php echo $_POST['open_data_rdw_kenteken'] ?>" maxlength="8"></p>
<p><input name="submit" type="submit" id="submit" value="<?php _e('Kenteken opzoeken', 'open_data_rdw') ?>"></p>
</form>
<?php if($data): ?>
<h3><?php _e('Voertuiggegevens', 'open_data_rdw') ?></h3>
<table>
<?php
$categories = array();
foreach ($data as $d) {
if( !is_array($fields) || in_array($d['name'], $fields) ) {
if( !in_array($d['category'], $categories) ) {
$categories[] = $d['category'];
echo '<tr class="open-rdw-header">';
echo '<td colspan="2" style="font-weight: bold;">';
echo ''.$d['category'].'';
echo '</td>';
echo '</tr>';
}
echo '<tr style="display:none">';
echo '<td>'.$d['label'].'</td>';
echo '<td>'.$d['value'].'</td>';
echo '</tr>';
}
}
?>
</table>
<?php endif; ?>
What i want to accomplish is that the data is loaded without the user have to enter a value and hit the submit button. The input value will get loaded based on the product page the user is viewing.
EDIT:
The data is loaded based on:
public function get_json() {
if ( isset( $_POST['kenteken'] ) ) {
$data = $this->rdw->get_formatted($_POST['kenteken']);
foreach ($data as $row) {
$json['result'][$row['name']] = $row['value'];
}
if ($_POST['kenteken']) {
if ($data[0]['value'] == '') {
$json['errors'] = __( 'No license plates found', 'open_data_rdw' );
}
else {
$json['errors'] = false;
}
}
else {
$json['errors'] = __( 'No license plate entered', 'open_data_rdw' );
}
header('Content-type: application/json');
echo json_encode($json);
die();
}
}
So instead of a $_POST action just get the data based on a pre-declared value that is different on each page.
Hard to answer - but I'll try to use my crystal ball.
$data comes from a database query, right?
I assume further, that the query takes the value from the open_data_rdw_kenteken form field to gather $data.
To have the table rendered, you have to fill $data with the right data. That implies that you must have a kind of default value for open_data_rdw_kenteken to get the data out of the DB. The default can be "all" which should reflect on your SQL Query or as your wrote "defined by product page".
Pseudo Code
$data = getData('BT-VP-41');
function getData($open_data_rdw_kenteken="")
{
$where = "";
if(!empty($open_data_rdw_kenteken)) {
$where = 'WHERE rdw_kenteken = "'.mysqli_real_escape_string($open_data_rdw_kenteken)';
}
$data = myslqi->query("SELECT * FROM dbTbl ".$where)
return $data;
}
As I wrote - this is pseudo code and will not run out of the box. You'll have to adapt that to your environment.
TL;DR: The line
<?php if($data): ?>
keeps you from rendering the table. To render you need $data filled with the right data.
Hope that will get you in the right direction.

How to verify multiple checkboxes using php

I have a list which I am populating from my DB into multiple checkboxes using a foreach loop:
<?php
$sections_arr = listAllForumBoards(0, 1, 100);
$count_board = count($sections_arr);
$ticker = 0;
foreach($sections_arr as $key => $printAllSections){
$ticker = $ticker + 1;
$sectionId = getBoardPart($printAllSections, 'id');
$sectionName = getBoardPart($printAllSections, 'title');
$sectionSlug = getBoardPart($printAllSections, 'slug');
?>
<dd><label for="<?php echo $sectionSlug; ?>">
<input type="checkbox" name="section[]" id="<?php echo $sectionSlug; ?>" value="<?php echo $sectionId; ?>" /> <?php echo $sectionName; ?></label></dd>
<?php } ?>
The list is populating as expected. But I want to be able to check to make sure that a user selects at least one of the checkboxes. I've searched here in SO and I only got the one that was done using JQuery, but I want to be able to do this verification using PHP
In the file, where your form is submitting (action file) add this condition:
if (empty($_POST['section'])) {
// it will go here, if no checkboxes were checked
}
In your action file, you should have the following
if(empty($_POST['section'])) {
//this means that the user hasn't selected any checkbox, redirect to the previous page with error
}

PHP add new data to multidimensional array

I'm a newbie to multidimensional array's
I have a form that stores data into an array.
I would like my users to re-use the form and store data to the array.
So my idea was a multidimensional array that stores a new array everytime the form is used.
But my problem is that I have no idea how to do this.
Here is my form:
$customer = '';
$customer .= '<tr><td>customername:<br/><input type="text" name="customer[customername]" value="" /> </td></tr>';
$customer .= '<tr><td>customertitle 1:<br/><input type="text" name="customer[customertitle1]" value="" /> </td></tr>';
$customer .= '<tr><td>customeremail 1:<br/><input type="text" name="customer[customeremail1]" value="" /> </td></tr>';
$customer .= '<tr><td>customertitle 2:<br/><input type="text" name="customer[customertitle2]" value="" /> </td></tr>';
$customer .= '<tr><td>customeremail 2:<br/><input type="text" name="customer[customeremail2]" value="" /> </td></tr>';
echo $customer;
This saves the form in an array:
if(isset($_POST['Submit'])) {
$customer = $_POST['customer'];
And this shows the first value of the array:
$customers = array(get_option('customer'));
foreach($customers as $customer){
echo $customer["customername"];
}
I hope this makes sence to anyone!!!!
Yes figured it out
Here goes for the ones that wish to know:
First create a function to get the current array.
Save the new value from the form with update_option
function savearray (){
if(isset($_POST['Submit'])) {
// get the option
$customers = get_option( 'customers' );
// add new data to the option
$customers[] = $_POST['customers'];
// save it back to the db
update_option( 'customers', $customers );
}
Then create a form that places data in arrays by name
<?php
$customers = '';
$customers .= '<tr><td>Name:<br/><input type="text" name="customers[name]" value="" /> </td></tr>';
$customers .= '<tr><td>Contact 1:<br/><input type="text" name="customers[contact1]" value="" /> </td></tr>';
echo $customers;
?>
So this works....
Now the next step.
I want to only show the name of the costumer and create a link to the data of the specific costumer.
So I did this:
<?php
$customers = get_option('customers');
foreach($customers as $val){
echo ''.$val["name"] . '<br>';
}
?>
This tells me that I want to view the name of all costumers in tha array and create a link.
I have no idea how to target the specific data in the array.
Anyone?????
I think you need to use ArrayObject
Ex:
<?php
// add a new consumer in your new array
$consumer["name"] = "John Doe";
$consumer["email"] = "toto#yopmail.com";
...
$a = new ArrayObject();
$a->append($consumer)
// for get a consumer in the array
foreach ($arr as $key => $value)
{
// Some instruction
}
?>
Hope it will help you

Categories