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.
Related
I am working on a checkbox search. I'm new to PHP. I would appreciate it if someone could help me. Basically the user checks the options required, hits submit and results matching the checkbox options is displayed. The checkboxes have a value of M for Male and F for Female which matches the data in the MYSQL table.
So if a user checks checkbox 'Male' (see code below) all data with 'Male' that have a value of 'M' in the MYSQL table are returned. And any checkboxes not checked should simply be ignored as the user is only interested in the option 'Male' being 'M' (true).
To sum up I only need the search to take into account checkboxes that have been checked and echo which users that has been selected(more like filtering) through PHP.Any help appreciated. Thanks
the table looks like this :
id name address gender race
-------------------------------------------
1. 1 Lee NY M French
2. 2 James LA M Colombian
3. 3 Kashi JAPAN F Japanese
and i have a form with checkboxes like this :
<form action="shortlist.php" method="post">
<label for="sel1">Gender:</label>
Male:<input name="keyword[]" type="checkbox" value="M" />
Female:<input name="keyword[]" type="checkbox" value="F" />
<button name = "myBtn" type="submit" class="btn btn- default">Search</button>
</form>
SQL :
$sql="SELECT name, address,gender,race FROM talent1 WHERE gender = $gender'";
I'm suppose to echo something like this :
echo "<table width='100%'>\n";
//if (mysqli_num_rows($result) > 0){
//$row=mysqli_fetch_assoc($result);
//$muchneededid = $row["talent_id"];
while ($row=mysqli_fetch_assoc($result))
echo'<tr>'."\n";
echo '<tr>';
echo '<th>Name</th>';
echo '<th>Address</th>';
echo '<th>Gender</th>';
echo '</tr>';
echo "<td>{$row["name"]}</td>\n" . "<td>{$row["address"]}</td>\n" . "<td>{$row["gender"]}</td>\n";
echo '</tr>'."\n";
echo "</table>\n";
}
else
{
echo "0 results";
}
mysqli_close($conn);
}
given the information we've got it would be something like this:
<?php
//$_POST['keyword'] = array("M", "F");
$sql_addon = ''; // EDIT: this was one line below first, which of course created an 'undefined' error.
if(isset($_POST['keyword'])) {
foreach($_POST['keyword'] as $k => $val) {
$sql_addon.= " OR gender='$val'";
}
}
$sql="SELECT name, address,gender,race FROM talent1 WHERE 1=1 ";
if($sql_addon) {
$sql .= " AND (1=2 ".$sql_addon.")";
}
echo $sql;
// SELECT name, address,gender,race FROM talent1 WHERE 1=1 AND (1=2 OR gender=M OR gender=F)
?>
Those 1=1 and 1=2 might look silly, but it's (IMHO) the easiest way to generate that sql. 1=2 is there to create a falsy value, so that no records will be shown if none of the options are clicked.
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
I'm updating some countries values into db table. All countries fetch from TBL_COUNTRY table. Then few countries store to another table. I'm using implode function to store multiple values. it works fine. it stored like this in my db table Afghanistan,Argentina,Austria,Bangladesh.
I have tried this code
<?php
$exp_str = explode(',', $model_availability);
foreach($exp_str as $get_str)
{
echo $get_str;
}
?>
This above code return this output AfghanistanArgentinaAustriaBangladesh
How do I put tick on the checkbox based on this value?
<?php
$sql = "SELECT * FROM ".TBL_COUNTRY." ORDER BY country_name ASC";
$exe = mysql_query($sql, $CN);
while($r = mysql_fetch_array($exe))
{
?>
<input type="checkbox" name="model_availability[]" value="<?=$r['country_name']?>" id="<?=$r['country_name']?>" />
<label for="<?=$r['country_name']?>"><?=$r['country_name']?></label>
<?php } ?>
<input type="checkbox" name="model_availability[]" value="<?=$r['country_name']?>" id="<?=$r['country_name']?>"<?=(in_array($r['country_name'],$model_availability)?" checked":"")?> />
//In the input box just add a checked attribute, you will get.
" id="" checked = "true" />
I'm trying to add tick boxes and when the boxes are ticked a value adds up (a variable) that variable is then added into the database along with each checkbox once the form is submitted, I've been trying to modifiy this code but cant figure out how to not use the parseInt() function and output a single variable that I can then add into the database/Email reply to the customer. I'm really stuck and would appreciate some help.
(the options are suppose to actually be (deodoriser,carpet,carpetrepair,furniture,tabs,urine but im using demo options for now below in the insert staement they are the correct names)
This is my HTML:
<p><input type="checkbox" name="extras[]" value="option1" rel="11">furniture</p>
<p><input type="checkbox" name="extras[]"" value="option2" rel="12">tabs</p>
<p><input type="checkbox" name="extras[]" value="option3" rel="13">urine</p>
<p><input type="checkbox" name="extras[]" value="option4" rel="30">couch</p>
<p><input type="checkbox" name="extras[]" value="option5" rel="20">steam</p>
<span id="output"></span>
This is my javascript function
$(document).ready(function() {
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
This is my email reply/datbase inserting at the moment
$idextra=$_POST['extras'];
$arr_num=count($idextra);
$i=0;
while ($i < $arr_num)
{
$q="INSERT INTO bs_reservations (dateCreated, name, email, phone, comments,status,eventID, qty,dropoff,deodoriser,carpet,carpetrepair,furniture,tabs,urine) VALUES (NOW(),'".$name."','".$email."','".$phone."','".$comments."','2','".$eventID."','".$qty."','".$dropoff."','{$idextra[1]}','{$idextra[2]}','{$idextra[3]}','{$idextra[4]}','{$idextra[5]}','{$idextra[6]}')";
$res=mysql_query($qu) or die('ERROR INSERTING: '.mysql_error());
$i++;
}
Thanks heaps for any advice/help in coding this. I know its a big question but I feel it will help a lot of people in the future.
$res=mysql_query($qu)
change that to
$res=mysql_query($q)
and probably this too
name="extras[]"" to name="extras[]"
and i think array starts with 0, and the query would be:
while ($i < $arr_num){
$q = "INSERT INTO bs_reservations";
$q .= " (dateCreated, name, email, phone, comments,status,eventID, qty,dropoff,deodoriser,carpet,carpetrepair,furniture,tabs,urine)";
$q .= " VALUES (NOW(),'".$name."','".$email."','".$phone."','".$comments."','2','".$eventID."','".$qty."','".$dropoff;
$q .= "','".$idextra[0]."','".$idextra[1]."','".$idextra[2]."','".$idextra[3]."','".$idextra[4]."','".$idextra[5]."')";
$res=mysql_query($q) or die('ERROR INSERTING: '.mysql_error());
$i++;
}
I have a form with several checkboxes which values are pulled from a database.
I managed to display them in the form, assign an appropriate value to each, but cannot insert their values into other database.
Here's the code:
<form id="form1" name="form1" method="post" action="">
<?php
$info_id = $_GET['info_id'];
$kv_dodatoci = mysql_query("SELECT * FROM `dodatoci`") or die('ERROR DISPLAYING: ' . mysql_error());
while ($kol = mysql_fetch_array($kv_dodatoci)){
$id_dodatoci = $kol['id_dodatoci'];
$mk = $kol['mk'];
echo '<input type="checkbox" name="id_dodatoci[]" id="id_dodatoci" value="' . $id_dodatoci . '" />';
echo '<label for="' . $id_dodatoci.'">' . $mk . '</label><br />';
}
?>
<input type="hidden" value="<?=$info_id?>" name="info_id" />
<input name="insert_info" type="submit" value="Insert Additional info" />
</form>
<?php
if (isset($_POST['insert_info']) && is_array($id_dodatoci)) {
echo $id_dodatoci . '<br />';
echo $mk . '<br />';
// --- Guess here's the problem ----- //
foreach ($_POST['id_dodatoci'] as $dodatok) {
$dodatok_kv = mysql_query("INSERT INTO `dodatoci_hotel` (id_dodatoci, info_id) VALUES ('$dodatok', '$info_id')") or die('ERROR INSERTING: '.mysql_error());
}
}
My problem is to loop through all checkboxes, and for each checked, populate a separate record in a database.
Actually I don't know how to recognize the which box is checked, and put the appropriate value in db.
You can tell if a checkbox is selected because it will have a value. If it's not selected, it won't appear in the request/get/post in PHP at all.
What you may want to do is check for the value of it and work based on that. The value is the string 'on' by default, but can be changed by the value='' attribute in HTML.
Here are a couple snippets of code that may help (not exactly production quality, but it will help illustrate):
HTML:
<input type='checkbox' name='ShowCloseWindowLink' value='1'/> Show the 'Close Window' link at the bottom of the form.
PHP:
if (isset($_POST["ShowCloseWindowLink"])) {
$ShowCloseWindowLink=1;
} else {
$ShowCloseWindowLink=0;
}
.....
$sql = "update table set ShowCloseWindowLink = ".mysql_real_escape_string($ShowCloseWindowLink)." where ..."
(assuming a table with a ShowCloseWindowLink column that will accept a 1 or 0)
As an extra note: You're using the wrong HTML syntax for IDs and <label>. <label>'s "for" attribute should point to an ID, not a value. You also need unique IDs for each element. The code you have posted would not validate.
Also, you're not validating your code at all. At the very least, do a htmlspecialchars() or htmlentities() on the input before you output it and a mysql_real_escape_string() before you insert data into the DB.
2nd Answer:
You might do something like this:
HTML:
echo '<input type="checkbox" name="id_dodatoci[]" value="'.$id_dodatoci.'" />';
PHP:
if ( !empty($_POST["id_dodatoci"]) ) {
$id_dodatoci = $_POST["id_dodatoci"];
print_r($id_dodatoci);
// This should provide an array of all the checkboxes that were checked.
// Any not checked will not be present.
} else {
// None of the id_dodatoci checkboxes were checked.
}
This is because you are using the same name for all of the checkboxes, so their values will be passed to php as an array. If you used different names, then each would have it's own post key/value pair.
This might help too:
http://www.php-mysql-tutorial.com/php-tutorial/using-php-forms.php
This is the loop that I needed. I realized that I need a loop through each key with the $i variable.
if(isset($_POST['id_dodatoci'])){
$id_dodatoci=$_POST['id_dodatoci'];
$arr_num=count($id_dodatoci);
$i=0;
while ($i < $arr_num)
{
$query="INSERT INTO `dodatoci_hotel`(id_dodatoci,info_id)
VALUES ('$id_dodatoci[$i]','$info_id')";
$res=mysql_query($query) or die('ERROR INSERTING: '.mysql_error());
$i++;
}
}
Well, as Eli wrote, the POST is not set, when a checkbox is not checked.
I sometimes use an additional hidden field (-array) to make sure, I have a list of all checkboxes on the page.
Example:
<input type="checkbox" name="my_checkbox[<?=$id_of_checkbox?>]">
<input type="hidden" name="array_checkboxes[<?=$id_of_checkbox?>]" value="is_on_page">
So I get in the $_POST:
array(2){
array(1){"my_checkbox" => array(1){[123]=>"1"}}
array(1){"array_checkboxes" => array(1){[123]=>"is_on_page"}}
}
I even get the second line, when the checkbox is NOT checked and I can loop through all checkboxes with something like this:
foreach ($_POST["array_checkboxes"] as $key => $value)
{
if($value=="is_on_page")
{
$value_of_checkbox[$key] = $_POST["my_checkbox"][$key];
//Save this value
}
}
Also something that few people use but that is quite nice in HTML, is that you can have:
<input type="hidden" name="my_checkbox" value="N" />
<input type="checkbox" name="my_checkbox" value="Y" />
and voila! - default values for checkboxes...!