i have a database like this
prod_id prod_name catogory_1 catogory_2 catogary_3
now i want place my filter like this
<slect id="filter for cat 1">
<option vlaue="all">all</option>
<option vlaue="caps">Caps</option>
<option vlaue="shoose">shoose</option>
<option vlaue="cloths">cloths</option>
<option vlaue="bags">bags</option>
</slect>
<slect id="filter for cat 2">
<option vlaue="all">all</option>
<option vlaue="mens">mans</option>
<option vlaue="womens">wonens</option>
<option vlaue="babys">babys</option>
</slect>
<slect id="filter for cat 3">
<option vlaue="all">all</option>
<option vlaue="large">Larg</option>
<option vlaue="midum">midum</option>
<option vlaue="small">small</option>
</slect>
<div id="display_prod_list">
here goes the list
</div>
my function
<?php
function display_product() {
$query = mysql_query("SELECT `pord_id` AS `id`, `prod_name` AS `name`,
`catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`,
`catogory_3` AS `catogory_3` FROM `porducts`");
$products = array();
while(($rows = mysql_fetch_assoc($query))!== false) {
$products[] = $rows;
}
return $pruducts;
}
?>
this function returns all products i want to change this function to return only filtered products
how can i do that? please help me. can i do this with php or i have to use jquery or something. please
tell me the best way to filter my products thanks
I don't know if this is about what you asking for, but hope it helps.
Use a WHERE clause on your MySQL query, for example:
SELECT `pord_id` AS `id`, `prod_name` AS `name`,
`catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`,
`catogory_3` AS `catogory_3`
FROM `porducts`
WHERE catogory_1 = 'caps' AND catagory_2 = 'babys';
You could build your query condition in this way:
$conditions = array();
$condition_string = '';
if ($catagory_1 != 'all') { $conditions[] = "catagory_1 = $catagory_1 "; }
if ($catagory_2 != 'all') { $conditions[] = "catagory_2 = $catagory_2 "; }
if ($catagory_3 != 'all') { $conditions[] = "catagory_3 = $catagory_3 "; }
if ($conditions) { $condition_string = ' WHERE '. implode($conditions, ' AND '); }
$sql =
"SELECT `pord_id` AS `id`, `prod_name` AS `name`,
`catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`,
`catogory_3` AS `catogory_3`
FROM `porducts` $condition_string ";
Just PHP
A standard HTML form that sumbits to the php script which executes query based on the filter values when the submit button is pressed.
The use the SQL WHERE clause to narrow down your results to products that match the criteria.
eg. WHERE catogory_1 = 'caps' AND catagory_2 = 'babys';
You will also need to put some logic in the php to prevent you from querying for a category when the filter value is 'all', as you can effectively ignore those categories.
Then output your results.
PHP & jQuery
You could use jQuery to populate the products part of the page with only the products that match the category filters when a filter is changed rather than reloading the page. A ajax request is made to the a php script that queries based on the current filters.
For example, all products are shown when your page loads at first then the "filter for category 1" is changed to "caps", using jQuery to detect a change event on the filter an ajax call to a php script that would run the following query.
SELECT `pord_id` AS `id`, `prod_name` AS `name`,
`catogory_1` AS `catogory_1`, `catogory_2` AS `catogory_2`,
`catogory_3` AS `catogory_3`
FROM `porducts`
WHERE catogory_1 = 'caps';
Then build your HTML based on the results and this is sent back as the ajax response and you should use it to replace the current HTML for the products.
Related
I have a form with 3 select boxes: age,room,type.
<form action="results.php" method="get">
<div class="form-group">
<select name="age">
<option value>Any</option>
<option value="1">15</option>
<option value="2">25</option>
<option value="3">30</option>
<option value="4">40</option>
</select>
</div>
<div class="form-group">
<select name="room">
<option value>Any</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="form-group">
<select name="type">
<option value>Any</option>
<option value="1">Personal</option>
<option value="2">Business</option>
</select>
</div>
</form>
What i am trying to do with PDO is to make a small search.
If all variables are empty then my condition is:
$search = $db->query("SELECT * FROM table");
If 1 of them (as example the age) is not empty then i have:
if(!empty($_GET['age'])){
$age = $_GET['age'];
$search = $db->query("SELECT * FROM table WHERE age = '$age'");
}
Now, if 2 of them are npt empty i have:
if(!empty($_GET['age']) && !empty($GET['room'])){
$age = $_GET['age'];
$room = $_GET['room'];
$search = $db->query("SELECT * FROM table WHERE age = '$age' AND room = '$room'");
}
In order to avoid all possible search combinations, how can i make a search with the term if is not empty. I had made one in the past:
if(!empty($age)){
$where = "WHERE age = '$age'";
}
if(!empty($room)){
$where .= "and room = '$room'";
}
$query = "SELECT * FROM table $where";
How can i make it happen with PDO?? :/
I'd do something like this:
$param = array();
$query = 'SELECT ... FROM t WHERE 1=1';
if(!empty($_GET['age'])){
$param['age'] = $_GET['age'];
$query .= ' AND t.age = :age';
}
if(!empty($_GET['room'])){
$param['room'] = $_GET['room'];
$query .= ' AND t.room = :room';
}
if(!empty($_GET['type'])){
$param['type'] = $_GET['type'];
$query .= ' AND t.type = :type';
}
$dbh->prepare($query)->execute($param);
You might want to separate out the prepare and the execute. Check the return from the prepare before you try calling execute. Or, configure PDO can throw an exception when an error occurs, e.g.
$dbh->setAttribute(PDO::ERRMODE_EXCEPTION);
You will need to make a query builder of some kind. You will also want to use prepared statements, rather than directly injecting user-provided input into the sql query. That might look something like this:
<?php
$search = [
'age' => 42,
'room' => 'Millyway',
];
$criteria = [];
$params = [];
foreach($search as $field => $value) {
$criteria[] = "$field = :$field";
$params[$field] = $value;
}
$where = ($criteria ? ('WHERE ' . implode(' AND ', $criteria)) : '');
$query = "SELECT * FROM tablename $where";
$stmt = $db->prepare($query);
$stmt->execute($params);
while($obj = $stmt->fetchObject()) {
// iterate over your result set
}
Given search terms as key-values in $search (which can be any column and value in the table, and will need to be populated from wherever those values come from), this code will build $criteria, a set of WHERE clause fragments (using a parameterized sql parameter name, rather than injecting the value directly), and $params, the list of parameters to be passed into the (upcoming) prepared statement.
It then builds the full WHERE clause in $where, by either combining all of the $criteria that were built, or returning an empty string. This is then added directly into the query, and the query is executed using the parameters array that was built up. You then iterate over the result set like any other PDO query.
Among others, the main benefit of using parameterized SQL over injecting variables directly is that it protects you from SQL Injection attacks.
Note that there are many ways this code could be improved. You could easily put it in a function; add complexity to allow for different types of comparisons (e.g. <> or LIKE); even use it as the basis for a more complicated query builder that allows more complicated logic such as ((age = :age AND room = :room1) OR (room = :room2)); and so on. What you do is up to the needs of your application.
I want to eliminate all the duplicates in a select dropdown list created with PHP.
My PHP code that creates the dropdown list is the following:
public static function getDropdownlist($conn)
{
//Initialize dropdown list
//--------------------------------------------------
$ddl_query = "select * from MIS_EMPLOYEES";
$stmt_ddl = oci_parse($conn, $ddl_query);
oci_execute($stmt_ddl);
//A default value -- this will be the selected item in the dropdown ##
$prosopiko = JRequest::getVar('bodies', 0);
if ($prosopiko == 0)
$default = 0;
else
$default = $prosopiko;
//Initialize array to store dropdown options ##
$options = array();
// $options = array_unique();
$options[] = JHTML::_('select.option', '0', 'Επιλέξτε');
while (($row = oci_fetch_array($stmt_ddl, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
$options[] = JHTML::_('select.option', $row['ID'], $row['POSITION']);
}
//Create <select name="month" class="inputbox"></select> ##
$dropdown = JHTML::_('select.genericlist', $options, 'bodies', 'class="inputbox"', 'value', 'text', $default);
return $dropdown;
}
}
But it brings all the duplicates written from an Oracle table.
How can I eliminate the duplicates? I tried array_unique but I failed.
In your SQL statement, simply change it to gather distinct elements you are interested in.
Since you are only using two values in the above code for the value and text, something like this should work:
SELECT ID, POSITION
FROM MIS_EMPLOYEES
GROUP BY ID, POSITION
Easiest option is to modify your query to SELECT DISTINCT ID, POSITION or GROUP BY ID, POSITION. Other than that you'll need to build up an array and use array_unique on that.
How to insert into MySQL from an HTML select multiple
This is my code HTML:
<select name="domaine[]" id="domaine" class="validate[required]" multiple>
<option></option>
<option value="WEB">WEB</option>
<option value="Java2EE">Java2EE</option>
<option value="android">android</option>
<option value="VB.Net">VB.Net</option>
<option value="iOS">iOS</option>
<option value="C++">C++</option>
</select>
This is my php code:
try{
$cdb=new PDO('mysql:host=localhost;dbname=source', 'root','');
} catch (Exception $e){
die("erreur".$e->getMessage());
}
$cin=$_SESSION['cin'];
$rep=$cdb->prepare("insert into dev (cin,comp)values('$cin','".$_POST["domaine"]."')");
$rep->execute();
It's very nice that you're using PDO, but your code is still vulnerable. VALUES takes multiple arguments.
if (isset($_POST['domaine']) && is_array($_POST['domaine'])) {
//(?,?),(?,?),(?,?) for 3 domaine
$values = implode(',', array_fill(0, count($_POST['domaine']), '(?,?)'));
$query = "INSERT INTO dev (cin, comp) VALUES $values";
$params = array();
foreach ($_POST['domaine'] as $d) {
array_push($params, $cin, $d);
}
$rep = $cdb->prepare($query);
$rep->execute($params);
}
You could also prepare a single INSERT statement and loop over execute, but I believe this is more efficient.
$_POST["domaine"] is an array, so puting it "as is" will result as "Array" in your database record.
You need to decide which type of "array->string" method is best for your app and use it before you insert into database.
Easiest way is to use a join($sep, $_POST['domaine']) or serialize($_POST['domaine']).
foreach ( $_POST["domaine"] as $aSelectedOption){
$rep=$cdb->prepare("insert into dev (cin,comp)values('$cin','".$aSelectedOption."') ");
$rep->execute();
}
this will insert an entry for each checked option
you could also use json_encode and json_decode though i wont suggest it.
This is part of code from my backoffice page. ( is an edit.php page for a user to edit / modify )
// first query to get cats from user table
$query = "select * from user where name='".$_SESSION['username']."' order by id ASC limit 1";
$result=mysql_query($query);
if (mysql_num_rows($result)) {
while($row=mysql_fetch_array($result)){
$cat1 = $row['cat1'];
$cat2 = $row['cat2'];
$cat3 = $row['cat3'];
$cat4 = $row['cat4'];
$cat5 = $row['cat5'];
$cat6 = $row['cat6'];
$cat7 = $row['cat7'];
$cat8 = $row['cat8'];
$cat9 = $row['cat9'];
$cat10 = $row['cat10'];
}
}
// now i want to build 10 select boxes with selected according the user table $cats
// below is what i can build to first box $cat1
// is there a way i can produce this for the 10 select boxes whitout having to make 10 cycles of bellow code
<select name="theme" id="theme">
<?php
$q1 = 'SELECT * FROM cats ORDER BY title ASC';
$r1 = mysql_query($q1);
while( $row = mysql_fetch_array($r1)) {
if ( $cat1 == $row['id'] ) {
print "<option class=\"cssoption\" selected=\"selected\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
else {
print "<option class=\"cssoption\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
}
?>
</select>
I am not a coder so this might not be effective code.
Hope someone can help me here and understands what i am trying to do.
Many Thanks.
The code is fine. This 10 cycles as you name it is a almost zero cost.
This is the usual way we do it, we fetch sequentialy the records one by one.
In addition it makes no sense to ask not to do the 10 cycles because you are applying an if else condition in the same time, this means that you check every record if the cat id is the same with the row so you need the loop.
On the other hand if for some reason you want to skip some records, you can use the mysql seek function to start fetching from the desired record.
for($i=0;$i<99999;$i++)
(9999*9999);
echo 'This time the cost of this loop was:',(microtime()-$start),' seconds.';
?>
Okay, so I have this form that is set to preload a DB record for editing if you add a ?edit=1 to the url, it will load record #1 for editing into the form. I have a box that is like this-
<select class="field select addr">
<option value="no"<?php if($row['has_amenities'] == "no") {echo ' selected=\"selected\"'; } ?>>No</option>
<option value="yes"<?php if($row['has_amenities'] == "yes") {echo 'selected=\"selected\"'; } ?>>Yes</option>
</select>
Now, let's say that $row['has_amenities'] is "yes" so when the form loads, the select box is showing "Yes".
BUT, if I change the select box to "No" and click save, it doesn't write "no" to the DB, but it does wipe out that record's "yes" with nothing.
What am I doing wrong?
Here's the update code--
$sql = "UPDATE venues SET microsite_title = '$_POST[microsite_title]',
microsite_city_title = '$_POST[microsite_city_title]', logo = '$_POST[logo]', photo1 =
'$_POST[photo1]', photo2 = '$_POST[photo2]', photo3 = '$_POST[photo3]', photo4 =
'$_POST[photo4]', photo5 = '$_POST[photo5]', photo6 = '$_POST[photo6]', photo7 =
'$_POST[photo7]', photo8 = '$_POST[photo8]', website_primary = '$_POST[website_primary]',
website_secondary = '$_POST[website_secondary]', paragraph_1_title =
'$_POST[paragraph_1_title]', paragraph_1 = '$_POST[paragraph_1]', paragraph_2_title =
'$_POST[paragraph_2_title]', paragraph_2 = '$_POST[paragraph_2]', paragraph_3_title =
'$_POST[paragraph_3_title]', paragraph_3 = '$_POST[paragraph_3]', paragraph_4_title =
'$_POST[paragraph_4_title]', paragraph_4 = '$_POST[paragraph_4]', paragraph_5_title =
'$_POST[paragraph_5_title]', paragraph_5 = '$_POST[paragraph_5]', paragraph_6_title =
'$_POST[paragraph_6_title]', paragraph_6 = '$_POST[paragraph_6]', top10_1 =
'$_POST[top10_1]', top10_2 = '$_POST[top10_2]', top10_3 = '$_POST[top10_3]', top10_4 =
'$_POST[top10_4]', top10_5 = '$_POST[top10_5]', top10_6 = '$_POST[top10_6]', top10_7 =
'$_POST[top10_7]', top10_8 = '$_POST[top10_8]', top10_9 = '$_POST[top10_9]', top10_10 =
'$_POST[top10_10]', top10_locale = '$_POST[top10_locale]', contact_title =
'$_POST[contact_title]', contact_street_addr = '$_POST[contact_street_addr]',
contact_street_addr2 = '$_POST[contact_street_addr2]', contact_city =
'$_POST[contact_city]', contact_state = '$_POST[contact_state]', contact_zip =
'$_POST[contact_zip]', contact_phone = '$_POST[contact_phone]', contact_tollfree =
'$_POST[contact_tollfree]', latitude = '$_POST[latitude]', longitude = '$_POST[longitude]',
testimonial = '$_POST[testimonial]', sidebar_title = '$_POST[sidebar_title]',
sidebar_content = '$_POST[sidebar_content]', has_amenities = '$_POST[has_amenities]'
WHERE id = '$_POST[query]'";
Also, I know it's not a good idea to write $_POST values without cleaning them first, but this is an internal form behind a firewall, etc. I'll clean it up later after it's working :o)
Thanks!
It looks like the <select> element has no name or id--is that the case in your code? If so, I believe $_POST[has_amenities] won't be set--there would be no has_amenities value in $_POST. You'd get an empty string instead.
Wrap all of the instances of $_POST[] in {} (curly braces) so it looks like this
'{$_POST['key']}'
The curly braces are need to force PHP to evaluate $_POST as a variable when it's inside a double-quoted string.
Also, quote your $_POST array keys like this
$_POST['key']
You want to get in the habit of this even though $_POST[key] will usually work. PHP is treating key as an constant which, if it's undefined, is automatically turned into a the string "key" so you get the behavior you're expecting.
However, if key already exists as a constant (via the define()) function, you'll get the value of the key constant which is not what you want.
Take a look at the Array do's and don'ts section.
Try wrapping your array variables with curly braces like so:
'$_POST[paragraph_3]' = '{$_POST[paragraph_3]}'
You'll need to specify a name for this select tag. I also see you're escaping your double-quotes with backslashes, which is unnecessary (it will literally use \" so the output would look like: selected=\"selected\" which is bad html).
Try using this:
<select name="has_amenities" class="field select addr">
<option value="no"<?php if($row['has_amenities'] == "no") {echo ' selected="selected"'; } ?>>No</option>
<option value="yes"<?php if($row['has_amenities'] == "yes") {echo 'selected="selected"'; } ?>>Yes</option>
</select>
Your SQL statement will work the way it is, but not that if a single quote is entered by the user, it will break the statement...possibly causing a huge security hole. Check out "SQL injection" on the google.