Dynamically Creating mysql select Query - php

I have multiple checkboxes in my websites:
checkbox 1
checkbox 2
checkbox 3 etc.
I want to dynamically generate mysql query based on the above checkboxes.
i:e if 1st checkbox is selected then the query should be:
$mysql="Select * from mytable where colname=" . $checkbox1 .;
if 1st and 2nd checkbox is selected then the query should be:
$mysql="Select * from mytable where colname=" . $checkbox1 ."AND colname=" . $checkbox2 ." ;
if all are selected then it should be :
$mysql="Select * from mytable where colname=" . $checkbox1 . "AND colname=" . $checkbox2 ."AND colname=" . $checkbox3 . ;
Can someone pls help:

you have to change your form like follow because its taking multiple value its should be post as an array
<form action="register.php" method="POST">
<input type="checkbox" name="rating[]" value="5">5 Star
<input type="checkbox" name="rating[]" value="4">4 Star
<input type="checkbox" name="rating[]" value="3">3 Star
<input type="checkbox" name="rating[]" value="2">2 Star
<input type="checkbox" name="rating[]" value="1">Less than 2 Star
</form>
Then in php
$where = '';
if(isset($_POST['rating'])){
$data = implode(',',$_POST['rating']); // beacuse your rating is only one column in db i think
$where = "WHERE cloumn_name IN($data)";
}
$query = "SELECT * FROM your_table $where";

You can use string concatenation with a bit of trickery to get the job done. do not rely on isset, instead use !empty.
<form action="example.php" method="post">
<input type="checkbox" name="Col1" value="colname" />Col 1</br>
<input type="checkbox" name="Col2" value="colname" />Col 2</br>
<input type="checkbox" name="Col3" value="colname" />Col 3</br>
</form>
<?php
if(!empty($_POST)) {
$string = '';
if(!empty($_POST['col1'])) {
$string.= "column1 ='".$_POST['col1']."'";
}
if(!empty($_POST['col2'])){
if(!empty($string)) {
$string.=" AND ";
}
$string.= "column2 ='".$_POST['col2']."'";
}
if(!empty($_POST['col3'])){
if(!empty($string)) {
$string.=" AND ";
}
$string .= "column3 ='".$_POST['col3']."'";
}
if(!empty($string))
{
//execute your query here.
}
}

Something about it
<? if ($_POST[option]==1) {
//query
}
?>
<form method="post">
<input type="checkbox" name="option" value="1">1
<input type="checkbox" name="option" value="2">2
<input type="checkbox" name="option" value="3">3
</form>

Just check if your Checkboxes are selcted via (isset($_POST[checkbox1]))
So you could do something like
if (isset($_POST[checkbox1])
{
//statement
}
else if (isset($_POST[checkbox2])
{
//statement2...
}
...
Read more here
Cheers

It should be apparent from the code provided below that I'm certainly no PHP coder. But anyway, here's an idea to think about...
Try it with different values for input between 0 and 127, e.g. ?input=66
<?php
if(isset($_GET['input'])){
$input = $_GET['input'];
}else{
$input=0;
}
$days = array('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun');
for( $i=0; $i<7; $i++ ) {
$daybit = pow(2,$i);
if( $input & $daybit ) {
echo "<input type = checkbox checked/>$days[$i]";
}else{
echo "<input type = checkbox>$days[$i]";
}
}
?>

Related

show value highest checkbox

I want to find the group of checkbox that user tick the most to something else
please help me!
Thanks.
Here my HTML
<form method="post">
<input type="checkbox" name="group_1[]" value="V1"/>V1
<input type="checkbox" name="group_1[]" value="V2"/>V2
<input type="checkbox" name="group_1[]" value="V3"/>V3
<br>
<input type="checkbox" name="group_2[]" value="V4"/>V4
<input type="checkbox" name="group_2[]" value="V5"/>V5
<input type="checkbox" name="group_2[]" value="V6"/>V6
<br>
<input type="checkbox" name="group_3[]" value="V7"/>V7
<input type="checkbox" name="group_3[]" value="V8"/>V8
<input type="checkbox" name="group_3[]" value="V9"/>V9
<br><br>
<input type="submit" name="submit" />
</form>
PHP
<?php
if (isset($_POST['submit'])) {
$group_1 = count($_POST['group_1']);
$group_2 = count($_POST['group_2']);
$group_3 = count($_POST['group_3']);
if ($group_1 > $group_2 and $group_1 > $group_3) {
echo "Group 1 is highest ";
}
elseif ($group_2 > $group_1 and $group_2 > $group_3) {
echo "Group 2 is highest ";
}
elseif ($group_3 > $group_1 and $group_3 > $group_2) {
echo "Group 3 is highest ";
}
}
?>
i'm new in php so I code "If Else" but i don't want to use this. and one more i don't want to code specific like "$group_1 = count($_POST['group_1']);" i just want to define "name of checkbox" to get value.
all i want is get same result but different code.
I think you could use the max() function to get highest value
Please refer to http://php.net/max
Probably like this:
<?php
if (isset($_POST['submit'])) {
$group_1 = count($_POST['group_1']);
$group_2 = count($_POST['group_2']);
$group_3 = count($_POST['group_3']);
$array = array("Group 1"=>$group_1,"Group 2"=>$group_2,"Group 3"=>$group_3);
$maxIndex = array_search(max($array), $array);
echo $maxIndex;
}
?>

Not able to fetch the dynamic select list data from from html to php. please advice

<form method="POST" name="mailform" action="sendmail.php">
<fieldset>
<?php
require_once("mysql_connect.php");
$sql = mysql_query( " SELECT NAME FROM TABLE WHERE ID = ( SELECT ID FROM TABLE2 WHERE COLUMN = '$USERNAME') ORDER BY NAME");
echo "<select>";
while($row = mysql_fetch_array($sql)){
echo "<option value='".$row["NAME"]."'>".$row["NAME"]."</option>";
}mysql_free_result($sql);
echo "</select>";
?>
<input type="text" name = "name" placeholder = "name Required" ><br \><br \>
<input type="checkbox" name="instance[]" value="yes" checked="checked" \>instance1><br>
<input type="checkbox" name="instance[]" value="Yes" \>instance2<br><br \>
<input type="submit" name="email" value="Send Mail">
</fieldset> <br \>
</form> <br \><br \>
This the part of the code. I need to build sendemail.php which should have the value from dynamic select list, and value from the check boxes.
<?php
require_once("mysql_connect.php");
$sql = mysql_query( " SELECT NAME FROM TABLE WHERE ID = ( SELECT ID FROM TABLE2 WHERE COLUMN = '$USERNAME') ORDER BY NAME");
echo "<select name='selection'>";
while($row = mysql_fetch_array($sql)){
echo "<option value='".$row["NAME"]."'>".$row["NAME"]."</option>";
}mysql_free_result($sql);
echo "</select>";
?>
change your php code with above.. you'll get $_POST['selection'] from dynamic select list.
Edit:
You'll get $_POST['instance'] array.
<?php
$selected = $_POST['selection'];
$instances = array();
foreach ($_POST['instance'] as $instance)
{
$instances[] = $instance;
}
?>
Now, you'll have $selected as dynamic selected value and $instances have array of checked checkboxes.
To get the value of a selected item in a list
<select id="items" name="animal">
<option value="0">--Select Animal--</option>
<option value="Cat">Cat</option>
</select>
$selected_val = $_POST['items'];
To get the selected checkbox values
Red <input type="checkbox" name="color[]" id="color" value="red">
Green <input type="checkbox" name="color[]" id="color" value="green">
$colorsChecked = $_GET['color'];
foreach ($color as $colorsChecked)
{
echo $color;
}
your select box must has a name.
echo "<select name='cbouser'>";
after post you need to use $_POST["cbouser"] or $_REQUEST["cbouser"]

Search multiple words and single word at a time in a multiple row in Mysql php

I'm trying to use this search for searching more than one words or single word at a time from a database. Now the problem is that my script only running properly but please help me...
<form name="ds" method="post">
<input type="text" name="name" placeholder="Entername" />
<!--<input type="text" name="search" placeholder="Location" />-->
<select name="location[]" multiple="multiple">
<option value="delhi">Delhi</option>
<option value="Mumbai">Mumbai</option></select>
<input type="submit" name="submit" value="Search" />
</form>
<?
$conn=mysql_connect("localhost","root","");
mysql_select_db("dbrozgarexpress",$conn);
echo $search =$_POST['location'];
$description = "";
$name2=$_POST['name'];
if(isset($name2)&&$name2 != ""){
if($flag){
$cheack.= "AND ";
}
$cheack.="user_first_name ='$name2' ";
$flag =true;
}
if(isset($search)&&$search != ""){
if($flag){
$cheack.= "AND ";
}
foreach($search AS $s)
{
$cheack.="user_current_location_id ='$s' or ";
$flag =true;
}
}
$cheack = substr($cheack, 0, -4);
echo $query = "SELECT * FROM `tb_user` WHERE $cheack ";
?>
error SELECT * FROM `tb_user` WHERE user_first_name ='kum
I think I have a general idea of what you are after.
P.S. the query will only show after you submit the form - i.e. after you click search button
Try this:
<?php
// Handle Post
if (count($_POST))
{
// Load Params
$name = isset($_POST['name']) ? $_POST['name'] : '';
$locations = isset($_POST['location']) ? $_POST['location'] : array();
// Start Query
$sql = 'SELECT * FROM `tb_user` WHERE ';
// Build Query
$sql_parts = array();
if (!empty($name)) {
$sql_parts[] = "`user_first_name` = '$name'";
}
if (sizeof($locations)) {
foreach ($locations as $location) {
$sql_parts[] = "`user_current_location_id` = '$location'";
}
}
$sql = $sql . implode(' AND ', $sql_parts);
// Debug
echo $sql ."<br><br>";
}
?>
<form action="" name="ds" method="post">
<input type="text" name="name" placeholder="Entername" />
<select name="location[]" multiple="multiple">
<option value="delhi">Delhi</option>
<option value="Mumbai">Mumbai</option></select>
<input type="submit" name="submit" value="Search" />
</form>
Here's an example of this working:
No location selected, name only
name and one location
name and two location

PHP - Loop number of selected check boxes on form submit

I have an issue where I need to loop the number of check boxes on a form submit. Foreach check box that is looped I need to then insert data into the database.
How Would I go about looping over the amount of check boxes that have being passed via form submit?
My code is as follows:
Form:
<form action="createChallenge.php" method="post" name="chalCreate">
Challenge Name:<input type="text" name="chalName" />
<br />
Challenge Target:<input type="text" name="chalTarget"/>
<br />
End Date:<input type="text" name="chalDate">
<br />
<!-- Needs a jquery datepicker -->
Select Friends: <br />
<?php
$selFriend = $conn->prepare("SELECT * FROM Friends WHERE UserID = '$userID' AND Friend = 'y' ORDER BY FriendName ASC");
$selFriend->execute();
foreach($selFriend as $row){
?>
<input type="checkbox" name="test" value="<?php echo $row['FriendID'] ?>"><?php echo $row['FriendName'] ?><br>
<?php
}
?>
<br />
<button type="submit">Create Challenge</button>
</form>
PHP to handle the form:
<?php
if(isset($_POST['test']))
{
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
echo $name = $_POST['chalName'];
echo $target = $_POST['chalTarget'];
echo $date = $_POST['chalDate'];
echo $friend = $_POST['test'];
echo $setby = $_COOKIE['userID'];
$create = $conn->prepare("INSERT INTO Challenge ( chalSetBy, chalName, chalTarget, chalDate ) VALUES ('$setby', '$name', '$target', '$date') ");
$create->execute();
if($create)
{
echo "Challenge made successfully";
}
else
{
echo "There was a problem";
}
}
?>
I thought doing the following would echo out data, but it didn't, it only selected the last check box:
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
Make an array of your checkbox in HTML page like as below,
<form name="frm" method="post">
<input type="checkbox" value="1" name="test[]">
<input type="checkbox" value="2" name="test[]">
<input type="checkbox" value="3" name="test[]">
<input type="checkbox" value="4" name="test[]">
<input type="checkbox" value="5" name="test[]">
<input type="checkbox" value="6" name="test[]">
<input type="submit">
</form>
<?php
foreach($_POST['test'] as $key=>$value)
{
echo $value."<br>";
}

How to use MYSQL and two different Submit buttons?

I have created a song database (mysql) where a user can enter data into the textfield, select "by artist" or a "by title" radio button and click submit. This all works fine. :)
However, I would like to add another submit button that bypasses the above query and simply lists all of the songs that have been added to the database with a year's time.
I believe that the query I need is:
select * from dt_tb where `dt` >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
but I cannot figure out how to code the PHP to run the query for the songs within the past year.
Here are the two forms I have:
<p>
<form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="Submit" value="Search" />
</form></p>
<form name="form" method="post" action="">
<br />
<input type="submit" name="Newsongs" value="New Releases" />
</form></p>
and here is the current, working php for the 1st query:
<?php
$delimiter = "\t";
$newline = "\n";
$var = #$_GET['q'] ;
$field = #$_GET['field'];
$var = htmlentities($var);
$trimmed = trim($var); //trim whitespace from the stored variable
$search_words = explode(' ', $var);
if ($var != "") {
// rows to return
$limit=100;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database
mysql_connect("DBLocation","DatabaseName","PASSWORD"); //(host, username, password)
//specify database
mysql_select_db("DatabaseName") or die("Unable to select database"); //select which database we're using
// Build SQL Query
$query = "SELECT * FROM Songs where $field like \"%$trimmed%\" order by $field ";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// If we have no results, offer a google search as an alternative
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
}
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
// display what the person searched for
echo "<p>You searched for: "" . $var . ""</p>";
// begin to show results set
echo "<p style=\"color: #00ff00; font-size: 1.2em;\">Results</p>";
$count = 1 + $s ;
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["title"];
$artist = $row["artist"];
echo "$title";
echo " - ";
echo "$artist";
echo "<br />";
echo $newline;
$count++ ;
}
$currPage = (($s/$limit) + 1);
//break before paging
echo "<br />";
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
}
?>
You can add a hidden field and then check it on submit:
<input type="hidden" name="act" id="act" value="">
Then on your second submit button, use JavaScript to change the value:
<input type="submit" name="Newsongs" value="New Releases" onclick="document.getElementById('act').value = 'list_all'" />
If the value is "list_all", process that, else do your current processing.
if ($_POST['act'] == 'list_all') {
// process second submit button code
} else {
// all your current code
}
You'll want to check if the NewSongs submit button was on the form submitted, and use that in an if statement to do the query or not.
<?php
if (!isset($_POST['NewSongs'])){
//do the search
} else {
//don't do the search
}
?>
You could use 2 submit button inside a form :
<p><form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="submit" value="Search" />
<input type="submit" name="submit" value="New" />
</form>
</p>
<?php
if(isset($_GET['submit']) && $_GET['submit'] == 'Search'){
// do search
}
if(isset($_GET['submit']) && $_GET['submit'] == 'New'){
// do second search
}
?>

Categories