I have a table with 7 columns populated from mysql... the table headers each contain a checkbox which if checked and clicked on submit will be sent to a export to csv page.
Is there a way to use the SELECT $var1, $var2...$var7 FROM... ? $var1 to $var7 will be used if checkbox checked and if no checkbox checked then display some message
To betted understand what i am asking i'll put some code...
HTML
<td class="captabel">
<input type="checkbox" value="expid" >
</td>
<td class="captabel">
<input type="checkbox" value="exploc" >
</td>
etc
php
if(isset($_POST['expid'])){
$expid="id";
}
else{
$expid="";
}
if(isset($_POST['exploc'])){
$exploc="locatie";
}
else{
$exploc="";
}
etc
and at some point comes the SELECT * FROM table... <-- this is what i want to replace with SELECT $expid, $exploc ... FROM table...
i have tried various ways and none worked.
Thanks.
You have to use the name attribute on your checkbox
<input type="checkbox" value="123" name="expid" />
Modify your input type <input type="checkbox" name="exploc" value="exploc">
In your php script check :
$selectStr= "";
if(!empty($_POST['expid'])) {
$selectStr="id";
}
else{
$selectStr="";
}
if(!empty($_POST['exploc'])) {
$selectStr= !empty($selectStr) ? ", locatie" : "locatie";
}
else{
$selectStr="";
}
so your query will be
if(!empty($selectStr)) {
$qry = "SELECT $selectStr FROM table...";
}
Instead of setting different name you can set array type name in <input type="checkbox" value="exploc" name="exploc[]">
Solved it.
Based on Dipanwita Kundu answer i used
if(!empty($columns)){
$sql = 'SELECT '. implode(', ', $columns). ' FROM raport' ;
}
and works like a charm.
Thank you.
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;";
I have the table below which I have fileld with some default values:
while($records=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$records['item1']."</td>";
echo "<td>".$records['item2']."</td>";
echo "<td>".$records['item3']."</td>";
echo "<td>".$records['item4']."</td>";
echo "<td>".$records['item5']."</td>";
echo "<td>".$records['item6']."</td>";
echo "<td>".$records['item7']."</td>";
echo "</tr>";
}
echo "</table>";
I also have a my_sql query statement that looks like this and references a function which sorts all the data by asc or desc:
$sortBy=$_POST['SortBy'];
$sortIn=$_POST['SortIn'];
$sql="SELECT * FROM Results ORDER BY $sortBy $sortIn";
$result=mysql_query($sql, $conn);
echo "<table>";
All of this works successfully with a bunch of connection statements that I won't include.
I also have a 2 option radio button that looks like this:
Include newItem
<input type="radio" name="IncludeNewItem" value="1" />Yes
<input type="radio" name="IncludeNewItem" value="0" />No
What I am trying to do is set it so that when I submit the user options from the HTML page, the table is generated (and sorted) and depending on the state of the radio button, it should either display or not display another column which already exists in the database. (For examples sake, let's call this 'item 8').
I tried creating something that looks like this:
$includeNI = if(isset($_POST['IncludeNewItem']))
{Alter Table Results Add $newItem };
But I'm really unsure about the syntax as I'm new to this language.
All help is appreciated.
i want to select a lot row of my database and have checkbox to any of rows that the user can choose any of them.then i should update database according to user choice, but i can't understand who of this checkbox is selected.
thanks a lot...
the semicode is here:
$query = "Select * mytable limit 30;";
$res = $mysql->ExecuteStatement (array ());
echo '<form method="post" action=""> ';
$b=0;
while ($rec=$res -> fetch())
{
echo '<input type="checkbox" id="$b" name="checkboxName[]" value="yes"/>';
$checkboxID = "number_".$rec["ID"].":";
echo $checkboxID;
echo $rec["column1"]."</br>";
$b++;
}
if(isset($_POST['formSubmit'])) //this code just get us how many of checkbox are chosen not who are chosen
{
foreach($_POST['checkboxName'] as $selected)
{
echo $selected."</br>";
}
}
Try some thing like this:
Provide a class to all checkboxes:
<input type="checkbox" class="MyChkbox" id="$b" name="checkboxName[]" value="yes"/>';
In JS:
$('.MyChkbox').click(function(){
if($(this).is(':checked'))
{
var checkedId = $(this).attr('id');
// checkedId will contain the checked checkbox id in it. Use it as per your need
}
});
Hi In these case you should pass the Id of row as value of Checkbox and then get them when form is posted so you can try this
echo '<td><input type="checkbox" class="MyChkbox" id="$b" name="checkboxName[]" value="' . $rec["ID"] . '"></td>';
these will have value as row ID
Assignment background :
I have a drop down menu which I am populating from a database. Based on the option user choses from the drop down , I need to update the chosen record. Now some information on the databases and the record types : There are 5 types of complaints : Electrical, Mechanical , Telephone , Fire System and Priority. Each of these complaints can have a status of either "open" or "close". So when the user chooses "Electrical type" , all the "open" complaint-id's (complaint id is a field in the same record) of electrical types will appear. Once the admin chooses the id, the corresponding record is to be updated to change the status to "close".
Now my problem :
I am able to display all the complaint ids , but upon choosing the concerned id and hitting the submit button , the status of the record does not change to "close".
The code
$user="root";
$password="";
$database="complaint_data";
$localhost="localhost";
mysql_connect($localhost,$user,$password);
#mysql_select_db($database) or die("Unable to open database");
echo ('<form action="" method="post"><br>');
echo ('<center><select name = "complaint"></center>');
echo ('<option value ="Electrical"> Electrical </option>');
echo ('<option value ="Mechanical"> Mechanical </option>');
echo ('<option value ="Telephone"> Telephone </option>');
echo ('<option value ="Fire"> Fire </option>');
echo ('<option value ="Priority"> Priority </option>');
echo ('<center><input type="submit" name="Submit" ></center>');
echo ('</form>');
if(($_SERVER["REQUEST_METHOD"]=="POST") and (!empty($_POST['Submit']) ) ){
$t=$_POST['complaint'];
switch ($t) {
case "Electrical":
$q="SELECT `complaintid` , `comment` FROM `complaints` WHERE `status`='open' and `type`='Electrical' ORDER BY `id` DESC";
$sql=mysql_query($q);
$count=mysql_num_rows($sql);
if($count!=0) {
echo ('<form action="" method="post"><br>');
echo ('<center><select name = "complaint1"></center>');
while($row=mysql_fetch_array($sql)) {
$cmp=$row['complaintid'];
echo "<option value =\"$cmp\"> $cmp </option> <br>";
}
echo ('</select>');
echo ('<center><input type="submit" name="Submit1" ></center>');
echo ('</form>');
if(($_SERVER["REQUEST_METHOD"]=="POST") and (!empty($_POST['Submit1'])) ) {
$cmpi=$_POST['complaint1'];
echo $cmpi;
$query="UPDATE complaints SET status='close' WHERE complaintid=`$cmpi` ";
mysql_query($query);
}
}
if($count=='0') {
echo "No record of electrical type found";
}
mysql_close();
break;
By the way I have included only the snippet for Electrical type, once it works I shall copy it to other types too ! TIA :)
Try this:
$query="UPDATE complaints SET status='close' WHERE complaintid=$cmpi";
removed ` surrounding $cmpi.