PHP: How to call option value in if statement? - php

I have this drop down list
echo "<select name='subcat'><option value=''>Select one</option>";
echo "<option value='all'>All</option>";
foreach ($dbo->query($quer) as $noticia) {
echo "<option value='$noticia[id]'>$noticia[sub_category]</option>";
}
What i want is to have 2 options, is to show "all" or one specific sub category from database
Here is my current code:
if($_POST['subcat'] == $subcat) {
$query = "Select ... where subcat = '".$subcat."'" }
else{
$query = show all;
My problem is that when I choose the dropdown value ALL, is doesn't go to else but still in the $subcat. How do I call
<option value='$noticia[id]'>
I try:
if($_POST['subcat'] == $noticia[id]
but not working..

Break your query up, depending on the value of $_POST['subcat']
$query = "Select ... ";
if($_POST['subcat'] != 'all') {
$query .= " where subcat = '".$subcat."'";
}
$query .= "...";

if($_POST['subcat'] == 'all') {
$query = show all;
else{
$query = "Select ... where subcat = '".$subcat."'" }
}

Related

Sort multi query array for a drop down menu

I have to relations: one with the times and one where the selected times go in after submitting a form. I'm trying to create a dropdown menu, which should be sorted. If a time slot is already occupied is should still show up in the drop down, but as disabled. E.G. 9 , 10: occupied, 11... and so on.
At the moment the occupied slots are at the bottom of the menu. How can I achieve, that they appear where they should be.
Here is my code so far:
$query = "SELECT stunde FROM zeiten WHERE buchbar = 2 and
NOT EXISTS (SELECT *
FROM raumbuchung
WHERE zeiten.stunde =
raumbuchung.zeitanfang and belegt = 'belegt');
SELECT zeitanfang, belegt from
raumbuchung where belegt = 'belegt'";
echo "Beginn der Veranstaltung: ";
echo "<select name='time' id='t1'>";
if (mysqli_multi_query($conn, $query)) {
do {
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row[belegt]) {
echo "<option value=$row[zeitanfang] disabled>$row[zeitanfang]: $row[belegt]</option>";
}
else {
echo "<option value=$row[stunde]>$row[stunde]</option>";
}
}
}
}
while(mysqli_next_result($conn));
}
Maybe someone can help me out?
First store them in separate arrays then populate as your wish.
$query = "SELECT stunde FROM zeiten WHERE buchbar = 2 and
NOT EXISTS (SELECT *
FROM raumbuchung
WHERE zeiten.stunde =
raumbuchung.zeitanfang and belegt = 'belegt');
SELECT zeitanfang, belegt from
raumbuchung where belegt = 'belegt'";
$occupied_arr = array();
$available_arr = array();
if (mysqli_multi_query($conn, $query)) {
do {
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row['belegt']) {
$occupied_arr[] = $row;
}
else {
$available_arr[] = $row;
}
}
}
}
while(mysqli_next_result($conn));
}
echo "Beginn der Veranstaltung: ";
echo "<select name='time' id='t1'>";
foreach ($available_arr as $key => $value) {
echo "<option value=".$value['stunde'].">".$value['stunde']."</option>";
}
foreach ($occupied_arr as $key => $value) {
echo "<option value=".$value['zeitanfang']."disabled>".$value['zeitanfang'].": ".$value['belegt']."</option>";
}
echo "</select>";

Output of autocomplete populated from mysql tables

My textboxes get autocomplete populated from mysql tables.
I want to display the output list from the textbox into a selectable option instead of an list item.
echo '<li onClick="fill(\''.$result->naam_klant.'\');">'.$result->naam_klant.'</li>';
My code so far:
'<select onClick="fill(\''.$result->naam_klant.'\');"><option value=$result->naam_klant></option></select>';
Can you guys help me with this ?
UPDATE
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
// Is the string length greater than 0?
if(strlen($queryString) >0) {
$query = $db->query("SELECT naam_klant FROM overboekingen WHERE naam_klant LIKE '$queryString%' LIMIT 10");
if($query) {
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.$result->naam_klant.'\');">'.$result->naam_klant.'</li>';
'<select onClick="fill(\''.$result->naam_klant.'\');"><option value=$result->naam_klant></option></select>';
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
} // There is a queryString.
} else {
echo 'There should be no direct access to this naam_klant script!';
}
}
?>
You don't give enough information, how you is your results structured?
<select onchange="fill(this.value);" onfocus="this.selectedIndex = -1;">
<?
for ($i=0; $i < count(results); $i++) {
$result = results[i];
echo "<option value='{$result->naam_klant}'>option {$result->naam_klant}</option>\r\n";
}
?>
</select>
Update
Since you want a selectable option instead of an list item
if ($query) {
echo '<select onchange="fill(this.value);" onfocus="this.selectedIndex = -1;">\r\n';
while ($result = $query->fetch_object()) {
echo '<option value={$result->naam_klant}>{$result->naam_klant}</option>\r\n';
}
echo '</select>\r\n';
}

Prepopulate a dropdown menu with multiple options from a MySQL database

Newbie here... I tried to adapt my code from here
The list is populated properly but I can't get it to pre-select. What am I doing wrong? Thanks in advance!
$q = "SELECT cat_id FROM category_user WHERE cat_id=$d";
while ($row = mysqli_fetch_array($q)) {
$cat = (int)$row['cat_id'];
}
$q = "SELECT cat_id, cat FROM category";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r)> 0) {
while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
echo "<option value=\"$row[0]\"";
$selected = '';
$cid=(int)$row[0];
if ($cid=$cat) {
$selected='selected="selected"';
echo $selected;
echo ">$row[1]</option>\n";
}else{
//Check for stickyness
if (isset($_POST['category'])&&($_POST['category']== $row[0]))
echo 'selected="selected"';
echo ">$row[1]</option>\n";
}
}
}
category
---------------
|cat_id | cat |
---------------
category_user
-------------------------
|cu_id | user_id | cat_id|
-------------------------
Why overcomplicate the code. You can try something like this
<?php
$result = mysqli_query($dbc, "SELECT cat_id, cat FROM category");
if ($result) {
echo "<select name='whatever_you_want'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='{$row[0]}'";
if (intval($row[0]) == intval($cat_id)) {
echo " selected";
}
echo ">{$row[1]}</option>";
}
echo "</select>";
}
?>
if($cid=$cat){
should be
if($cid==$cat){
and
$cid=(int)$row[0];
(int) is unnecessary because string to int are compared automatically.
Figured it out. the foreach loop preselects everything for the dropdown menu. The problems were mostly getting the array from the mysql table to iterate as selected. The last piece of the puzzle were the brackets [] after $cats.
Thanks for your help, and sorry I wasn't very clear on what I was trying to accomplish. My bad.
<p><select class=\"box\" name=\"wkType[]\" multiple=\"multiple\">";
$q = "SELECT cat_id FROM category_user WHERE user_id=$d";
$r = mysqli_query ($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$cats[]=$row['cat_id'];
}
$q = "SELECT cat_id, cat FROM category";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r)> 0) {
while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
echo "<option value=\"$row[0]\"";
foreach ($cats as $key =>$cat) {
if ($row[0]==$cat){
echo 'selected="selected"';
//Check for stickyness
if (isset($_POST['category'])&&($_POST['category']== $row[0]))
echo 'selected="selected"';
}
}
echo ">$row[1]</option>\n";
}
}else{
echo '<p>Please select a category.</p>';
}
echo "</select></p>";

Only display a specific category from a database (PHP/SQL)

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.

Filter results by Product Type and Sort List by Price (PHP/SQL)

I'm in the process of learning how to create an e-commerce site. I'm trying to figure out how to order product results by price. Code below is a menu list to either filter a specific product category or the option to view all products--the code for that works.
I'm not sure how to add code to "sort by price" (low to high, high to low).
I've tried creating a function called priceList and calling inside the function categoryList (which queries the database for which product type or to view all products), but does not work.
function priceList() {
$con = getConnection();
if($pUserCat == "lowToHigh") {
$sqlQuery = "SELECT Price from Products
ORDER BY Price ASC";
} elseif($pUserCat == "highToLow") {
$sqlQuery = "SELECT Price from Products
ORDER BY Price DESC";
// 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']);
}
// Close connection
closeConnection($con);
}
Form
<!--category and price form ------------------------- -->
<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>
<form action="register_script.php" name="frm" method="post">
<select name="price" id="price">
<option value="lowToHigh">Low to High</option>
<option value="highToLow">High to Low</option>
</select>
<input type="submit" name="orderPrice" value="orderPrice" />
</form>
</div>
PHP
<?php
function categoryList($pUserCat=false) {
echo "I am in category list" . "<br/>";
$con = getConnection();
$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";
}
// 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']);
}
// priceList();
$priceOrder = getPriceBtn(); //$priceOrder holds value of option selected in
//price order menu
priceList($priceOrder);
// Close connection
closeConnection($con);
}
function getPriceBtn() {
//echo "<br/>"."I am calling getPriceBtn function" . "<br/>";
$priceBtn = $_POST["orderPrice"]; // price button
return $price;
//echo $priceBtn;
}
?>
I think you need to pass the $pUserCat to the function priceList($pUserCat);
A tip, you should have a default query like from high to low and if the other option is selected then run that query:
$sqlQuery = "SELECT Price FROM Products ORDER BY Price DESC";
if($pUserCat == "lowToHigh") {
$sqlQuery = "SELECT Price FROM Products ORDER BY Price ASC";
}
Also you could re-write this:
$sqlQuery = "SELECT * from Products"; // is this needed?
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";
}
like this categoryList($pUserCat):
if($pUserCat != 'viewall') {
$sqlQuery = "SELECT * FROM Products WHERE ProductType='%s'";
$sqlQuery = sprintf($sqlQuery, $pUserCat);
} else {
$sqlQuery = "SELECT * from Products";
}
Local function variables are not shared. If a function variable is defined within a function, then a function that you call from within that function does not have access to the parent's local variables, which is the very reason they are called "local". You need to pass the variable as a parameter:
When defining:
function priceList( $pUserCat ) {
...
}
When calling:
priceList( $pUserCat );

Categories