Echo only the duplicate values of array_count_values result php - php

After both myself and a friend searching for hours upon end, and trying numerous things we are unable to find out how to echo only the duplicate values of array_count_values result. I will break it down:
We have numerous select boxes, which build the array when sent via GET, for example:
<div class="form-group col-sm-2 mb-sm">
<select name="select[]" class="form-control">
<option value="" disabled="" selected="">Select</option>
<option value="optionOne">Option 1</option>
<option value="optionTwo">Option 2</option>
</select>
</div>
<div class="form-group col-sm-2 mb-sm">
<select name="select[]" class="form-control">
<option value="" disabled="" selected="">Select</option>
<option value="optionOne">Option 1</option>
<option value="optionTwo">Option 2</option>
</select>
</div>
<div class="form-group col-sm-2 mb-sm">
<select name="select[]" class="form-control">
<option value="" disabled="" selected="">Select</option>
<option value="optionOne">Option 1</option>
<option value="optionTwo">Option 2</option>
</select>
</div>
We are then doing the following:
if (max(array_count_values($_GET['select'])) == 2) {
$twoSelected = '2 of the selections are the same, which were (DUPLICATE SELECTION HERE)';
}
We have tried a foreach loop, but can't seem to get it to work.
Any help will be very much appreciated.
Kind Regards

Try this one
$array = array("test", "hello", "test", "world", "hello");
$duplicatedValuesArray = array_keys(array_filter(array_count_values($array), function($v) {
return $v > 1;
}));
echo implode(', ',$duplicatedValuesArray);

I think below code is helpful for you to get duplicate value.
$array = array(1=>'12334',2=>'123345',3 =>'Helloo' ,4=>'hello', 5=>'helloo');
// Convert every array value to uppercase, and remove all duplicate values
$notdublicates = array_unique(array_map("strtoupper", $array));
// The difference in the original array $array, and the $notdublicates array
// will be the duplicate values
$getduplicates = array_diff($array, $notdublicates);
print_r($getduplicates);

Related

Working with session in PHP

I have a form from which i take some datas and using session i want to keep that datas as a history on my page, and also when i click on one line from my history i want my datas to be autocomplete in my form. I saw an example on one page and i tried doing it to apply to what i want but it's not quite functional.
This is my code for the form:
<form method="get">
Create:<br><br>
Name:<br> <input type="text" id="name" value="" /><br>
surname:<br> <input type="text" id="surname" value="" /><br>
Sex:<br> <div class="select-wrapper">
<select name="sex" id="sex">
<option value="">- Sex -</option>
<option value="woman">Woman</option>
<option value="male">Male</option>
</select>
</div>
Role: <div class="select-wrapper">
<select name="rol" id="rol">
<option value="">- Role -</option>
<option value="visitor">Visitor</option>
<option value="Professor">Professor</option>
<option value="Student">Student</option>
</select>
</div>
Text color: <div class="select-wrapper">
<select name="cul" id="cul">
<option value="">- Text color -</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
</select>
</div>
Font text: <div class="select-wrapper">
<select name="font" id="font">
<option value="">- Font text -</option>
<option value="15px Arial">Arial</option>
<option value="15px Times New Roman">Times New Roman</option>
<option value="15px Georgia">Georgia</option>
<option value="15px Comic Sans MS">Comic Sans MS</option>
<option value="15px Lucida Sans Unicode">Lucida Sans Unicode</option>
<option value="15px Courier New">Courier New</option>
</select>
</div>
Format : <div class="select-wrapper">
<select name="format" id="format">
<option value="">- Format -</option>
<option value="portrait">Portrait</option>
<option value="landscape">Landscape</option>
</select>
</div>
Style text: <div class="select-wrapper">
<select name="stil" id="stil">
<option value="">- Style text -</option>
<option value="stil1">Stil1</option>
<option value="stil2">Stil2</option>
<option value="stil3">Stil3</option>
<option value="stil4">Stil4</option>
<option value="stil5">Stil5</option>
<option value="stil6">Stil6</option>
</select>
</div>
</form>
And this is where i tried to use session:
<?php
session_start();
$createpas = parseRequest();
storecreatepas($createpas);
include "form.php";
$createpases = $_SESSION['createpases'];
include "history.php";
function storecreatepas($createpas) {
if (!isset($_SESSION['createpases'])) {
$_SESSION['createpases'] = [];
}
if (!$createpas->isEmpty()) {
$_SESSION['createpases'][] = $createpas;
}
}
function parseRequest() {
$createpas = new createpasRequest;
$createpas->cul = !empty($_GET['cul']) ? $_GET['cul'] : "";
$createpas->font = !empty($_GET['font']) ? $_GET['font'] : "";
$createpas->format = !empty($_GET['format']) ? $_GET['format'] : "";
$createpas->stil = !empty($_GET['stil']) ? $_GET['stil'] : "";
return $createpas;
}
/**
* createpas request
*/
class createpasRequest
{
public $cul = "";
public $font = "";
public $format = "";
public $stil = "";
function toQueryString() {
$params = [
'cul' => $this->cul,
'font' => $this->font,
'format' => $this->format,
'stil' => $this->stil
];
return http_build_query($params);
}
function isEmpty() {
return !$this->cul || !$this->font || !$this->format || !$this->stil;
}
function culAsObject() {
return new DateTime($this->cul);
}
function fontAsObject() {
return new DateTime($this->font);
}
function formatAsObject() {
return new DateTime($this->format);
}
function stilAsObject() {
return new DateTime($this->stil);
}
}
And the display code:
<ul>
<?php
foreach ($createpases as $s) {
?>
<li><a href="search.php?<?php echo $s->toQueryString() ?>">
<?php echo $s->cul?> - <?php echo $s->font?> - <?php echo $s->format?> - <?php echo $s->stil?>
</a></li>
<?php
}
?>
</ul>
It works just fine until some point. It gets my datas from my form posts them on the page but when i click on them they don't autocomplete in in my form. And also if i want the options to be unique in the list how can i do that? Right now if i complete the same datas 2 or 3 times they appear multiple times in my list.
Thank you for your help!
You need to start the session in the Form page and then check if the SESSION array contains the values to be echoed.
So your code will become:
<?php session_start();
if(!isset($_SESSION['name']){$_SESSION['name']=''}
if(!isset($_SESSION['sex']){$_SESSION['sex']=''}
if(!isset($_SESSION['rol']){$_SESSION['rol']=''}
?>
//this way you will not have issues on page first load before the user fills in the form
<form method="get">
Create:<br><br>
Name:<br> <input type="text" id="name" value="<?php echo $_SESSION['name']; ?>" /><br>
surname:<br> <input type="text" id="surname" value="" /><br>
Sex:<br> <div class="select-wrapper">
<select name="sex" id="sex">
<option value="" <?php if($_SESSION['rol']==''){echo 'selected'} ?>>- Sex -</option>
<option value="woman" <?php if($_SESSION['rol']=='woman'){echo 'selected'} ?>>Woman</option>
<option value="male" <?php if($_SESSION['rol']=='visitor'){echo 'selected'} ?>>Male</option>
</select>
</div>
Role: <div class="select-wrapper">
<select name="rol" id="rol">
<option value="" <?php if($_SESSION['rol']==''){echo 'selected'} ?>>- Role -</option>
<option value="visitor" <?php if($_SESSION['rol']=='visitor'){echo 'selected'} ?>>Visitor</option>
<option value="Professor"<?php if($_SESSION['rol']=='Professor'){echo 'selected'} ?>>Professor</option>
<option value="Student"<?php if($_SESSION['rol']=='student'){echo 'selected'} ?>>Student</option>
</select>
</div>
and so on.
It appears that your form does not auto-fill with the data because you do not have such a functionality implemented. This auto-complete functionality is not automatic, as in, the server does not do it for you.
Here is an example of what you need to do in order to get the autocomplete to work:
Name:<br> <input type="text" id="name" value="<?= $_SESSION['name'] ?>" /><br>
For the select to auto-complete, you'll need to do something like this:
<select name="cul" id="cul">
<option value="">- Text color -</option>
<option value="red" <? echo ($_SESSION['cul']==="red")?"selected='selected'":""; ?>>Red</option>
<option value="blue" <? echo ($_SESSION['cul']==="blue")?"selected='selected'":""; ?>>Blue</option>
<option value="black" <? echo ($_SESSION['cul']==="black")?"selected='selected'":""; ?>>Black</option>
</select>
This sets the value for each form element by directly setting the value / selected item using the $_GET data from a previous submission, or if there is no data, everything will be empty / default values.
Per a suggestion from one of the comments to this answer, I would like to point out that you must include "session_start()" to the top of the document if you wish to use the session variables on the document (if you have not done so already).
One question about the original question: is that first code block procedurally generated, or hand-typed?

How to combine several dropdown list values in mysql query?

<form method="post" action="search.php">
<select name="Num[]">
<option value="">Select One</option>
<option value="numofpeople">Number of people</option>
</select>
<select name="op[]">
<option value="">Select One</option>
<option value=">4">>4</option>
<option value=">2">>2</option>
</select>
<br />
<select name="num2[]">
<option value="">Select One</option>
<option value="price">Price</option>
</select>
<select name="op2[]">
<option value="">Select One</option>
<option value="<20000"><20000</option>
<option value="<40000"><40000</option>
</select>
<br />
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</form>
Here is my code to provide a dropdown list for the user. It will act as a filter to generate more specific result through mysql and don't get the logic to combine these dropdown values.
I would like to have something like:
Select * from hotel where price < 40000;
and I will provide all keywords after "Where".
Select boxes name are defined as array in html and your requirement is a user can select a single option in a select box. So you need to update the name of select boxes. You no need to add < in select box values, These conditions used at server end. I have corrected the HTML.
<form method="post" action="">
<select name="Num">
<option value="">Select One</option>
<option value="numofpeople">Number of people</option>
</select>
<select name="op">
<option value="">Select One</option>
<option value="4">>4</option>
<option value="2">>2</option>
</select>
<br />
<select name="num2">
<option value="">Select One</option>
<option value="price">Price</option>
</select>
<select name="op2">
<option value="">Select One</option>
<option value="20000"><20000</option>
<option value="40000"><40000</option>
</select>
<br />
<div class="input-group-btn">
<button class="btn btn-default" type="submit" name="search_btn"><i class="glyphicon glyphicon-search"></i> Search</button>
</div>
</form>
Server Side code for handle selected values and add to query.
if(isset($_POST['search_btn'])){
$conditons = array();
if(isset($_POST['Num'])){
$conditons[] = '`people` = "'.$_POST['Num'].'"';
}
if(isset($_POST['op'])){
$conditons[] = '`option` < '.$_POST['op'];
}
if(isset($_POST['price'])){
$conditons[] = '`price` = '.$_POST['price'];
}
if(isset($_POST['op2'])){
$conditons[] = '`op2` < '.$_POST['op2'];
}
$conditons = implode(' & ', $conditons);
echo $query = 'select * from hotel where '.$conditons;
}
You an update your real field name in conditions. After added conditions, result query will be as -
select * from hotel where `people` = "numofpeople" & `option` < 4 & `op2` < 20000
Here is a very generic example that I just put together. This code is not tested, but I have written like this before.
<?php
// Checks to see if post variables are available
if(isset($_POST)) {
// Creates original command
$query = "SELECT * FROM hotel WHERE "
// gets each value from the post
foreach($_POST as $key => $value) {
$query .= $key . "=" . $value . "AND ";
}
// Removes the trailing "AND "
$query = substr($query, 0, -4);
echo $query;
}
If you need to switch things up depending on key, you can just do a switch inside of the foreach statement that will check the key value. The key is the "name" attr that is assigned in the HTML that you are posting from.
This method is also not sanitized because I did not get a response to which connection type you are using, but it shouldn't be that hard. If you need me to write it, then I would be more than happy to do so.

passing values to sql through check boxes and dropdowns

How can i pass Drop down values to sql database and also the check box for example if a user selects English and maths than the value inserted in to the database would be 1 or else the value would be 0
<form>
<p id="p1">Select Your Year</p>
<select id="year_sel">
<option value="blank"></option>
<option id="primary" value="primary">Primary</option>
<option value="1">Year one</option>
<option value="2">Year two</option>
<option value="3">Year Three</option>
</select>
<input type="checkbox" name="Math" value="Math">Math<br>
<input type="checkbox" name="English" value="English">English<br>
<input type="checkbox" name="HealthScience" value="HealthScience">Health Science<br>
<input class="sub_reg" type="submit" value="Register Subjects" />
</form>
this is how my database looks like
First, your <select id="year_sel"> needs a name attribute to post ->
<select id="year_sel" name="year_sel" >
Since you are using <form> the default is get, so you would get the selected value in $_GET
$year_sel = $_GET['year_sel'];
If you changed it to
<form method="post">
then you would get it in $_POST
$year_sel = $_POST['year_sel']
Second, checkboxes are only posted if checked, so you can use isset() to set a value using a ternary -
$math = isset($_GET['Math']) ? 1 : 0;
$english = isset($_GET['English']) ? 1 : 0;
...[rest of your checkboxes]...
swap $_GET/$_POST like the select
$math = isset($_POST['Math']) ? 1 : 0;
$english = isset($_POST['English']) ? 1 : 0;
<select id="year_sel" name="year_sel">
<option value="primary">Primary</option>
<option value="1">Year one</option>
<option value="2">Year two</option>
<option value="3">Year Three</option>
</select>
on your form action something.php file use this to get the select value
$language = $_POST["year_sel"]; // chose whetever your form method
establish the database connection please do refer some tutorials (if you don't know )
write the mysqli insert command like
$SQL = "INSERT INTO yourtable (language) VALUES ('$language')";
mysqli_real_escape_string($sql);
$result = mysqli_query($sql) or die (mysqli_error());
now you can insert this value in your mysql or any database table
this is not tested
<form>
<p id="p1">Select Your Year</p>
<select id="year_sel" name="year_sel">
<option value="blank"></option>
<option id="primary" value="primary">Primary</option>
<option value="1">Year one</option>
<option value="2">Year two</option>
<option value="3">Year Three</option>
</select>
<?php
$variable = $_POST["year_sel"];
?>
Should mention the HTML ELEMENT name to get the value.

how to create a comma delimited array from an ordered select box in jquery

How can I create an array of items from a generated list using a select box to order the items and deliminate them by a comma.
Example...
I have a list of items generated by the id in the database with a select box associated with the item.
<?php
$sql = mysql_query("SELECT id, title FROM songs WHERE id='$id' ORDER BY title ASC");
while($row = mysql_fetch_array($sql)){
$id = $row['id'];
$title = $row['title'];
$song_chart .= '
<div id="$id">
<select>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
//etc...
</select>
'.$title.'
</div>';
}
$song_chart .= '<button></button>';
echo $song_chart;
?>
I have multiple items that I would like to select a value for.
If the value is greater than 0 than I want to grab the 'id' from the item the select is associated with and order all of the items by the selection (not the id).
Then I would like to post the information and place it into a comma delimited array to insert into my database.
I currently do not have any code that I have actually tried, I am really not sure how to go about this. Any help would be greatly appreciated. Thanks in advance!
EDIT
The output of the above would look like this...
<div id="1">
<select>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
//etc...
</select>
one
</div>
<div id="2">
<select>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
//etc...
</select>
two
</div>
<div id="3">
<select>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
//etc...
</select>
three
</div>
<div id="4">
<select>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
//etc...
</select>
four
</div>
<button></button>
Then on submit I would like to reorganize the generated id's accourding to the selected value and place then in an array/string like so...
var arr = '2, 3, 1, 4';
and post them to the database.
OK, in this situation, it's easier to encode the data in the value of the OPTION
<div id="3">
<select>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
//etc...
</select>
three
</div>
Becomes:
<div id="3">
<select>
<option val="3,1">1</option>
<option val="3,2">2</option>
<option val="3,3">3</option>
<option val="3,4">4</option>
//etc...
</select>
three
</div>
Embed the ID in the data. Comma separated.
I came with a solution with the help from Diodeus (Thanks).
$(document).ready(function(){
$('.selection').value(""); // clears the values
$('selection option').click(function(){ // when option is clicked
s=new Array(); // create array
$("select option:selected").each(function(){
// check to see which values are selected
var v = $(this).val();
if(v != ""){ // if the value is not empty.
s.push(v);
}
});
});
$("#submitList").click(function(){
if(s != ""){
alert(s);//or submit the list
}
});
});
I also changed a few things in the html output.
<div id="3">
<select class='selection'>
<option></option>
<option val="1,id">1</option>
<option val="2,id">2</option>
<option val="3,id">3</option>
<option val="4,id">4</option>
//etc...
</select>
three
</div>

How do I extract specific data with preg_match?

I'm looking to extract values from a whole load of html (i've just trimmed down to the relevant data), there are multiple 'select' elements, and only want to extract those who's 'name' element matches the name 'aMembers'. So the resulting values I would like to retrieve are 5,10,25 and 30 (see below) how can I achieve this with preg_match?
<DIV id="searchM" class="search"><select name="aMembers" id="aMembers" tabIndex="2">
<option selected="selected" value="">Data 3</option>
<option value="5">A name</option>
<option value="10">Another name</option>
</select>
</DIV>
<DIV id="searchM" class="search"><select name="bMembers" id="bMembers" tabIndex="2">
<option selected="selected" value="">Data 2</option>
<option value="15">A name</option>
<option value="20">Another name</option>
</select>
</DIV>
<DIV id="searchM" class="search"><select name="aMembers" id="Members" tabIndex="2">
<option selected="selected" value="">Data 1</option>
<option value="25">A name</option>
<option value="30">Another name</option>
</select>
</DIV>
I would try to split this task into 2 steps:
matching needed tags
matching needed values in them
This way would be easier:
$str = 'your HTML code here...';
preg_match_all('|<select name="aMembers".*?</select>|ms', $str, $matches);
foreach ($matches[0] as $select) {
preg_match_all('|value="(.+?)"|', $select, $matches2);
var_dump($matches2[1]);
}

Categories