<input type="checkbox" name="average" value="average" <? if (get_option('average') == 'average'){ echo 'checked="checked"';} ?>>Average
<input type="checkbox" name="petite" value="petite" <? if (get_option('petite') == 'petite'){ echo 'checked="checked"';} ?>>Petite
if ( get_option('average') == 'average' ): // choose category
$average = "AND build = '".get_option('average')."'";
endif;
if ( get_option('petite') == 'petite' ): // choose category
$petite = "OR build = '".get_option('petite')."'";
endif;
$qry = mysql_query("SELECT performerid,pic0 FROM ".$table." WHERE **$average $petite** ORDER BY RAND() LIMIT 20");
How can i make this code work? I need the sql query to work if $average is selected, is both $average and $petite are selected, or just $petite is selected?
TY!
you may use something like this:
$selectedCategories = array();
foreach(array('petite', 'average', 'athletic') as $category)
{
if (get_option($category) == $category)
{
$selectedCategories[] = $category;
}
}
$qry = mysql_query(
"SELECT performerid,pic0
FROM ".$table."
WHERE build IN('" . implode("', '", $selectedCategories) . "')
ORDER BY RAND() LIMIT 20;");
Note: this won't work if you select no category.
you need to use php function isset();
if(isset($_POST)){ //checks if post is set
if(isset($)POST['average']) && !isset($_POST['petite'])){
//do staff only average is set
}
elseif(isset($_POST['petite']) && !isset($_POST['average'])){
//do staff only petite is set
}
elseif(isset($_POST['average'] && isset($_POST['average']))){
//do staff both is set
}
}
Related
I have tried to find out searching from 3 fields. If I will fill only 1 field then data should search, if i will fill in 2 columns then data should search.
Help me out where i am wrong as data is searching from any scenario.
Below is my code which i have used but it not working :-
$query = "";
$keyword = $_REQUEST['sports'];
$country = $_REQUEST['city'];
$category = $_REQUEST['code'];
if(isset($keyword)){//if keyword set goes here
$query = "SELECT * FROM event WHERE sports LIKE '%$keyword%' OR postelcode LIKE '%$keyword%' OR city LIKE '%$keyword%'";
if(isset($category)){
$query = "AND postelcode LIKE '$category'";
}
if(isset($country)){
$query = "AND city LIKE '$country'";
}
}else if (isset($category)){ //if keyword not set but category set then goes here
$query = "SELECT * FROM event WHERE postelcode LIKE '$category'";
if(isset($country)){
$query = "AND city LIKE '$country'";
}
}else if(isset($country)){//if only country set goes here
$query = "SELECT * FROM event WHERE city LIKE '$country'";
}
$result1 = mysqli_query($conn, $query);
if (mysqli_num_rows($result1) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result1))
{
?> <ul>
<li>Contact Email :- <?php echo $email; ?></li>
<li>Sports :- <?php echo $row["sports"]; ?></li>
</ul>
<?php
}
}
?>
$query = "AND postelcode LIKE '$category'"; is logic which replaces your query. You need to append to it with .= if you're going to add conditions to the WHERE clause. Each instance of trying to add AND logic to your query needs to append to your select query, not replace it.
You're replacing $query variable value with each condition you are adding.
Use .= operator to append the new where clause to the previous query string.
Plus I have made some other changes which will make your code immune to errors by setting up isset to Request variable and replacing isset of where clause variables with !empty because you have already defined all the variables in the beginning of the code. So isset() will always be true.
$query = "";
$keyword = isset($_REQUEST['sports']) ? $_REQUEST['sports'] : ''; //Checking if parameter is passed
$country = isset($_REQUEST['city']) ? $_REQUEST['city'] : '' ; //Checking if parameter is passed
$category = isset($_REQUEST['code']) ? $_REQUEST['code'] : ''; //Checking if parameter is passed
if(!empty($keyword)){//if keyword set goes here
$query = "SELECT * FROM event WHERE sports LIKE '%$keyword%' OR postelcode LIKE '%$keyword%' OR city LIKE '%$keyword%'";
if(!empty($category)){
$query .= " AND postelcode LIKE '$category'"; // Added space before AND
}
if(!empty($country)){
$query .= " AND city LIKE '$country'"; // Added space before AND
}
}else if (!empty($category)){ //if keyword not set but category set then goes here
$query = "SELECT * FROM event WHERE postelcode LIKE '$category'";
if(!empty($country)){
$query .= " AND city LIKE '$country'"; // Added space before AND
}
}
if(isset($country)){//UPDATED THIS CONDITION: if only country set goes here
$query = "SELECT * FROM event WHERE city LIKE '$country'";
}
$result1 = mysqli_query($conn, $query);
if (mysqli_num_rows($result1) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result1))
{
?> <ul>
<li>Contact Email :- <?php echo $email; ?></li>
<li>Sports :- <?php echo $row["sports"]; ?></li>
</ul>
<?php
}
}
Removed the unneeded if blocks and improper string concatinations (subsequent $query =".."; $query =".."; $query =".."; ) that just overwrite previous value of $query.
Use .= operator instead to combine strings - like - $query = "text1 "; $query .= "text2 "; $query .= "text3"; - that results to - $query = "text1 text2 text3";
Also did proper initiation of variables ($keyword, $country and $category) to prevent notice errors. Also mysqli_real_escape_string() on the variables to prevent sql injection attacks.
The below code returns records that matches any of the search fields using mysql OR condition.
Updated Code:
$query = "";
$keyword = mysqli_real_escape_string($conn, ((isset($_REQUEST['sports']) AND $_REQUEST['sports'] != "" )? "%{$_REQUEST['sports']}%" : ''));
$country = mysqli_real_escape_string($conn, ((isset($_REQUEST['city']) AND $_REQUEST['city'] != "" )? "%{$_REQUEST['city']}%" : ''));
$category = mysqli_real_escape_string($conn, ((isset($_REQUEST['code']) AND $_REQUEST['code'] != "" ) ? "%{$_REQUEST['code']}%" : ''));
if($keyword!="" OR $country!="" OR $category!=""){
$query = "SELECT * FROM event WHERE sports LIKE '$keyword' OR postelcode LIKE '$category' OR city LIKE '$country'";
$result1 = mysqli_query($conn, $query);
if (mysqli_num_rows($result1) > 0) {
while($row = mysqli_fetch_assoc($result1)) {
?>
<ul>
<li>Contact Email :- <?php echo $email; ?></li>
<li>Sports :- <?php echo $row["sports"]; ?></li>
</ul>
<?php
}
}
}
The below code searches in all columns and returns records that match all search fields using mysql AND condition.
Alternative Code:
$query = "";
$keyword = mysqli_real_escape_string($conn, ((isset($_REQUEST['sports']) AND $_REQUEST['sports'] != "" )? "%{$_REQUEST['sports']}%" : ''));
$country = mysqli_real_escape_string($conn, ((isset($_REQUEST['city']) AND $_REQUEST['city'] != "" )? "%{$_REQUEST['city']}%" : ''));
$category = mysqli_real_escape_string($conn, ((isset($_REQUEST['code']) AND $_REQUEST['code'] != "" ) ? "%{$_REQUEST['code']}%" : ''));
if($keyword!="" OR $country!="" OR $category!=""){
$query = "SELECT * FROM event WHERE ";
if($keyword!="") {
$query .= "sports LIKE '$keyword'";
}
if($category!="") {
if($keyword!=""){
$query .= " AND "
}
$query .= "postelcode LIKE '$category'";
}
if($county!="") {
if($keyword!="" OR $category!="") {
$query .= " AND "
}
$query .= " city LIKE '$country'";
}
$result1 = mysqli_query($conn, $query);
if (mysqli_num_rows($result1) > 0) {
while($row = mysqli_fetch_assoc($result1)) {
?>
<ul>
<li>Contact Email :- <?php echo $email; ?></li>
<li>Sports :- <?php echo $row["sports"]; ?></li>
</ul>
<?php
}
}
}
Background :
when a user selects one of the option [ example : Undelivered ] in the drop down menu, then i am displaying only the rows which have that value [ example : Undelivered ]
<tr><th>
<select id="my_select" onchange="send_option();">
<option value="all">Status</option>
<?php
$query = "SELECT DISTINCT in_transit FROM do_order";
$result = mysqli_query ($mysqli, $query);
while ( $row = mysqli_fetch_array($result) )
echo "<option value='" . $row['in_transit'] . "'>" . $row['in_transit'] . "</option>";
?>
</select>
</th></tr>
<?php
$theBigQuery = "SELECT * FROM do_order WHERE 1";
if (isset($_POST['my_option']) && $_POST['my_option'] != "")
{
if($_POST['my_option'] == "all")
{
}
else
{
$theBigQuery .= " AND in_transit like '" . $_POST["my_option"] . "'";
}
echo "<script type='text/javascript'>function changeOption(){document.getElementById('my_select').value='".$_POST['my_option']."';} changeOption();</script>";
}
$orderrecords = $db_handle->runSelectQuery($theBigQuery);
?>
<tr><td id="<?php echo $orderrecords[$k]["tracking_id"];?>">
<?php echo $orderrecords[$k]["in_transit"]; ?>
</td></tr>
<form method="post" action"dashboard.php" style="display:none" id="my_form">
<input type="text" id="my_option" name="my_option"/>
</form>
script
function send_option ()
{
var sel = document.getElementById( "my_select" );
var txt = document.getElementById( "my_option" );
txt.value = sel.options[ sel.selectedIndex ].value;
var frm = document.getElementById( "my_form" );
frm.submit();
}
Requirement :
Now I want to display rows in decrement order , so in above code i changed below line . now rows are displaying in decrement order.
$theBigQuery = "SELECT * FROM do_order ORDER BY id DESC";
Issue :
but if i select any option in dropdown [ example : undelivered ] , its not displaying any rows.
Using you edit, when you select an option, your query will become :
$theBigQuery = "SELECT * FROM do_order ORDER BY id DESC AND in_transit like 'Undelivered'";
This is a wrong sql query!!
So to fix this; leave the $theBigQuery as it was, and after the if (isset( .. test, before running the query, add the ORDER BY clause :
$theBigQuery = "SELECT * FROM do_order WHERE 1";
if (isset($_POST['my_option']) && $_POST['my_option'] != "")
{
if($_POST['my_option'] == "all")
{
}
else
{
$theBigQuery .= " AND in_transit like '" . $_POST["my_option"] . "'";
}
echo "<script type='text/javascript'>function changeOption(){document.getElementById('my_select').value='".$_POST['my_option']."';} changeOption();</script>";
}
$theBigQuery .= " ORDER BY id DESC";
$orderrecords = $db_handle->runSelectQuery($theBigQuery);
I am using PHP to call the database to print 3 different dropdown menus. That works. My problem is calling the function and passing the dropdown selections into the function and displaying the records after the submit button is pressed. The function is a build query taking into account if only 1 of the dropwdowns are selected or all 3.
The function is currently in the same page as the the form.
Here is the form:
<form action="edit.php" method="POST">
<select>
<?php $getGroup = mysql_query("SELECT DISTINCT resgroup FROM restable ORDER BY resgroup");
while($viewAllGroups = mysql_fetch_array($getGroup)){
?>
<option id="<?php echo $viewAllGroups['resgroup']; ?>"><?php echo $viewAllGroups['resgroup']; ?></option><?php } ?>
</select>
<select>
<?php $getType = mysql_query("SELECT DISTINCT restype FROM restable ORDER BY restype");
while($viewAllTypes = mysql_fetch_array($getType)){
?>
<option id="<?php echo $viewAllTypes['restype']; ?>"><?php echo $viewAllTypes['restype']; ?></option><?php } ?>
</select>
<select>
<?php $getService = mysql_query("SELECT DISTINCT service FROM restable ORDER BY service");
while($viewAllServices = mysql_fetch_array($getService)){
?>
<option id="<?php echo $viewAllServices['service']; ?>"><?php echo $viewAllServices['service']; ?></option><?php } ?>
</select>
<input type="submit" class="btn btn-primary" value="Filter" />
</form>
Here is the function:
<?php
function displayrecords(){
$groups = $_POST['resgroup'];
$type = $_POST['restype'];
$service = $_POST['service'];
if($groups != ""){
$where[] = " `resgroup` = '".mysql_real_escape_string($group)."'";
}
if($type != ""){
$where[] = " `restype` = '".mysql_real_escape_string($type)."'";
}
if($service != ""){
$where[] = " `service` = '".mysql_real_escape_string($service)."'";
}
$sql_json = "SELECT * FROM mytable WHERE $where_clause ORDER BY id DESC";
}
?>
Then I try to display the function.
<?php displayrecords(); ?>
I am not getting an error, however, once the submit button clicked, the dropdown menu's clear out, and it doesn't return anything. I know I'm missing a lot. I would appreciate any help.
Thank you in advance.
First of all please provide name to each select element. Again in the the edit.php file access the values of post array by that name.
Now I am giving an example for it.
HTML part:
<select name='select1' >
<option value='1'>Value</option>
<option value='1'>Value</option>
</select>
Now in edit.php you can access the value of selected element of selectbox select1
as $_POST['select1'];
You are adding an Array into the string, which will only result in "SELECT * FROM mytable WHERE Array() ORDER BY id DESC"; or something similar.
Try to add this befor your $sql_json = "...line:
$where = implode(" AND ", $where);
This should add restype=value AND service=value etc to your string.
Additionally, you are referencing to $group instead of $groups in your if($groups != "") clause.
Also, you have to give your select tags a name to be able to reference them in $_POST:
<select name="restype">
You need to alter your PHP because the sql statement is looking for a variable $where_clause and I don't see it defined in your code.
You can rewrite the building of the where clause
<?php
function displayrecords(){
$groups = $_POST['resgroup'];
$type = $_POST['restype'];
$service = $_POST['service'];
$where = "";
if($groups != ""){
$where = " `resgroup` = '".mysql_real_escape_string($group)."'";
}
if($type != ""){
if( $where != "" ) $where .= " AND ";
$where .= " `restype` = '".mysql_real_escape_string($type)."'";
}
if($service != ""){
if( $where != "" ) $where .= " AND ";
$where .= " `service` = '".mysql_real_escape_string($service)."'";
}
$sql_json = "SELECT * FROM mytable WHERE $where ORDER BY id DESC";
}
?>
I have 2 checkboxes. Their values go to another php file and if any of them is checked, its value is inserted mysql codes. I did it, but when the number of checkbox increase and more advanced things appear, my code will be impossible to put into practise.
Here is checkbox.php :(it is inside a form)
<div>
<label>Choose:</label>
<label>Camera </label><input type="checkbox" name="kind[]" value="1" />
<label>Video </label><input type="checkbox" name="kind[]" value="2"/>
</div>
when the form is clicked, it goes to fetch_kind.php via AJAX and jquery($.post).
Here is code:
<?php
$kind = array();
$kind = $_POST['kind'];
$count = count($kind);
if ($count== 0) {
echo "You did not checked any of checkboxes!!!";
}
if ($count == 2) {
$sql = "SELECT id,kind FROM products";
} else {
foreach ($kind as $value) {
if ($value =="1") {
$sql = "SELECT id,kind FROM products WHERE kind = " . $value;
}
if ($value =="2") {
$sql = "SELECT id,kind FROM products WHERE kind = " . $value;
}
}
}
?>
Could you give a better example? Thank you...
A simple way would be to group all the values and us IN
if ($count > 0){
$sql = "SELECT id,kind FROM products WHERE kind IN (" . implode (',', $kind) . ")";
}
Also you might want to look into sanitizing you input.
You can loop through all your checkboxes and add a simple condition to an array. You implode the array at the end.
Something like:
$conds = array();
foreach ($kind as $value) {
$conds[] = '`kind` = ' . intval($value);
}
$sql = "SELECT id,kind FROM products WHERE " . implode(" OR ", $conds);
From a dropdown menu a user can choose: view all, athletic, dress, or sandals. I am creating a function that if the user chooses athletic--only the Product Type 'Athletic', only athletic items from the database will be shown.
Right now, because how my code is written, if the user selects 'Athletic' they will see athletic items, but also all other products in the database because the function showAllProducts was called.
I'm not sure how to write, that if a user selects a specific product type, only that product type will be shown.
if (isset($_SESSION['valid_user']))
{
//echo "I am in the if statement of the session";
echo 'You are logged in as: '.$_SESSION['valid_user'].' <br />';
showAllProducts();
} else {
echo "I am not setting the session variable";
//die;
}
$userCat = getUserCategory();
orderByCategory($userCat);
//function athleticCategory ---------------------------------------------
function athleticCategory() {
echo "I am in the athletic function" . "<br/>";
$con = getConnection();
$sqlQuery = "SELECT * from Products
WHERE ProductType='Athletic'";
// Execute Query -----------------------------
$result = mysqli_query($con, $sqlQuery);
if(!$result) {
echo "Cannot do query" . "<br/>";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
if ($count > 0) {
echo "Query works" . "<br/>";
} else {
echo "Query doesn't work" ."<br/>";
}
// Display Results -----------------------------
$num_results = mysqli_num_rows($result);
for ($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc ($result);
// print_r($row);
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['Image']).'" />';
echo "Price: " . stripslashes($row['Price']);
}
}
Dropdown Menu
<form action="register_script.php" name="frm" method="post">
<select name="category" id="category">
<option value="viewall">View All</option>
<option value="dress">Dress</option>
<option value="athletic">Athletic</option>
<option value="sandals">Sandals</option>
</select>
<input type="submit" value="Go" />
</form>
Edited Code:
$sqlQuery = "SELECT * from Products";
if($pUserCat == "athletic") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='athletic'";
} elseif ($pUserCat == "dress") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='dress'";
} elseif ($pUserCat == "sandals") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='sandals'";
} elseif ($pUserCat == "viewall") {
$sqlQuery = "SELECT * from Products";
}
make a function , that accept one parameter ie category name and use default hint as 0
function categoryList($cat=false){
if($cat)
$sqlQuery = "SELECT * from Products
WHERE ProductType={$cat}";
else
$sqlQuery = "SELECT * from Products";
//do other stuff of Reading option
}
Set your 'View All' form option like this:
<option value="">View All</option>
You can use it as it is.
if (isset($_POST['category']))
$category = $_POST['category'];
$sqlQuery = "SELECT * from Products";
if ( ! empty($category)) {
if (get_magic_quotes_gpc()) {
$category = stripslashes($category);
}
if ( ! is_numeric($category)) {
$category = "'" . mysql_real_escape_string($category) . "'";
}
$sqlQuery .= " WHERE ProductType='{$category}'";
}
It has basic security features so people can't inject malicious SQL into your script.
If you call that function without any category, it will be assumed you want to show all values.
You dont need to check if for each and every single case and then write the sqlQuery according to that, as long as you use the same <option value="xxx"> as the categories are called in your db.