array_search function not returning values - php

Here am having two tables namely tools and tool_use.
tools table looks like this
id name tools_names quantity type
13 cutting player cutting playerA,cutting playerB,cutting playerC 3 engineer
12 REFLECTORS REFLECTORSA,REFLECTORSB 2 team
tool_use table looks like this
id user_id type tools
8 siraj engineer cutting playerA,cutting playerB
7 siraj team REFLECTORSB
6 siraj team REFLECTORSA
i want to display the tools_names except inserted to tool_use table while inserting but the entire tools_names are displaying eventhough the result looks like in the table.here is my control
public function ajax_tools()
{
$data['tools']=$this->Tools_model->view_available_tools($_POST['type']);
foreach ($data['tools'] as $key=>$val) {
$data['toolss'][] =explode(',',$val['tools_names']);
}
$data['tools_names'] = $this->Tools_model->get_tool_names($_POST['type'])->result();
foreach ($data['tools_names'] as $row)
{
if (($key =array_search($row->tools,$data['toolss'])) !== false)
{
unset($data['toolss'][$key]);
$data['toolss'] = array_values($data['toolss']);
}
}
return $data['toolss'];
$this->load->view('ajax_tools',$data);
}
Here is my models
public function view_available_tools($type)
{
$this->db->order_by('id','desc');
$this->db->where('status',1);
$this->db->where('type',$type);
$query=$this->db->get('tools');
return $query->result_array();
}
public function get_tool_names($type)
{
return $this->db->get_where('tool_use',array('type'=>$type));
}
this is my view
<div class="form-group">
<label for="type" class="control-label">Type:</label>
<select name="type" id="type" class="form-control" required>
<option value="">please select</option>
<option value="team" <?php echo set_select('type','team'); ?>>Team</option>
<option value="engineer" <?php echo set_select('type','engineer'); ?>>Engineer</option>
</select>
</div>
<div class="form-group ">
<label for="tools" class="control-label">Tools:</label>
<select name="tools[]" id="tools" multiple="multiple" required>
<option value="">please select</option>
</select>
</div>
<script>
$('#type').change(function(){
var type=$('#type').val();
var url='<?php echo base_url(); ?>tools/tools_control/ajax_tools';
$.post(url, {type:type}, function(data)
{
$('#tools').html(data);
});
});
</script>
please help me to solve my issue

When you array_search, you're trying to search for $row->tools which supposedly contains cutting playerA,cutting playerB. And you search for that inside an array that does not contain the same kind of comma-separated lists of values but instead contains their exploded versions (as you did an explode on line 3).

if tools in table tool_use contain single values i find it out the solution but if it contains more values i mean stored as an array keeping me away from the destination please have a look
public function ajax_tools()
{
$data['tools']=$this->Tools_model->view_available_tools($_POST['type']);
foreach ($data['tools'] as $key=>$val)
{
$data['toolss'][] = $data['t']=explode(',',$val['tools_names']);
}
$data['tools_names'] = $this->Tools_model->get_tool_names($_POST['type'])->result();
var_dump($data['tools_names']);
foreach ($data['tools_names'] as $val)
{
if (($key =array_search($val->tools,$data['t'])) !== false)
{
unset($data['t'][$key]);
$data['t'] = array_values($data['t']);
}
}
$this->load->view('ajax_tools',$data);
}

Related

Remove duplicates in php drop down list

I have a php drop down list which retrieves locations from a database, it gets all the data correctly, but sometimes if two records has the same in the database, it will add the item twice in the drop down. This is a location drop down, and some locations are duplicates, i would like to know what code can i add to remove duplicate entries and just keep one.
Here is my code:
<label for="select-service">
<strong>Enter a Location:</strong>
</label>
<select class="form-control" id="select-location" class="col-xs-12 col-sm-4 form-control" required>
<option value="">Select Location</option>
<?php
foreach($appointment_locations as $location) {
$LocationsArray = explode(",", $location->notes);
foreach($LocationsArray as $singleLocation):
?>
<option value="<?=$singleLocation ?>"><?=$singleLocation ?></option>
<? endforeach;
};?>
</select>
EDIT:
Here is the output
I tried using foreach(array_unique($appointment_locations) as $location) { but it doesnt show my second provider when i click on the location Rosebank
1) validate your inserted data to avoid such a situations
2) why you do not group by your retrieved data from database?
if you do not have access to do this, you can try a simple solution rather than the array_unique solution
$tmp = [];
foreach ($repeatedLocations as $location) {
if (isset($tmp[$location]) == false) {
// do your stuff
$tmp[$location] = true;
}
}
unset($tmp);
try
foreach(array_unique($appointment_locations) as $location) {
//... code
or
$LocationsArray = array_unique(explode(",", $location->notes));
https://www.php.net/manual/en/function.array-unique.php

How to add multiple selected values into a single column in PHP CodeIgniter?

I'm working on a project where I need to add multiple selected values into a single Column using Php CodeIgniter.
Here's the actual problem statement:
I have a INT column total_persons to store the number of total people (i.e. 5) and a VARCHAR column person_names which would store the names of those 5 people.
To select multiple users from dropdown, I'm using Select2 library.
But when I submit the data, following error pops up
The Person Names field is required.
Of course it is because I've set validation rules on the form as follows:
$this->form_validation->set_rules('person_names','Person Names','required');
I don't understand why it does not take any value when there are 5 user names selected.
If I add ID of a single user (keeping the column to be INT) instead of multiple selected values, it works fine and sends data in DB. But when I try to store multiple usernames, it throws the error I pasted above.
Here's my Expense.php code from Controller
function add()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('expense_type','Expense Type','required');
$this->form_validation->set_rules('person_names','Person Names','required');
$this->form_validation->set_rules('total_persons','Total Persons','required');
$this->form_validation->set_rules('expense_amount','Expense Amount','required');
$this->form_validation->set_rules('expense_details','Expense Details','required');
$this->form_validation->set_rules('date_added','Date Added','required');
if($this->form_validation->run())
{
$params = array(
'expense_type' => $this->input->post('expense_type'),
'total_persons' => $this->input->post('total_persons'),
'person_names' => $this->input->post('person_names'),
'expense_amount' => $this->input->post('expense_amount'),
'expense_details' => $this->input->post('expense_details'),
'date_added' => $this->input->post('date_added'),
'update_date' => $this->input->post('update_date'),
);
print_r($params);
exit();
$expense_id = $this->Expense_model->add_expense($params);
redirect('expense/index');
}
else
{
$this->load->model('Expense_type_model');
$data['all_expense_type'] = $this->Expense_type_model->get_all_expense_type();
$this->load->model('User_model');
$data['all_users'] = $this->User_model->get_all_users();
$data['_view'] = 'expense/add';
$this->load->view('layouts/main',$data);
}
}
Expense_Model.php
function add_expense($params)
{
$this->db->insert('expense',$params);
return $this->db->insert_id();
}
view.php
<div class="col-md-6">
<label for="person_names" class="control-label"><span class="text-danger">*</span>Person Names</label>
<div class="form-group">
<select name="person_names[]" class="form-control multiselect" multiple="multiple">
<option value="">select user</option>
<?php
foreach($all_users as $user)
{
$selected = ($user['user_name'] == $this->input->post('person_names')) ? ' selected="selected"' : "";
echo '<option value="'.$user['user_name'].'" '.$selected.'>'.$user['user_name'].'</option>';
}
?>
</select>
<span class="text-danger"><?php echo form_error('person_names');?></span>
</div>
</div>
If I'm not missing some key point, the code should add five names in the user_name field as follows?
["user1", "user2", "user3", "user4", "user5"]
(This is my assumption, apologies if I've guessed it wrong)
Can someone help me figure out where am I making a mistake?
Thanks very much in advance.
CodeIgniter Form Validation class supports the use of arrays as field names. In order to use it, you need to include the [] on the validation rules :
$this->form_validation->set_rules('person_names[]','Person Names','required');
And also on the form error :
form_error('person_names[]')
Edit
In order to save the array in a single column, you could json_encode it first, to get json formatted string which you could retrieve the data later as array using json_decode :
$params = array(
'expense_type' => $this->input->post('expense_type'),
'total_persons' => $this->input->post('total_persons'),
'person_names' => json_encode($this->input->post('person_names')),
'expense_amount' => $this->input->post('expense_amount'),
'expense_details' => $this->input->post('expense_details'),
'date_added' => $this->input->post('date_added'),
'update_date' => $this->input->post('update_date'),
);
In this way you can save your multiple persons ids in single column by seperating them with space .
You can get the saved ids by taking ids into array and using jquery you can explode it and show in multiple select field.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" id="alertrecepients" name="alertrecepients" multiple size="10">
<?php
if(!empty($users)){
foreach ($users as $cl){
?>
<option value="<?php echo $cl->userId ?>"
<?php
$x = 0;
$paramArray31=explode(' ',$alertrecepients);
$limit= count($paramArray31);
while($x <= $limit-1) {
if ($paramArray31[$x] == $cl->userId) {
echo "selected";
}
$x++;
}
?>>
<?php echo $cl->name ?></option>
<?php }} ?>
</select>
<script>
$( "select[name='alertrecepients']" )
.change(function() {
var str = "";
$( "select[name='alertrecepients'] option:selected" ).each(function() {
str += $( this ).val() + " ";
});
$( "#selectedrecepients" ).val( str );
})
.trigger( "change" );
</script>
<input type="hidden" value="<?php echo $alertrecepients; ?>" name="selectedrecepients" id="selectedrecepients" />
I am not familiar with snippet, so i am posting answer like this.

Retrieve name ID from php json file

I have this php file for country/state/town list using json method.
PHP file:
sleep(1);
$stateID = $_GET['stateID'];
$countyID = $_GET['countyID'];
$townID = $_GET['townID'];
$html = $_GET['html'];
$states = array();
$states['MA'] = "Massachusetts";
$states['VT'] = "Vermont";
$states['SC'] = "South Carolina";
$counties = array();
$counties['MA']['BARN'] = 'Barnstable';
$counties['MA']['PLYM'] = 'Plymouth';
$counties['VT']['CHIT'] = 'Chittenden';
$counties['SC']['ANDE'] = 'Anderson';
$towns = array();
$towns['MA']['BARN']['CHA'] = "Chatham";
$towns['MA']['BARN']['DEN'] = "Dennis";
$towns['MA']['BARN']['YAR'] = "Yarmouth";
$towns['MA']['PLYM']['BRI'] = "Bridgewater";
$towns['MA']['PLYM']['MAR'] = "Marshfield";
$towns['MA']['PLYM']['WAR'] = "Wareham";
$towns['VT']['CHIT']['BUR'] = "Burlington";
$towns['VT']['CHIT']['ESS'] = "Essex";
if($stateID && !$countyID && !$townID){
echo json_encode( $counties[$stateID] );
} elseif( $stateID && $countyID && !$townID ) {
echo json_encode( $towns[$stateID][$countyID] );
} elseif( isset($villages[$stateID][$countyID][$townID]) ) {
echo json_encode( $villages[$stateID][$countyID][$townID] );
} else {
echo '{}';
}
I retrieve value from MySql database(example:MA for country).
Now I need to print country/state/town name into select box dropdown like this.
<select id="country" class="validate[required]" name="country">
<option value="0">Choose ...</option>
<option selected="selected" value="'.$country['selector'].'">Show Country Name From php File</option>
</select>
<select id="state" class="validate[required]" name="state">
<option value="0">Choose ...</option>
<option selected="selected" value="'.$state['selector'].'">Show state Name From php File</option>
</select>
<select id="town" class="validate[required]" name="town">
<option value="0">Choose ...</option>
<option selected="selected" value="'.$town['selector'].'">Show town Name From php File</option>
</select>
How can I print this?
Create a php file that makes the call to the database. The results are, normally, stored in a php array. You can turn this array into Json using json_encode()(http://www.php.net/manual/en/function.json-encode.php).
Simply echo this in the php-file.
Now call that script with jQuery. There is a simple jQuery method called getJson(). - Read more about it here: http://api.jquery.com/jquery.getjson/
This will bring the MySQL results to you - in Json form - and you could now use JavaScript to loop the results, and display the form accordingly. A simple example would be (I haven't tested this but I hope you get the idea):
$.each(data, function() {
$('#mySelect')
.append($("<option></option>")
.attr("value",data[row].NameOfColumn)
.text(value));
row ++;
});
Note the name of column - that's the name of the key for the value you are looking for. In your case you might want to loop the keys as well - with an outer loop - since the data seems to be presented in such a matter.

PHP multiple Dropdown list, not passing arrayto foreach() PHP newbie

services = $row['services_provided'];//services is in the projects table, cmt_services
<select name="services" multiple> <?php
dbConnect();
$result=mysql_query("SELECT * FROM cmt_services order servicesid");
while ($result2=mysql_fetch_array($result)) {
$Selectedservice="";
if (is_array($s_p)){
foreach ($services as $key=> $value) {
if ($result2['servicesid']==$value)
{
$Selectedservice = "selected";}
}
echo '<option value="'.$result2['servicesid'].'"'.$SelectedBus.'>'.$result2['service_name'].' '.$SelectedBus.'</option>';
}
}?>
</select>
//
Dropdown populates using data in cmt_services stored in project table using servicesid as 1,2,3. How can I display 1,2,3 as selected among 1,2,3,4,5,6?
There is a little trick in PHP where you use square-braces to tell PHP to expect an array:
<select name="services[]" multiple>
You should now find that you automatically have an array from your request.
$services = $_POST['services']; // this is an array

post values from a multiselect list to a mysql query using php and jquery

Hi guys I am trying to post values which is getting number from another text box for MySQL select query but i am stuck can u please help me here is my code when I try to get result I cannot add comma(,) between values. also tried implode() and explode() function but the result only got number of array element please help me. I will be glad to try your ideas thanks.
on my sql query i get only row as a result which is my first select
thanks a lot for your help again guys
function exportselectionlist(){
var qcolumns=document.getElementById('selectionlist');
for (i=0; i < qcolumns.length; i++) {
qcolumns.options[i].selected = true;
}
document.selectionlist_form.submit();
}
<form id="selectionlist_form" action="xxx.php" method="post"
name="selectionlist_form">
<select id="selectionlist" style="width:300px;" multiple="multiple" size="4"
name="selectionlist[]">
<option value=""></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
<input type="submit" value="x" />
<a onclick="exportselectionlist()" href="javascript:;">Export</a>
</form>
//xxx.php
<?php foreach ($selectionlist as $value) {
$resultstr = array();
foreach ($selectionlist as $result)
$resultstr[] = $result;
echo $x=implode(",",$resultstr);
sql = mysql_query("SELECT * FROM table where idArticle in ('$x')");
Try changing your js function to:
function exportselectionlist() {
var qcolumns = document.getElementById('selectionlist');
for (i=0; i < qcolumns.length; i++) {
qcolumns.options[i].selected = true;
}
document.selectionlist_form.submit();
}
and then your "xxx.php" to:
$selectionlist = $_POST['selectionlist'];
echo implode(',', $selectionlist);
As a side note, your php code indicates to me that you have register_globals turned on? I would recommend turning that off in favor of creating the variable you need from the $_POST superglobal.

Categories