Cant work 4th column in dependant select box - php

I have csv with 4 columns. If i select make it shows models then year. I want it to show versions at the 4th box. however nothing happens. i have changed code and it will show versions in the 3rd box and then years disappears. still nothing in 4th box.
Played around with this bit of the code which makes the above effect but cant figure out why the 4th select box dont work.
$makes_models_years_versions = array();
$uploads_folder = wp_upload_dir()['basedir'];
$file = fopen($uploads_folder.'/make_model_year_version.csv', 'r');
$firstline = true;
while (($line = fgetcsv($file)) !== FALSE) {
if ($firstline){
$firstline = false;
continue;
}
$makes_models_years_versions[$line[0]][$line[1]][$line[2]][] = $line[3];
}
COMPLETE CODE BELOW:
function ajax_cf7_populate_values() {
// read the CSV file in the $makes_models_years_versions array
$makes_models_years_versions = array();
$uploads_folder = wp_upload_dir()['basedir'];
$file = fopen($uploads_folder.'/make_model_year_version.csv', 'r');
$firstline = true;
while (($line = fgetcsv($file)) !== FALSE) {
if ($firstline){
$firstline = false;
continue;
}
$makes_models_years_versions[$line[0]][$line[1]][$line[2]][] = $line[3];
}
fclose($file);
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'makes' => array_keys($makes_models_years_versions),
'models' => array(),
'years' => array(),
'versions' => array(),
'current_make' => false,
'current_model' => false,
'current_year' => false
);
// collect the posted values from the submitted form
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
$year = key_exists('year', $_POST) ? $_POST['year'] : false;
$version = key_exists('version', $_POST) ? $_POST['version'] : false;
// populate the $return_array with the necessary values
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = array_keys($makes_models_years_versions[$make]);
if ($model) {
$return_array['current_model'] = $model;
$return_array['years'] = $makes_models_years_versions[$make][$model];
if ($year) {
$return_array['current_year'] = $year;
$return_array['versions'] = $makes_models_years_versions[$make][$model][$year];
if ($version) {
$return_array['current_version'] = $version;
}
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
}
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );

Related

jquery $.post function is not executing the function

I am trying to post data to populate my HTML dropdowns using jQuery's $.post as shown below.
var county = $("#county");
var constituency = $("#constituency");
var ward = $("#ward");
populate_fields();
$('select[name="political"]').change(function(ev) {
ev.preventDefault();
populate_fields();
});
function populate_fields() {
// call the server side script, and on completion, update all dropdown lists with the received values.
county.html('').append($('<option>').text('Please choose a county'));
constituency.html('').append($('<option>').text('Please choose a constituency'));
ward.html('').append($('<option>').text('Please choose a ward'));
var data = {
// pass all the currently selected values to the server side script.
"county" : county.val(),
"constituency" : constituency.val(),
"ward" : ward.val()
}
$.post('php/dropdown.php', data, function (resp) {
console.log('function works');
all_values = resp;
$.each(all_values.county, function () {
$option = $("<option>").text(this).val(this);
if (all_values.current_county == this) {
$option.attr('selected', 'selected');
}
county.append($option);
});
$.each(all_values.constituency, function () {
$option = $("<option>").text(this).val(this);
if (all_values.current_constituency == this) {
$option.attr('selected', 'selected');
}
constituency.append($option);
});
$.each(all_values.ward, function () {
$option = $("<option>").text(this).val(this);
if (all_values.current_ward == this) {
$option.attr('selected', 'selected');
}
ward.append($option);
});
},'json');
}
the php file being referred to works perfectly, however the post does not receive data from this file and the function does not execute, I have traced the problem to the above snippet of code. Anyone have an Idea as to what could be the problem?
Here is my php Code as requested for more insight into the problem:
<?php
// read the CSV file in the $makes_models_years array
$makes_models_years = array();
//$uploads_folder = wp_upload_dir()['basedir'];
$file = fopen("./resources/polling_data.csv","r");
$firstline = true;
while (($line = fgetcsv($file)) !== FALSE) {
if ($firstline) {
$firstline = false;
continue;
}
$makes_models_years[$line[0]][$line[1]][] = $line[2];
}
fclose($file);
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'county' => array_keys($makes_models_years),
'constituency' => array(),
'ward' => array(),
'current_county' => false,
'current_constituency' => false
);
// print_r($return_array);
// collect the posted values from the submitted form
$make = key_exists('county', $_POST) ? $_POST['county'] : false;
$model = key_exists('constituency', $_POST) ? $_POST['constituency'] : false;
$year = key_exists('ward', $_POST) ? $_POST['ward'] : false;
// populate the $return_array with the necessary values
if ($make) {
$return_array['current_county'] = $make;
$return_array['constituency'] = array_keys($makes_models_years[$make]);
if ($model) {
$return_array['current_constituency'] = $model;
$return_array['ward'] = $makes_models_years[$make][$model];
if ($year) {
$return_array['current_ward'] = $year;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
print_r($return_array);
die();
?>
I realised that the issue was in the post not being able to read data returned by the php file. I solved it by placing the php file in the same directory as the javascript file, apparently they don't work well when in placed separate folders.

Mantis - Import CSV File - Throwing Error as APPLICATION ERROR #11

I am geeting the below error A necessary field "Summary" was empty. Please recheck your inputs.Can anyone suggest how to proceed.
I have mapped the summary column in import but still shows the error.
<?php
class Csv_importPlugin extends MantisPlugin
{
function register() {
$this->name = plugin_lang_get( 'title' );
$this->description = plugin_lang_get( 'description' );
$this->version = '2.0.0';
$this->requires = array( 'MantisCore' => '2.0.0' );
$this->author = 'Bug 4220 Team';
$this->contact = 'https://github.com/mantisbt-plugins/csv-import/';
$this->url = 'https://github.com/mantisbt-plugins/csv-import/';
$this->page = 'config';
}
function config() {
return array(
'import_issues_threshold' => MANAGER ,
);
}
function hooks() {
return array(
'EVENT_MENU_MANAGE' => 'csv_import_menu',
);
}
function csv_import_menu() {
return array(
'' . plugin_lang_get( 'manage_issues_link' ) . '',
);
}
}
Try this. No need of plugin
Let's say you have a CSV file with file columns
$file = $_FILES['csv_file']['tmp_name']; //get CSV file
$handle = fopen($file, "r"); //handle
while(($filesop = fgetcsv($handle, 1000, ",")) !== false){ //start while loop
$sname = $filesop[0];
$fname = $filesop[1];
$oname = $filesop[2];
$gender= $filesop[3];
$country= $filesop[4];
// Put your SQL code to insert before while loop ends
} //end while loop

Phpexcel replace null value with empty string

I have noticed that if a cell is empty phpexcel gives it a null value. Is there a way i can replace the null value with any empty string before i loop through the array and store into the database. Below is my code and i am using the codeigniter framework.
public function import(){
$id = $this->session->userdata('company_id');
$directoryname = get_company_full_name($id);
if (!is_dir(FCPATH.'assets/customer_documents/Databases/'.$directoryname)) {
mkdir(FCPATH.'assets/customer_documents/Databases/'.$directoryname, 0777, TRUE);
}
$database_name = $this->input->post('database_name');
// $data['addressbook'] = $this->csv_model->get_addressbook($id);
$data['errors'] = ''; //initialize upload error array to empty
$config['upload_path'] = FCPATH.'assets/customer_documents/Databases/'.$directoryname;
$config['allowed_types'] = '*';
$config['max_size'] = '';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$data['errors'] = $this->upload->display_errors();
$data['databases'] = $this->database->get_databases($id);
$this->session->set_flashdata($data);
redirect(base_url().'Databases');
} else {
$file_data = $this->upload->data();
$file_ext = $file_data['file_ext'];
// use custom function to determine if filetype is allowed
if (allow_csv_type($file_ext))
{
$file_path = FCPATH.'assets/customer_documents/Databases/'.$directoryname. '/' .$file_data['file_name'];
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file_path);
$date_uploaded = date("Y-m-d H:i:s");
if ($objPHPExcel) {
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
// array_shift($arr_data); // removes the 1st/header element
//store the database name and details
$database_data = array(
'db_name'=>$database_name,
'company_id' => $id,
'deleted' => 0,
'date_uploaded'=> $date_uploaded
);
$this->database->insert_db($database_data);
$database_id = $this->db->insert_id();
foreach ($arr_data as $row) {
$insert_data = array(
'company_id' => $this->session->userdata('company_id'),
'number'=>$row['A'],
'province'=>$row['B'],
'district'=>$row['C'],
'ward'=>$row['D'],
'farming_type'=>$row['E'],
'commodity'=>$row['F'],
'database_name'=>$database_name,
'db_id' =>$database_id,
'deleted' => 0,
'date_uploaded'=>$date_uploaded
);
$this->database->insert_csv($insert_data, $id);
}
log_message('info', '*****************************Customer with the ID: '.$this->session->userdata('company_id').' and name: '.get_company_full_name($this->session->userdata('company_id')).' uploaded a csv database. The uploder phone number: '.$this->session->userdata('phone').' The database ID: '.$database_id.' The database name: '.$database_name.'*****************************');
$this->session->set_flashdata('success', 'Data Imported Succesfully');
redirect(base_url().'Databases');
} else{
$data['errors'] = "Error occured";
$data['page_class'] = 'Databases-page';
$data['title'] = 'Databases';
$data['content_view'] = 'Databases/index';
$this->template->admin_template($data);
}
}
else {
$this->session->set_flashdata('errors','File type is not allowed!');
redirect('Databases');
}
}
}
}
I am just looking for a way i can add empty sting values on the empty cells that are coming with null values.
Just use a simple array modifier before it reaches PHPExcel.
If performance is an issue, one may consider not to create multiple functions within array_map(). Note that isset() is extremely fast, and this solutions does not call any other functions at all.
$replacements = array(
'search1' => 'replace1',
'search2' => 'replace2',
'search3' => 'replace3'
);
foreach ($a as $key => $value) {
if (isset($replacements[$value])) {
$a[$key] = $replacements[$value];
}
}
See: https://stackoverflow.com/a/32321702/4272537

php Notice: array to string conversion

hi all im new ish to php and new to stack overflow but do have some knowledge in php what im trying to do is get one value from my returned array call from an api function is
$character->getSlot('head');
using print_r gives me:
Array (
[icon] => http://url to image location
[name] => Wizard's Petasos
[slot] => head )
if i echo $character->getSlot('head', 'name); gives me C:\xampp\htdocs\test\index.php on line 19 and just returns the word Array
here is the section of index.php
<?php
include('api.php');
// Call API
$API = new LodestoneAPI();
// Search for: Demonic Pagan on Sargatanas
$character = $API->get(array(
"name" => "Darka Munday",
"server" => "Ragnarok"
));
// Basic character data
echo "Character ID: " . $character->getID();
$ID = $character->getID();
$API->parseProfile($ID);
$Character = $API->getCharacterByID($ID);
echo $character->getSlot('head', 'name');
and the section of the api just in case
// GEAR
public function setGear($Array)
{
$this->Gear['slots'] = count($Array);
$GearArray = NULL;
// Loop through gear equipped
$Main = NULL;
foreach($Array as $A)
{
// Temp array
$Temp = array();
// Loop through data
$i = 0;
foreach($A as $Line)
{
// Item Icon
if (stripos($Line, 'socket_64') !== false) { $Data = trim(explode('"', $A[$i + 1])[1]); $Temp['icon'] = $Data; }
if (stripos($Line, 'item_name') !== false) { $Data = trim(str_ireplace(array('>', '"'), NULL, strip_tags(html_entity_decode($A[$i + 2])))); $Temp['name'] = htmlspecialchars_decode(trim($Data), ENT_QUOTES); }
if (stripos($Line, 'item_name') !== false) {
$Data = htmlspecialchars_decode(trim(html_entity_decode($A[$i + 3])), ENT_QUOTES);
if (
strpos($Data, " Arm") !== false ||
strpos($Data, " Grimoire") !== false ||
strpos($Data, " Tool") !== false
)
{ $Main = $Data; $Data = 'Main'; }
$Temp['slot'] = strtolower($Data);
}
// Increment
$i++;
}
// Slot manipulation
$Slot = $Temp['slot'];
if (isset($GearArray[$Slot])) { $Slot = $Slot . 2; }
// Append array
$GearArray['numbers'][] = $Temp;
$GearArray['slots'][$Slot] = $Temp;
}
// Set Gear
$this->Gear['equipped'] = $GearArray;
// Set Active Class
$classjob = str_ireplace('Two-Handed ', NULL, explode("'", $Main)[0]);
$this->Stats['active']['class'] = $classjob;
if (isset($this->Gear['soul crystal'])) { $this->Stats['active']['job'] = str_ireplace("Soul of the ", NULL, $this->Gear['soul crystal']['name']); }
}
public function getGear() { return $this->Gear; }
public function getEquipped($Type) { return $this->Gear['equipped'][$Type]; }
public function getSlot($Slot) { return $this->Gear['equipped']['slots'][$Slot]; }
the solution to this is probably really simple and im being really dumb but any help would be great :) thanks in advance
public function getSlot($Slot) {
return $this->Gear['equipped']['slots'][$Slot];
}
getSlot method have only one argument. You are passing another argument but getSlot method returns array.
You can do like this :
public function getSlot($Slot, $param = null) {
if(empty($param)) {
return $this->Gear['equipped']['slots'][$Slot];
} else {
if(isset($this->Gear['equipped']['slots'][$Slot][$param] )) {
return $this->Gear['equipped']['slots'][$Slot][$param];
} else {
return null;
}
}
}
OR
echo $character->getSlot('head')['name'] // If version is >= 5.4.*
If version < 5.4.*
$slot = $character->getSlot('head');
echo $slot['name'];

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