i am trying to sort my products using a drop down box. when i select an option the code does not run and the products do not change position. iv managed to sort products by using different buttons but i think a drop down list would look better on a website.
<?php
echo $sort = #$_GET['order'];
if (!empty($sort)) {
echo $query="SELECT * FROM products ORDER BY '".$sort."'";
} else {
echo $query="SELECT * FROM products order by " ;
}
?>
<form name="sort" action="" method="post">
<select name="order">
<option value="choose">Make A Selection</option>
<option value="price_asc">Price </option>
<option value="price_desc">Z-A</option>
<option value="name_asc">A-Z</option>
</select>
<input type="submit" value=" - Sort - " />
</form>
<?php
//Run the query.
$record_set = $connection->query($query);
while( $row = $record_set->fetch_assoc() ) {
echo '<div class="product">';
echo '<div class="product-content"><h3>'. $row['name'].'</h3>' .'</div>' . '<br />'.'<div class="product-thumb"><img src="/ISD assignment2/images/'. $row['imageName'].'"></div>'. '<div class="product-desc">'.$row['description']. '</div>'. '<br />' .'£'. number_format($row['price'], 2) . '<p>Add</p>';
echo '</div>';
}
?>
Two potential issues:
1) Your Form has no action. I believe you are trying to get it to refresh onto itself.
which would be:
action=" <?php echo $_SERVER['PHP_SELF'] ?>"
2) You are submitting via POST, yet using GET.
$sort = $_POST['order'];
Related
Im trying to update a drop down list with the countries of the world from a db query, which is working fine. I want to set the country of the user as selected, based on their IP. I am collecting their IP fine and working out their country, but Im struggling to set the selected in the output based on this.
<?php
include_once 'database.php';
$result = mysqli_query($conn,"SELECT *
FROM tbl_fm_countries
order by Country Asc");
$ipcountry = "United Kingdom";
?>
<form action="results.php" method="post" id="foodmilesTracker">
<fieldset>
<legend>Where are you?</legend>
<ol>
<li>
<label for="countryTo">Your Location</label>
<select name="countryTo">
<?php
// output data of each row
while($row = $result->fetch_assoc()){
echo "<option value='" . $row['CountryId'] . "'>" . $row['Country'] . "</option>";
}
?>
</select>
</li>
</ol>
</fieldset>
I have tried lots of options and seem to get all set as selected or none. For the example I am setting ipcountry manually.
I recommend doing it following way
<?php while($row = $result->fetch_assoc()){ ?>
<option value="<?php echo $row['CountryId']; ?>" <?php echo $row['Country'] == $ipcountry ? 'selected':''; ?>><?php echo $row['Country']; ?></option>
<?php } ?>
I want to have dropdown selected option selected after submit/refresh page. I search for other examples but no one works on my code.
How to retain selected value after submit/refresh with this code?
<form name="test" action="test.php?id=<?php echo $row["id"]; ?>" method="post">
<select id="test_email" name="test_email">
<option value="">...select</option>
<?php
$sql2 = "SELECT test_id, test_email FROM test WHERE status='Act'";
$res = $db->query($sql2);
if ($res->num_rows > 0) {
while($row1 = mysqli_fetch_array($res)) {
?>
<option value="<?php echo $row1['test_email'];?>-<?php echo $row1['test_id'];?>"><?php echo $row1['test_id'];?></option>
<?php
}
}
?>
</select>
Solved this way:
Because I could not pass $_POST['test_email'] with <?php echo $row1['test_email'];?>-<?php echo $row1['test_id'];?>
Because I use explode on $_POST['test_email']
I make one more post (insert in db) $test_temp = trim(mysqli_real_escape_string($db, $_POST['test_email'])); to have my dropdown value (whole string) in db.
I added hidden input in my form <input id="test_temp" type="hidden" name="test_temp" value="<?php echo $row["test_temp"]; ?>">
And changed select option line to <option value="<?php echo $row1['test_email'] . '-' . $row1['test_id']; ?>"<?php if($row1['test_email'] . '-' . $row1['test_id'] == $row['test_temp']) echo ' selected="selected"' ; ?>><?php echo $row1['test_id'];?></option>.
Perhaps this could be simpler but it works like a charm.
#roberto06: Thank you for your guidance.
You need to add the selected="selected" attribute on the option matching your $_POST value.
You might also want to concatenate <?php echo $row1['test_email'];?>-<?php echo $row1['test_id'];?> into <?php echo $row1['test_email'] . '-' . $row1['test_id']; ?>, but that's up to you.
Here's a solution (I assumed that $POST['test_email'] has to be equal to $row1['test_email'] . '-' . $row1['test_id'] in order for the condition to be matched). I'm using a shorthand if...else here, but you could also use a classic if :
<form name="test" action="test.php?id=<?php echo $row["id"]; ?>" method="post">
<select id="test_email" name="test_email">
<option value="">...select</option>
<?php
$sql2 = "SELECT test_id, test_email FROM test WHERE status='Act'";
$res = $db->query($sql2);
if ($res->num_rows > 0) {
while($row1 = mysqli_fetch_array($res)) {
?>
<option value="<?php echo $row1['test_email'] . '-' . $row1['test_id']; ?>"<?php echo (isset($_POST['test_email']) && $row1['test_email'] . '-' . $row1['test_id'] == $_POST['test_email']) ? ' selected="selected"' : ''; ?>><?php echo $row1['test_id'];?></option>
<?php
}
}
?>
</select>
</form>
Thanks for all advice! I am pulling a list of months that are not set to "current month" into a drop down/select menu in order to set some other month to be available for action. I get that list but and it populates the dropdown but then doesn't pass that value to the update. I'm either super confused or missing something very small.
Here are the queries:
if (isset($_POST['addMonth'])) {
$addmonth = $_POST['addmonth'];
//open additional months
$query_open_additional = "UPDATE reimbmonths SET reimb_open = 1 WHERE monthname = '$addmonth' ";
$query_current = "SELECT * FROM reimbmonths WHERE reimb_open = 1";
$result_current = mysql_query($query_current) or die ('Query failed: ' . mysql_error() . "<br />\n$sql");
$num_current = mysql_num_rows($result_current);
echo "Added another month: " . $addmonth;
}
And this is the HTML/PHP:
<h3>Open additional months</h3>
<form id="add-months" action="" method="post" onsubmit="window.location.reload() onchange="addMonth();"">
<select name="addmonth" id="addmonth">
<option <? if (empty($_POST["addmonth"])) { echo 'selected';} ?> disabled> --- Choose a Month --- </option>
<?
$i = 0;
while ($i < $num_months) {
$month_to_add = mysql_result($result_select_closed,$i,"monthname");
?>
<option value="<? $month_to_add ?>" <? if($_POST["addmonth"] === '$month_to_add') { echo 'selected';} ?>><? echo ucwords($month_to_add) ?></option>
<?
$i++;
}
?>
</select>
<input class="submit_btn" type="submit" name="addMonth" value="Set Month"/>
</form>
I am trying to convert my search page from using a checkbox styled method to being able to use a drop down box to select each separate title header as a potential search option. However when converting this the title drop down box still acts as its old checkbox style, being that it only shows the data that is stored within the title name no matter which title is selected.
PHP Section:
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
// Set up our error check and result check array
$error = array();
$results = array();
// First check if a form was submitted.
// Since this is a search we will use $_GET
if (isset($_GET['search'])) {
$searchTerms = trim($_GET['search']);
$searchTerms = strip_tags($searchTerms); // remove any html/javascript.
if (strlen($searchTerms) < 3) {
$error[] = "Search terms must be longer than 3 characters.";
}else {
$searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection.
}
// If there are no errors, lets get the search going.
if (count($error) < 1) {
$searchSQL = "SELECT sid, sbody, stitle, sdescription FROM simple_search WHERE ";
// grab the search types.
$types = array();
$types[] = isset($_GET['body'])?"`sbody` LIKE '%{$searchTermDB}%'":'';
$types[] = isset($_GET['title'])?"`stitle` LIKE '%{$searchTermDB}%'":'';
$types[] = isset($_GET['desc'])?"`sdescription` LIKE '%{$searchTermDB}%'":'';
$types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked)
if (count($types) < 1)
$types[] = "`sbody` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked
$andOr = isset($_GET['matchall'])?'AND':'OR';
$searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `stitle`"; // order by title.
$searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}");
if (mysql_num_rows($searchResult) < 1) {
$error[] = "The search term provided {$searchTerms} yielded no results.";
}else {
$results = array(); // the result array
$i = 1;
while ($row = mysql_fetch_assoc($searchResult)) {
$results[] = "{$i}: {$row['stitle']}<br />{$row['sdescription']}<br />{$row['sbody']}<br /><br />";
$i++;
}
}
}
}
function removeEmpty($var) {
return (!empty($var));
HTML Section:
<body>
<?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm">
Search For: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /><br />
Search In:<br />
Body: <input type="checkbox" name="body" value="on" <?php echo isset($_GET['body'])?"checked":''; ?> /> |
Title: <form action="form_action.asp">
<select name="title">
<option value="Test Simple Search 1">Test Simple Search</option>
<option value="Searching Made Easy 101">Search Made Easy</option>
<option value="Gateway to Information">Gateway to Information</option>
<option value="The Gaming World as we Know it">Gaming World</option>
<option value="Hundreds of Ants Attacking">Ants Attacking</option>
<?php echo isset($_GET['title'])?"checked":''; ?> </select> |
Description: <input type="checkbox" name="desc" value="on" <?php echo isset($_GET['desc'])?"checked":''; ?> /><br />
Match All Selected Fields? <input type="checkbox" name="matchall" value="on" <?php echo isset($_GET['matchall'])?"checked":''; ?><br /><br />
<input type="submit" name="submit" value="Search!" />
</form>
<?php echo (count($results) > 0)?"Your search term: {$searchTerms} returned:<br /><br />" . implode("", $results):""; ?>
The option values that are used are the name as the titles stored within stitle within the mysql database. Have I simply implemented them wrong or is my php used after title completely incorrect?
Any advice on what I can do or any code snippets from yourselves would be very appreciated.
Ok I think I get your issue.
First if you want to select more than one item in a dropdown, then you need to add the multiple attribute to the select tag like this <select name="title" multiple>
Now when the user holds the CTRL key down and clicks entries, each clicked entry gets selected.
Secondly the data identifying the selected items will now be returned as an array in $_GET['title'] so if the first 2 options are selected the $_GET['title'] array would look something like this :-
0 - "Test Simple Search 1"
1 - "Searching Made Easy 101"
Now in order to re-select the items that were selected by the user when they submitted the form you have to set the selected="selected" attribute on each of the <option> tags that equate to the selected rows of the dropdown so they look selected when the user sees the form again.
<?php
function was_i_selected($selected_options, $value) {
if ( in_array($value, $selected_options, true) ) {
return 'selected="selected"';
} else {
return NULL;
}
}
?>
<select name="title" multiple>
<option <?php echo was_i_selected($_GET['title'], 'Test Simple Search 1');?> value="Test Simple Search 1">Test Simple Search</option>
<option <?php echo was_i_selected($_GET['title'], 'Searching Made Easy 101');?> value="Searching Made Easy 101">Search Made Easy</option>
<option <?php echo was_i_selected($_GET['title'], 'Gateway to Information');?> value="Gateway to Information">Gateway to Information</option>
<option <?php echo was_i_selected($_GET['title'], 'The Gaming World as we Know it');?> value="The Gaming World as we Know it">Gaming World</option>
<option <?php echo was_i_selected($_GET['title'], 'Hundreds of Ants Attacking');?> value="Hundreds of Ants Attacking">Ants Attacking</option>
</select>
Now that look very clumsy and we have not checked that $_GET['title'] actually exists, so I would probably do it like this :-
<?php
$options = array(
'Test Simple Search 1' => 'Test Simple Search',
'Searching Made Easy 101' => 'Search Made Easy',
'The Gaming World as we Know it' => 'Gaming World',
'Hundreds of Ants Attacking' => 'Ants Attacking'
);
<select name="title" multiple>
<?php
foreach ( $options as $val => $label ) {
if ( ! empty($_GET['title'] ) {
$sel = in_array($val, $_GET['title'], true) ? 'selected="selected"' : '';
echo '<option ' . $sel . ' value="' . $val . '">' . $label . '</option>';
} else {
echo '<option value="' . $val . '">' . $label . '</option>';
}
}
?>
</select>
I am trying to use the $_GET value to load on the same page as my form instead of opening a new page. For example, the form is on my page "products.php" and I want the form to filter database results by type of product. So on submit, it should redirect to "products.php?type=tee".
If I manually type it in the address bar it works like a charm, but I can't get the form submit to load it.
Here's my code (Update: Here's the whole file, using require_once into a basic html5 template):
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Populate Items to Show
function populateItems($result){
while ($row = $result->fetch_assoc()){
if ($row['available']){
echo '<li><img src="', $row['image'], '" />';
echo '<ul>';
echo '<li><h1>', $row['product'], '</h1></li>';
echo '<li><h2>', $row['description'], '</h2></li>';
echo '<li><h3>$', $row['price'], '</h3></li>';
echo '</ul>';
echo '</li>';
}
}
$result->free();
}
//Create Item List
echo '<ul class="item">';
//Create Filter
echo '<li id="filter">';
if ($result = $conn->query("SELECT DISTINCT type FROM products")){
echo 'Filter Results By: <form method="GET" action="', $_SERVER['PHP_SELF'], '">';
echo '<select>';
echo '<option>Show All</option>';
while ($type = $result->fetch_assoc()){
echo '<option name="type" value="', $type['type'], '">', $type['type'], 's</option>';
}
echo '</select>';
echo '<input type="submit" value="Go" />';
echo '</form>';
}
echo '</li>';
//Find if Filter Exists
if (isset($_GET['type']) && $_GET['type'] != "" ){
$gettype = $_GET['type'];
$filtertype = $conn->query("SELECT * FROM products WHERE type='$gettype'");
$count = $filtertype->num_rows;
if ($count <= 0){
populateItems($conn->query("SELECT * FROM products"));
}else{
populateItems($conn->query("SELECT * FROM products WHERE type='$gettype'"));
}
}else{
populateItems($conn->query("SELECT * FROM products"));
}
//End Item List
echo '</ul>';
?>
I've searched all over and haven't found anything that quite answers my question... Any help would be appreciated!
You have your <option name="type" named when it should be the <select>.
<option> does not have named attributes.
Therefore, you need to remove name="type" from your <option> and change your <select> to <select name="type">
Change
<form method="post" action="">
To
<form method="get" action="">
You have to change the Method if you want to use GET! Like this:
...<form method="get" action="">...