PHP/MySQL Search for Two Fields in one Table - php

I am building my first PHP/MySQL site and i would like to return search results from two fields in my one table within the database - Catagory, and Location (There are 15 fields in total in the table, but there are only two required for the search).
Each option will have a drop down menu which will list a fixed number of choices in each field - for instance, there will probably be 15 or so Locations, and 7 or 8 Catagories.
I want the user to be able to select an item from either one or both drop down menus, click a 'Search' or #Go' button, and be presented with the results.
As mentioned, i am brand new to PHP/MySQL so apologies if my question is a little 'simple' and i hope someone can point me in the right direction.
Thanks
Dan
EDIT:
Brad, Conner, I don't have anything thus far i'm afriad in terms of the search query specifics, i'm just starting to research how to do it hence complete lack of code in my question!
But to try and be more specific, the only fields i want to return results from are Location and Job Catagory - these are two fields of about 15 in my table that are already populated with fixed terms - e.g, Location may have London, Manchester, Leeds, and Catagory may have Administrative, Management, Clerical etc - there is no option for the visitor to input a new term, only select from a drop down menu of pre-arranged items.
The other fields in my table aren't relevant to the search (salary, company, contact email etc), so...I am thinking i only need two queries, and results can also be displayed if you only send one (e.g, you aren't bothered about job location, just speciality, you could still find all the results and decide if you fancied relocating). Is that any better or more helpful?
Thanks for you help so far.
Dan

A user enters a search query and you'd like to select the rows from your table that contain or exactly match that query? If so, something like
For if category contains $search_query
SELECT category, location
FROM table
WHERE concat(' ', category, ' ') LIKE '%$search_query%'
Or if it is an exact match you would use this for your conditional instead:
WHERE category = '$search_query'
I'm probably offtrack though, you need to specify like Brad said

Dan you need to build your sql statement dynamically. Below is a simple peice of code to demonstrate what I mean. Always besure to escapse user data to provent sql inject.
if ( isset($_POST['go']) ){
$location = $_POST['location'];
$category = $_POST['category'];
$sql = "SELECT * FROM table ID IS NOT NULL ";
if ( $location !="" ){
$sql .= " AND location = " . $location;
}
if ( $category !="" ){
$sql .= " AND category = " . $category;
}
}

Without any details on your table structure and the data in question, the basics would be somethign like:
SELECT ...
FROM ...
WHERE (field1 = $location_option) or (field2 = $category_option)

Related

How to handle database information changes with links using PHP and MySQL?

Say I have a website with a product page that displays information about the product which is generated by product.php using a GET on productname and getting information from a MySQL database. Now, occasionally product names will change. This will happen rarely but it will happen.
After the name change, old links to www.website.com/product.php?productname=Toaster400 will no longer work obviously. However, I would like for these links to redirect to the correct page. I would also like to allow people to search for "Toaster400" even though the corrected name is "Toaster400a".
I have thought of only one solution which is to have an table in MySQL of 'old names.' If a product is not found in the Product table, then I could check the 'old names' table and see which product that old name is related to.
Is this the best way of appraching this? Thank you.
Thank you.
EDIT:
Here's the code:
//This just initializes the database connection
require __DIR__ . "/resources/database.php";
//checks to see if they searched for anything
if(isset($_GET['search_text'])) {
$name = $_GET['search_text'];
$db = getDbConnection();
//This is a stored procedure which is literally just a select for % . ? . %
$stmt = $db->prepare("CALL get_products(?)");
$stmt->bindParam(1, $name, PDO::PARAM_STR, 150);
$isQueryOk = $stmt->execute();
$results = array();
The code then checks how many rows were returned and redirects accordingly.
You can consider 'tags' column in the table for a product. For example:
table column
id->1
Product name-> test
tags->test
after update, value of column will be
id->1
product name->testupdate
tags->test, testupdate
and by doing this, you can search renamed product. Hope this helps.:)
table product : product_id, product_name, description, etc.
table history : product_id, product_name
url : example.com/../sample_name
select * from product where product_name='sample_name'
if not found
select * from history h
left join product p on h.product_id=p.product_id
where h.product_name='sample_name'

How to seperate results from a mysql select

I apologize for this beginner question but unfortunately it is my level.
I have a fairly simple web page for my work, it is a index.php page that when opened goes out to a DB and retrieves the contents of a certain column. It then places the results in a drop down pick list.
Here is my problem, this column is a list of materials for customers. Some customers have more than 1 different type of material, while others have one.
Therefore my pick list can look like:
Apple /n
Orange; Apple; banana/n
banana;peach /n
orange/n
I am trying to come up with something that when I pull the data from the mysql DB that my php seperates the materials and only provides unique items.
Here is my code for creating picklist:
<p><select size="1" name="material" ID="material" onChange="showfield(value);">
<option value=''><None></option>;
<?php
while ($row = mysql_fetch_array($query))
{
$rowmod = strtr($row['material']," ","_");
echo "<option value='$rowmod'>$row[material]</option>";
}
?>
Here is my mysql select:
$query="select distinct material from TABLE-A order by material";
Update:
I think my Mysql is right, I think I played around with the php strtr and I was able to remove the ; and add lines in, but now I do not know how to make it cycle through and create my
here is the new code:
$row[product]";
}
?>
some output from my $row will have only one product, some will have 2 or more, I wonder if I have to put another while loop after the $rowmod?
I have a feeling I am close, but hoping for some guidance.
First of all, you should make a material table, indexed with an auto_increment id, and use that ID in what you call TABLE-A in a column material_id. Like that you'll have a list of unique material in one table dedicated to it, where you can even add some columns for the details of the material, etc..
Then I am unsure of your needs/use-case, but it looks like you'll need a customer_material table to link a customer with its material(s) so that you know which customer uses which material. It would have an id auto-incremented, as it should always be for any table for better practices, a customer_id and a material_id, with an unique index on the both last columns (customer_id+material_id) to be sure you link one material to one customer only once and not many time each material for the same customer.
Then when you'll need to list the materials for a given customer, just use this query:
select m.id, m.name
from customer_material cm
join material m on cm.material_id = m.id
where cm.customer_id = YOUR_CUSTOMER_ID
If you need to list all materials uniquely, you;ll then need this query:
select m.id, m.name
from material m
order by m.name /* optional, to order by the material name */
And voila. As I am unsure of your use-case the schema of the DB might be a bit different, but I think anyway the main problem in your issue is that the DB is not well architected. Lemme know if I something is unclear here.
You mentioned that different customers have different materials, but that is not reflected in your SQL query because there is no WHERE clause, meaning that you are selecting all unique values from the materials table regardless of any condition. But with that aside, I think that if you change your code slightly you will get some data.
$query="select distinct `material` from `TABLE-A` order by material"
<p><select size="1" name="material" ID="material" onChange="showfield(value);">
<option value=''><None></option>;
<?php
while ($row = mysql_fetch_assoc($query))
{
$rowmod = strtr($row['material']," ","_");
echo "<option value='$rowmod'>$row['material']</option>";
}
?>

Checkbox php and mysql

I am building a website with PHP, I am not so good at php but i have found good tutorial online.
The website is for people to register as a dog walker, so when someone registers i want them to check the box of the areas that corresponds to them but there are many areas (100+) so I do not know whats the best way to do it using php and mysql. (i dont know anything about JS but i cant look for tutos)
Should all the names of the areas be store in one fild in the database or i have to build one field for each area?
I want people to be able to update the areas.
Then i wanted to have a select form with the search button.
I just want to know in words what is the best way to do it.
Thank you.
I think the best practice is to get a one-to-many relationship in your database. Which means in a simplified way '1 walker can have many areas'.
If I understond Sable Foste's comment correct, he's telling you to create one column in your user table for each area, this would require a massive database table. Besides, updating your script would be a huge pain in the ass since you would have to add each area manually. Instead I would suggest you to create two tables:
table users
user_id
user_name
table areas
area_id
area_name
Fill the areas table with all options you have. Now, when a user wants to register on your page, you can perform an SQL query which fetches all areas like so:
$areas = $database->query("SELECT * FROM areas ORDER BY area_name ASC");
if( $database->num_rows( $areas ) > 0 ) {
foreach( $database->fetch_array($areas) as $area ) {
echo '<input type="radio" name="area[]" value="'.$area['area_id'].'" /> '.$area['area_name'].'<br />';
}
}
$database illustrates a database wrapper in this example. You can also use mysql_ functions, however, they are about to be deprecated from PHP, so instead try to find tutorials on mysqli_ functions or PDO database layer.
As you can see I've named the fields area[], by doing this we get an array after we submit our register form. This array can be looped and contains all checked radio buttons. Each radio button contains the area_id:
if( isset( $_SERVER['REQUEST_METHOD'] == "POST" )) {
// Make sure you check data here and insert the user in the database first before proceeding
foreach( $_POST['areas'] as $area_id ) {
// Do something with the $area_id
}
}
Since we still have no option to connect the area_id to the user_id. To do so, we create another table that saves the connections:
table users_to_areas
area_id
user_id
In this database you will store each $area_id together with the $user_id of a newly registered or logged in user. NOTE: if you are updating a userprofile you can simply delete all previous records (DELETE FROM users_to_areas WHERE user_id = $user_id) and insert them again using the same looping method as above.
On the edit profile page, you can use the same script to list all areas again, to see if a user is connected to the area you can use a simple query (SELECT COUNT(*) FROM users_to_areas WHERE user_id = $user_id AND area_id = $area_id), if the num_rows() function returns 1 then the checkbox should be checked, otherwise it should be unchecked.
Hope this kicks you off in the right direction, good luck.
You should store all of your fields in separate rows. So if you have 100 areas, you should have 100 1 column rows (you can have more columns if there are other corresponding information you want to store).
The rest of your question is much more open-ended. You'll need to show some examples of what you are working with or have built to make it more clear

Display categories from a database

I am currently updating my site. As you can see I currently have a list of catagories (example: Free Offers, Gifts, Accessories).
These catagories will then list to promotions and then link to a single page and each one of my promotion is saved in MySQL under my DBNAME xclocouk_mobile and table mobi and each one has a promo_cat as the field name with a category underneath it.
I know how to connect to this database. What I want to know is how do I get my index page to read and display a list of catagories found under the promo_cat as listed above?
I need them to list the title as shown on my page which is done manually. But I do not want it to display duplicates.
How can I accomplish this?
$q = "SELECT promo_cat FROM mobi";
$result = mysql_query($q,$connection);
while($output = mysql_fetch_array($result)) {
echo $output['category'];
}
EDIT:
this will list duplicates if there are duplicates in your database, else it won't.
If you have duplicates in your db, use "select distinct(promo_cat) .. "
You want to use DISTINCT
SELECT DISTINCT(promo_cat) FROM xclocoauk.mobi

SQL queries or php code?

Hello i am in a delima
Suppose that i have 50 products in a category and i want to get all the features of my products...
Ofcourse a SQL join wont help because joining would return product info many times!
So here is the question.. what is better
PLAN A
Get all the products' features in category with one SQL query and then iterate with php each feature and put it in Product.
PLAN B
For each product get the features by calling a query
Other solutions accepted!
EDIT
My table schema outline is..
A table Product which has product info(per row)
A table features which has features (feature id )
A table for features' values
And a table that has Products with their features and values
$sql1 = "SELECT * FROM products P, ". //don't use star, make sure no fields are overwritten
INNER JOIN products_to_features PTF on P.id = PTF.project_id
INNER JOIN features F F.id = PTF.feature_id
ORDER BY P.id";
$r = mysql_query($sql1, $conn);
$arr = array();
$lastProductId = -1;
while ($row = mysql_fetch_assoc($r))
{
if ($row[p_id] != $lastProductId)
{
$lastProductId = $row['p_id'];
$arr['p_id'] = array('productName' => $row['p_name'],
'productPrice' = $row['p_price'],
'productFeatures' = array(),
//other fields from product table);
}
$arr['p_id']['productFeatures']['f_id'] = array('featureName' => $row['f_name'], blah...);
}
I don't know your fields obviously, and you may want to join on feature_values so that will be more work. You can do keys/values different (ie - product names as keys. Feature-name as keys with feature-value as values, whatever you want) but the point is this is doable (and recommended) in one query.
Not Plan B.
Whatever you do this can and should be done with one or at most two total queries (one for headers, one for correctly sorted list of features + id column). Whether that query is Plan A or some unmentioned Plan C depends on your exact table structure, which isn't clear from your question.
Generally, the less database queries you have to make, the better. It greatly depends on your table structure, but I'd go with Plan A.
A query inside a loop will greatly degrade performance of your application. Avoid it at all cost.
Show us the schema. There's a strong possibility a single SQL query will solve your problem.

Categories