How to Change Multiple Checkbox Query to Multiple Chosen jQuery? - php

I have a multiple checkbox query, as below
<span style="width:276px;display:inline-block;"> <input type="checkbox" name="check_list[]" value="sub_category_id = '1''">Name1</span>
<span style="width:276px;display:inline-block;"> <input type="checkbox" name="check_list[]" value="sub_category_id = '2'">Name2</span>
<span style="width:276px;display:inline-block;"> <input type="checkbox" name="check_list[]" value="sub_category_id = '3'">Name3</span>
<span style="width:276px;display:inline-block;"> <input type="checkbox" name="check_list[]" value="sub_category_id = '4'">Name4</span>
then
<?php
$names = implode(' or ', (array)$_POST['check_list'.$i]);
echo $names;
?>
I got part of my query.
sub_category_id = '1'' or sub_category_id = '2' or sub_category_id = '3' or sub_category_id = '4'
Using chosen Jquery, I´m able to retrieve the MySQL data (Name1, Name2, Name3, Name4), as below:
<select name="sub_category_id[]" id="sub_category_id[]" multiple class="chosen-select" tabindex="8">
<option value="">Selecione...</option>
<?php foreach ($arrEstados as $value => $name) {
echo "<option value='{$value}'>{$name}</option>";
}?>
</select>
$names = $_POST['sub_category_id'];
$query=implode('sub_category_id=', $names);
echo $query;
But the 'or' is missing. I don´t have great skills in PHP, so I ask: Is this the right way to get my query? I´m not using PDO or mysqli.

change your html select element to follow this:
<select name="check_list[sub_category_id][]" id="sub_category_id[]" multiple class="chosen-select" tabindex="8">
<option value="">Selecione...</option>
<?php
foreach ($arrEstados as $value => $name) {
echo "<option value='{$value}'>{$name}</option>";
}
?>
</select>
doing this will create an array like this in your $_POST:
$_POST => Array
(
[check_list] => Array
(
[sub_category_id] => Array
(
[0] => 2
[1] => 3
)
)
)
then change your PHP like so:
<?php
$names = isset($_POST['check_list']) && isset($_POST['check_list']['sub_category_id']) ? $_POST['check_list']['sub_category_id'] : NULL;
$query = "SELECT * FROM tablename WHERE ";
if(!is_null($names)){
foreach($names as $i => $name){
if($i !== 0){
$query .= " OR ";
}
$query .= "sub_category_id = '$name'";
}
}
echo($query);
//Output: SELECT * FROM tablename WHERE sub_category_id = '2' OR sub_category_id = '3'
}
?>
you might need to change the query to fit your application, but this will help get in you in the right direction.

As Martin suggest de http://www.tutorialspoint.com/mysql/mysql-in-clause.htm turns the simple way to solve it. That´s what i did:
<select chosen still the same...>
$sub_category_1 = $_POST['sub_category_id'];
$query=implode(',', $sub_category_1);
$sql = "Select * from table WHERE sub_category_id IN($query)";

Related

How to display the hotel names that have the maximum count from data base by calculating sum in PHP?

I am new to PHP coding. I want to display the names of the hotels from data base in ascending order according to the respective counts of the preferences selected by the user from the checkboxes. My code displays the names of the hotels according to the preferences entered by the user. The logic is to display the hotel name if there exists a "1" under the preference name in data base against that hotel. For example, if the user selects two checkboxes out of 7, "pool" and "gym" so, my code displays the hotels that have "1" in both the preferences of gym and pool in database. My data base looks like:
Hotel_id| Hotel_name| Pool| pool_count | Gym | gym_count| spa | spa_count| 0
1 Abc hotel 1 1.4 1 1.5 1 1.9
2 xyz hotel 1 1.2 0 0 0 0
3 xmk hotel 1 1.0 1 0.5 0 0
4 New hotel 1 1.99 0 0 0 0
5 old hotel 1 0.98 0 0 0 0
6 street hotel 1 0.78 0 0 0 0
. . . .
.
.
I am using SQLite3 for making data base. If the user selects the check boxes of pool, gym and spa then all those hotels that have a "1" under the column of the pool, gym and spa must be retrieved (my code does this) then it should calculate the sum of the respective counts. For example it should add pool_count with gym_count and spa_count and then display the names of the hotels in ascending order according to their respective total sum values. I have tried to implement it by first making an array that contains all the column names of the counts and then a query that calculates the sum but I don't get how can I pass the specific column name of the preferences that have been selected by the user.
php_checkbox.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>PHP: Get Values of Multiple Checked Checkboxes</title>
<link rel="stylesheet" href="css/php_checkbox.css"/>
</head>
<body>
<div class="container">
<div class="main">
<form action="checkbox_value.php" method="post">
<h2>PHP: Get Values of Multiple Checked Checkboxes</h2>
<select id="mySelect" name="list">
<option selected>Select a place</option>
<option value="1">Lahore</option>
<option value="2">Dubai</option>
<option value="3">New York</option>
<option value="4">Canberra</option>
<option value="5">London</option>
</select>
<p class="heading">Select Your Preferences:</p>
<input type="checkbox" name="check_list[]" value="pool" id="checkbox_1">
<label for="checkbox_1">Pool</label>
<input type="checkbox" name="check_list[]" value="gym" id="checkbox_2">
<label for="checkbox_2">Gym</label>
<input type="checkbox" name="check_list[]" value="spa" id="checkbox_3">
<label for="checkbox_3">Spa</label>
<input type="checkbox" name="check_list[]" value="is_beach" id="checkbox_4">
<label for="checkbox_1">Beach</label>
<input type="checkbox" name="check_list[]" value="is_wifi" id="checkbox_5">
<label for="checkbox_2">Wifi</label>
<input type="checkbox" name="check_list[]" value="is_familyoriented" id="checkbox_6">
<label for="checkbox_3">Family oriented</label>
<input type="checkbox" name="check_list[]" value="is_economical" id="checkbox_7">
<label for="checkbox_3">Value for money</label>
<div>
<input type="submit" name="submit" Value="Submit"/>
</div>
<?php include 'checkbox_value.php';?>
</form>
</div>
</div>
</body>
</html>
checkbox_value.php:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mytrip.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$hotelOptions = array('pool', 'gym', 'spa', 'is_wifi', 'is_beach', 'is_familyoriented', 'is_economical');
$countOptions = array('pool_count', 'gym_count', 'spa_count', 'wifi_count', 'beach_count','family_count','econo_count');
if (isset($_POST['submit'])) {
if (!empty($_POST['check_list']) && is_array($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
// Loop to store and display values of individual checked checkbox.
$where = '';
foreach($_POST['check_list'] as $selected) {
echo "<p>".$selected ."</p>";
if (array_search($selected, $hotelOptions) !== false) {
$where .= " AND {$selected} = 1";
}
}
$where = substr($where, 5, strlen($where));
// $sql = "SELECT hotel_name FROM Dubai WHERE ".$where.";";
$query= "SELECT SUM( ) FROM Dubai WHERE ".$where.";";
$sql = "SELECT hotel_name FROM Dubai WHERE ".$where.";";
echo "<p>".$where ."</p>";
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
} else {
echo "<b>Please Select Atleast One Option.</b>";
}
The second task that I want to achieve is to display the data according to the destination selected by the user in the drop down list in "php_checkbox.php" code. I have given unique id's to each option in the list but don't get how can I dynamically send the city name in the query to open the table of that destination. My current query looks like:
SELECT hotel_name FROM London WHERE
How can I open the table for the city that has been selected from the drop down list by the user?
Help in this regard shall be highly appreciated.
You should make ordering by selected fields almost the same as $where is done. I would map option names to their respective column counts: 'pool' => 'pool_count'. Choosing from table selected by user is even more straightforward, just make array containing input values as indexes, table name as values and pick concatenate chosen index into query.
I have used simplified version of your code (only one city, less columns) but logic would work with your data as well just adjust it. There is one thing left, you should handle case where $_POST['list'] does not contain proper value.
Here's code:
$hotelOptions = array('swimming_pool', 'roof_top', 'sea_side');
$countOptions = array(
'swimming_pool' => 'swimming_pool_count',
'roof_top' => 'roof_top_count',
'sea_side' => 'sea_side_count',
);
$cities = array(1 => 'Dubai');
if (isset($_POST['submit'])) {
if (!empty($_POST['check_list']) && is_array($_POST['check_list'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['check_list']);
echo "You have selected following ".$checked_count." option(s): <br/>";
// Loop to store and display values of individual checked checkbox.
$where = '';
$order = '';
foreach($_POST['check_list'] as $selected) {
echo "<p>".$selected ."</p>";
if (array_search($selected, $hotelOptions) !== false) {
$where .= " AND {$selected} = 1";
$order .= " {$countOptions[$selected]} DESC,";
}
}
$where = substr($where, 5, strlen($where));
$order = substr($order, 0, strlen($order) - 1);
if (isset($cities[$_POST['list']])) {
$sql = "SELECT hotel_name FROM ".$cities[$_POST['list']]." WHERE ".$where." ORDER BY ".$order.";";
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "<p> <br /></p>\n";
echo "\n". $row['hotel_name'] . "\n";
}
$db->close();
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
}
} else {
echo "<b>Please Select Atleast One Option.</b>";
}
}
it should add pool_count with gym_count and spa_count and then display
the names of the hotels in ascending order according to their
respective total sum values
For this you can do it in multiple way,
Get the submitted checkboxes, now when you have them just loop through them and make the string if it is checked:
$query_string = '';
foreach($selected_checkboxes as $name=>$value)
{
if($value==1)
$query_string .= "`$name` + ";
}
$query_string = rtrim($query_string, " + ");
Query:
SELECT *, ($query_string) AS AMENITIES_COUNT
FROM xyz
ORDER BY AMENITIES_COUNT DESC
PHP:
Just sum the amenities in the usort function and sort it based on that.
dynamically send the city name in the query to open the table of that
destination
Making the query dynamic is pretty easy, you just need to understand what will change and what will not.
So when user selects a city and hits the submit button your query variable will become this:
$selected_city = $_POST['city'];
$query = "SELECT hotel_name FROM `$selected_city` WHERE ...";
You may need to use that city in your filter queries too. (will edit the answer in case I have missed something)
===EDIT===
Some Optimization in your code:
$hotel_count_options = array ( ['pool'] => 'pool_count', ['gym'] => 'gym_count', ['spa'] => 'spa_count', ['is_wifi'] => 'wifi_count', ['is_beach'] => 'beach_count', ['is_familyoriented'] => 'family_count', ['is_economical'] => 'econo_count' );
$where = '';
$query_select_string = '';
foreach($_POST['check_list'] as $selected) {
echo "<p>".$selected ."</p>";
if (array_search($selected, array_keys($hotel_count_options)) !== false) {
$where .= " AND {$selected} = 1";
$query_select_string .= "{$hotel_count_options['$selected']} + ";
}
}
$query_select_string = rtrim($query_string, " + ");
Now just change your select query string,
$sql = "SELECT hotel_name, $query_select_string as ame_count FROM Dubai WHERE ".$where." ORDER BY ame_count desc;";

How can I set multiple default values in an HTML select control using the values in a PHP array?

This is sort of an extension of the problem solved here: Set default value for HTML select control in PHP however I would like to fill in Multiple values that match, with the values to fill in stored in an additional array:
This is my code so far:
<select name="genres[]" id="genres_edit" multiple>
<?php
$genrelist = array(
'Action',
'Adventure',
'Comedy',
'Cooking',
'War',
'Western');
for($i = 0;$i < count($genrelist);$i++) {
echo "<option value=\"$genrelist[$i]\"";
for ($g = 0; $g < count($genre);$g++) {
if ($genrelist[$i] == $genre[$g]) {
echo "selected=\"selected\"";
}
echo ">$genrelist[$i]</option>";
}
}
?>
</select>
$genrelist is the array of all possible genres that will be used to fill up the select control, and the array of actual genres is stored in $genre.
Basically I want it to highlight the values in the selectbox that match any of the values in the $genre array.
i.e. if the genres stored in $genres are: Adventure, Cooking, Western, then those 3 values will be highlighted in the select box, out of the 6 available genres in the box.
Here's how I'd do it ...
$genres = array(
'Action',
'Western'
);
$genrelist = array(
'Action',
'Adventure',
'Comedy',
'Cooking',
'War',
'Western');
foreach ($genrelist as $k=>$v) {
$sel = (array_search($v,$genres) !== false) ? ' selected' : '';
echo '<option value="'. $k .'"'. $sel .'>'. $v .'</option>';
}
Here's the sandbox ... http://sandbox.onlinephpfunctions.com/code/e4f2ca28e0fd43513b694f5669329cc1db328598
Assuming your form in being set with method="get" then the $_GET superglobal should have an array in it called genres (as defined by the fact that your multiple select box is called genres[]).
So when looping through your output you should be able to check if the current genre (from the $genrelist array) exists in the $_GET['genres'] array ... like so:
<?php
$genrelist = array(
'Action',
'Adventure',
'Comedy',
'Cooking',
'War',
'Western');
?>
<select name="genres[]" id="genres_edit" multiple="multiple">
<?php foreach($genrelist as $genre): ?>
<?php $sThisSelected = in_array($genre, $_GET['genres']) ? " selected=\"selected\"" : ""; ?>
<option value=\"<?= $genre; ?>\"<?= $sThisSelected; ?>><?= $genre; ?></option>
<?php endforeach; ?>
</select>
There's no sanity checking or sanitisation in this but that's the theory anyway.
If you want multiple selection you must specify your select tag with multiple option
<select multiple="1">
<option selected>option1</option>
<option selected>option1</option>
<option selected>option1</option>
</select>
The drawback is that the select menu is no more a dropdown, if that matter for you, let me know and I will try to tune in the solution.

php and MYSQL SELECT issues with arrays

I was wondering if you could tell me what is wrong with my code or point out where I am going wrong, as I am not able to display any results. $_POST['checkbox'] is an array.
<?
$get_id=$_POST['checkbox'];
if(empty($get_id)) {
echo("<h3>You didn't select anything.</h3>");
} else {
$where[] = sprintf(" id='%s'",$_POST["checkbox"]);
}
$where_str = " WHERE ".implode(" AND ",$where);
$sql = "SELECT * FROM products $where_str";
$result = mysql_query($sql, $link);
echo "<table>";
echo "<tr> <th>Description</th> </tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr><td>";
echo $row['description'];
echo "</td></tr>";
}
echo "</table>";
?>
You should refrain from using short tags <? as they are not supported after PHP 5.4.
You are not connecting to MySQL ($link undefined)
You are using a deprecated API (mysql_). See comments for alternatives (mysqli_ or PDO)
You should use the REQUEST_METHOD index of $_SERVER to determine whether your script has been posted.
if( $_SERVER[REQUESTED_METHOD] == 'POST' && !empty($_POST['checkbox']) ) {
... }
You need to use error handling to check for errors. If you echo $sql; you would see that the checkboxes aren't being populated:
SELECT * FROM products WHERE id=''
Your script is vulnerable to SQL injection. When you switch to current API, use binded parameters.
Is $_POST[checkbox] an array?
sprintf will not work as you intend it to because you are passing the entire $_POST[checkbox] array to it. You would need to iterate through it to format it. (See Ollie's answer)
Example
Assuming your HTML looks like this:
<form method="post" ...>
<input type="checkbox" name="checkbox[]" value="1" />
<input type="checkbox" name="checkbox[]" value="2" />
<input type="checkbox" name="checkbox[]" value="3" />
<input type="submit" name="submit" />
</form>
And all three boxes are checked; it will produce this array:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Following Collie's loop:
foreach ($_POST['checkbox'] as $checkbox) {
$where[] = sprintf(" id='%s'",$checkbox);
}
$where will look like:
Array
(
[0] => id='1'
[1] => id='2'
[2] => id='3'
)
The rest of your script should work. However, you should look into using the IN operator.
That will enable you to skip the loop and just use implode:
$where = "'" . implode("', '", $_POST[checkbox]) . "'";
Which produces:
'1', '2', '3'
And combined with IN:
$sql = "SELECT ... FROM WHERE id IN ($where)";
Be aware that this is not sanitized and you're still vulnerable to injection.
If $_POST["checkbox"] is an array like you say then you cannot use it as a string in the sprintf. Try using array_pop to return the last value of that array or similar.
You could foreach through each element in the array:
foreach ($_POST['checkbox'] as $checkbox) {
$where[] = sprintf(" id='%s'",$checkbox);
}
Although this will probably just create an invalid SQL statement if asking for ID to be equal to two different integers.

How do I create this array? (PHP)

I am a little stuck on how to create this array.
My data:
category_id | category_name
1 bikes
2 cars
3 books
4 computers
Array:
$category=array();
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$category=array('category_id'=>$category_id, 'category_name'=>$category_name);
while ($row = $result->fetch_array()){
$category_id=$row['category_id'];
$category_name=$row['name'];
}
I want to create an array so that I can echo the data in a radio list like...
<input type='radio' value='<?PHP echo $category['category_id']; ?>'
name='category[]'><?PHP echo $category['category_name']; ?>
o bikes
o cars
o books
o computers
The problem is that the array only consists of one pair (1, bikes) and not all the data.
How can I make an array with all the data?
Thanks!
You are doing three things wrong, first you are not actually setting $category to equal anything - only the values of two undefined values, which default to null. So you end up with an array like:
array('category_id' => null, 'name' => null)
Second, you are doing nothing with the values of $category_id and $category_name when you do set them. Next, you are not going through the array item by item, you simply output the initial way it was set - which is linked to another problem that your array is short of a dimension. It should be 2-dimensional, not 1-dimensional.
This code sums up the gist of it all. I would suggest reading up on how arrays work in PHP and how to define them, they're a very commonly used data type throughout frameworks and the like.
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$categories=array();
while ($row = $result->fetch_array()){
$categories[] = array('category_id' => $row['category_id'], 'category_name' => $row['name']);
}
Then when you need to output:
foreach ( $categories as $category ) {
?>
<input type='radio' value='<?php echo $category['category_id']; ?>' name='category[]'><?php echo $category['category_name']; ?>
<?php
}
This can of course be cleaned up further.
That is because you are echoing out side of the loop there by giving you only first row records eg bikes, you should do like:
$category=array();
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$category=array('category_id'=>$category_id, 'category_name'=>$category_name);
while ($row = $result->fetch_array()){
$category_id=$row['category_id'];
$category_name=$row['name'];
?>
<input type='radio' value='<?PHP echo $category['category_id']; ?>'
name='category[]'><?PHP echo $category['category_name']; ?>
<?php
}
You are assigning to variables $category_id and $category_name, rather than to the array $category, so you're only seeing the first row returned from the query.
I normally use PDO, and would write it something like this:
<?php
$db = ...
$sql = 'SELECT * FROM categories ORDER BY category_name ASC';
$categories = $db->query($sql);
?>
<html>
<body>
<? foreach ($categories as $category): ?>
<input type="radio" name="category[]" value="<?= $category->category_id ?>">
<?= $category->category_name ?>
</input>
<? endforeach ?>
</body>
</html>

search by category with php mysql

hello im using this code to do search
<form action="arama.php" method="get">
<input type="text" name="lol">
<select name='kategori'>
<option value="tum">Tum kategoriler</option>
<?
while ($kat = mysql_fetch_array($kategori_isim)) {
echo "
<option value=".$kat[kategori_isim].">".$kat[kategori_isim]."</option>";
}
?>
</select>
<input type="submit" value="ara">
</form>
<?
$lol = mysql_real_escape_string($_GET['lol']);
$kategori = mysql_real_escape_string($_GET['kategori']);
if ($kategori == "tum") {
$ara = mysql_query("select * from dosyalar where baslik like '%$lol%'");
}
else {
$ara = mysql_query("select * from dosyalar where baslik like '%$lol%' order by kategori = '%$kategori%'");
}
?>
search by term works but not listing by kategori.. what can i do?
I'm not sure I understand the question (I can't really figure out what those fields mean), but I think that your second query should be more like:
$ara = mysql_query("SELECT * FROM dosyalar WHERE kategori LIKE '%$kategori%'");
ORDER BY only specifies how to sort the results, you can only use a column name, not a check as in your code.
Extending my answer: the ORDER BY kategori = '%$kategori%' isn't a syntax error but I don't think it does anything useful. The check kategori = '%$kategori%' will always be false (unless you have a value with percent signs both at start and at end) so the ORDER BY clause will be useless and you will just do the same select you're doing in the other branch of the if block.
Specifying ORDER BY kategori = '$kategori' will return 0 for all the records where kategori is not equal to $kategori, 1 for the ones where it matches. This will basically sort all the matching rows at the end of your query.
Maybe the query failed. In that case mysql_query() returns FALSE and mysql_error() returns a description of the error.
Try
<form action="arama.php" method="get">
<input type="text" name="lol" />
<select name='kategori'>
<option value="tum">Tum kategoriler</option>
<?php
while ( false!==($kat=mysql_fetch_array($kategori_isim)) ) {
$htmlIsim = htmlspecialchars($kat['kategori_isim']);
echo ' <option value="', $htmlIsim, '">', $htmlIsim, "</option>\n";
}
?>
</select>
<input type="submit" value="ara" />
</form>
<?php
$lol = isset($_GET['lol']) ? mysql_real_escape_string($_GET['lol']) : '';
$kategori = isset($_GET['kategori']) ? mysql_real_escape_string($_GET['kategori']) : '';
$query = "select * from dosyalar where baslik like '%$lol%'";
if ( 'tum'!==$kategori ) {
$query .= "order by kategori = '%$kategori%'";
}
$ara = mysql_query($query) or die( htmlspecialchars(mysql_error().': '.$query) );
echo '<pre>Debug: ', mysql_num_rows($ara) , ' records in the result set for ', htmlspecialchars($query), "</pre>\n";
?>

Categories