Populate select drop down with data from two mysql queries - php

I'm sure this is easy to figure out to most anyone who knows PHP and mysql but I am not able to figure it out. I will try to explain in the best way possible
Please let me know if I'm miss something
Relevant Table structure
Table | Fields
category | id,group_n (more fields exist but are not required now)
p_group | id,group_n
what I want to achieve:
Query to find currently selected group_n field in category table if available based on the current _isset id taken from the _get URL in relation to the category.
Example of work flow :
sample rows for category
ID | category | short | group_n
1 | Skin Whitening Pills | pills | Skin Whitening
2 | Skin Whitening Cream | cream | Skin Whitening
3 | Weight Gain / Loss | wgainl | Weight Gain / Loss
As you can see multiple categories can have a single group_n. I use the group_n to show an expert for that group.
select option is populated with the field group_n from category
select options are populated with all options from p_group (except selected so there is no duplicate"
category with id 2 has group_n as Skin Whitening
edit_category.php?id=2 would display all input options for for id 2 that are currently in the table row in order to edit them and update the query. Now when the select options for the group_n are populated the selected should be Skin Whitening but all rows in p_group should be available to select.
code
<?php
$qry=mysql_query("SELECT group_n from category where id=$id", $con);
if(!$qry)
{
die("Query Failed: ". mysql_error());
}
?>
<select name="group" id="group">
<?php
// First, define the desired default value
$default_value = $row['group_n'];
while($row=mysql_fetch_array($qry))
{
// Then you can mark that one as selected in your "while" loop
$selected = ($row['group_n'] == $default_value) ? ' selected' : '';
$qry2=mysql_query("SELECT * from p_group", $con);
while ($row2 = mysql_fetch_array($qry2))
{
echo "<option value='" . $row2['group_n'] . "'" . $selected . ">" . $row2['group_n'] . "</option>";
}
}
?>
</select>
I've also tried with a single query left joining the two tables but the following query will list only a single row which doesn't get auto populated but gives the right value.
$qry=mysql_query("
SELECT a.group_n,
b.group_n from p_group a
left join category b
on a.group_n=b.group_n
group by b.group_n where b.id=$id", $con);
I am not sure whether my query needs to be changed or the php but I can only get one of the queries to work with the select at a single time. I need to know how to get either both queries to work so selected option is one from the category table and the drop down from p_group table.
Ideally I would want the category table to be associated with the id from p_group but for now I'd settle for keeping it as text.

After waiting for input from the user community which is unusually quiet this week, I searched around and fiddled with code until I came to the UNION sql join. This basically takes two sets of data and presents as one which did the trick. Not sure if this is the best way and maybe there is a pure PHP way, but this did the trick.
SQL snippet
$qry=mysql_query("select group_n as group_a from category where id=$id union select group_n from p_group group by group_n", $con);
Basically this would select query on left union it with the query on the right and display all the records.
Limitations
1. field count selected must match
2. UNION will select no duplicates
3. UNION ALL will select duplicates
full relevant code :
$qry=mysql_query("select group_n as group_a from category where id=$id union select group_n from p_group group by group_n", $con);
if(!$qry)
{
die("Query Failed: ". mysql_error());
}
// First, define the desired default value
$default_value = $row['group_a'];
while($row=mysql_fetch_array($qry))
{
$selected = ($row['group_a'] == $default_value) ? ' selected' : '';
// Then you can mark that one as selected in your "while" loop
echo "<option value='" . $row['group_a'] . "'" . $selected . ">" . $row['group_a'] . "</option>";
}
?>
</select>

Related

Automatically add SQL Querys based on checkboxes input and text input - trying to build a search filtering system

I am trying to build a filtering system that shows results based on text input and checkbox options selected by a user.
My database currently has 3 tables
table 1 : brunches
table 2 : vibes
table 3 : cuisines
brunches contains a list of restaurants, and in thebrunchesvibescontains vibes andbrunchescuisinestables contains the food that the restaurants frombrunches` offers.
So for example
Table 1 - Brunches
id Name
1 Jamies Brunch
2 Roka
3 Mcdonalds
Table 2 - Vibes
id vibe brunchid
1 Arty 1
2 Luxury 1
3 Trendy 3
Table 3 - Cuisines
id cuisines brunchid
1 BBQ 1
2 Japanese 1
3 British 3
As you can see all the tables match up via brunchid.
What I am trying to achieve is i have a bunch of checkboxes in a form, which contains a list of 'vibes' and 'cuisines', when a user checks the vibes and cuisines they want displayed, it should then run a query and show only those results.
this is the php code so far, however it doesn't work - when i select multiple options, it returns an sql error, because it is just doing an AND statement, that being said, I'm not sure if the way i've got it searching the vibes table is correct... and i'm not sure how to add OR statements when there are multiple options selected.
$type = $this->input->post("type");
$name = $this->input->post("brunchname");
$vibes = $this->input->post("vibes");
$cuisines = $this->input->post("cuisines");
$range = $this->input->post("range");
$sqlQuery = "SELECT b.*, host,
FROM brunches b
LEFT JOIN hosts ON hosts.id = b.hostid ";
if(! empty($vibes)) {
foreach ($vibes as $v):
$sqlQuery .= "WHERE b.id in (
select bv.brunchid from brunchvibes bv where bv.vibe = '$v')";
endforeach;
}
if(! empty($cuisines)) {
foreach ($cuisines as $c):
$sqlQuery .= "WHERE b.id in (
select b.brunchid from brunchcuisines bc where bc.cuisine = '$c')";
endforeach;
}
if(! empty($name)) {
$sqlQuery .= "name LIKE '%$name%')";
endforeach;
}
$sqlQuery .=" AND approved ='1'";

Only get one occurance of a table row in mysql php based on id

I have a table that looks like this
id | itemID | catID | Title
----------------------------------------------------------------------------
0 3 4 Hello
1 3 6 Hello
2 4 4 Yo
3 4 8 Yo
4 5 2 Hi
5 1 3 What
I want to do a MySQL PHP Select that only gets one occurrence of the itemID. As you can see they are the same item, just in different categories.
This is what I tried
SELECT * FROM Table GROUP BY itemID
That didn't seem to work, it still just shows duplicates.
Is this what you are looking for? http://www.sqlfiddle.com/#!2/5ba87/1
select itemID, Title from test group by itemID;
As far as MySQL is concerned, the data is all unique, since you want all of the columns. You have to be more specific.
Do you just want the itemID (or other column)? Then say so:
select [column] from Table GROUP BY itemID
Do you want the last entry of a particular item ID? Then say that:
select * from Table where itemID = 1 ORDER BY id DESC
Or the first one?
select * from Table where itemID = 1 ORDER BY id
If none of these are what you want, then you probably need to restructure your tables. It looks like you want different categories for your items. If so, then you'll want to split them out into a new join table, because you have a many-to-many relationship between Items and Categories. I recommend reading up on database normalization, so you're not duplicating data (such as you are with the titles).
If you want everything for the distinct itemIDs, you could certainly take a long route by doing one selection of all of the distinct itemIDs, then doing a series of selections based on the first query's results.
select distinct(`itemID`) from Table
Then in your PHP code, do something like this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$itemID = $row['itemID'];
$sql2 ="SELECT * FROM Table WHERE 1 and `itemID`=\"$itemID\" limit 1";
$result2 = #mysql_query($sql2, $connection);
while ($row2 = mysql_fetch_array($result2))
{
$id = $row2['id'];
$itemID = $row2['itemID'];
$catID = $row2['catID'];
$Title = $row2['Title'];
}
}

PHP-MySQL Tagging

I have a comics website which currently allows users to choose which comics they view by category: Charts, Office, Life, Misc, etc.
I'd like to implement a tagging system, similar to what we have here on StackOverflow, which will describe more of the content of each comic rather than its category. Ex: In Charts category, I have several business related...
My simple solution would be to handle it just how I've handled my categorization-
Create a "Tags" table with tagid, tagname, tagdescription
Add a tagid_ForeignKey field in comics table, and add a tag to each post.
When a user clicks on a tag, it will show only those posts with that tag... or if there is also a category specified, it will show that specific category with that specific tag.
This approach, however, seems to limit me to one tag per category. What if I have a comic that is business and relationships related... so It'd need both of those tags.
How would I be able to attach multiple tags per comic?
EDIT:
A few more questions:
1) What do I insert into my new relational table... anything?
2) Also, for while ($row = $tag->fetch_assoc()) {, how can I loop through a table if there is a join? Isn't that an associative array?
3) The issue is that I am echoing out the tag choices as such, so once a user clicks on a link, how would you be able to allow them to then click on another link to assign a 2nd tag?
function getTags() {
include 'dbconnect.php';
global $site;
$tag = $mysqli->query("SELECT tagid, tagname FROM tags");
//$tag = $mysqli->query("SELECT * FROM comics c INNER JOIN comictags ct ON (c.comicID = ct.comicID) WHERE ct.tag_id IN (1, 2, 3) GROUP BY c.comic_id");
mysqli_close($mysqli);
while ($row = $tag->fetch_assoc()) {
echo "<a href='?action=homepage&site=" . $site . "&tag=" . $row['tagid'] . "&tagname=" . $row['tagname'] . "'/>" . $row['tagname'] . "</a><br />";
}
}
Just add another table. Then you have three: One for Tags, one for Comics, and one for the relationship. You have to have this indirection table to properly store a many-to-many relationship. This allows each comic to have zero or more tags (and vice versa).
You can accomplish this with a many-to-many relationship. A many-to-many relationship uses a relational join table that would look like this:
+---------------+---------------+
| comic_id | tag_id |
+---------------+---------------+
| 1 | 2 |
+---------------+---------------+
| 1 | 3 |
+---------------+---------------+
| 1 | 4 |
+---------------+---------------+
Now, in your query:
SELECT * FROM comics c INNER JOIN comic_tags ct ON (c.comic_id = ct.comic_id) WHERE ct.tag_id IN (1, 2, 3) GROUP BY c.comic_id
Where 1, 2, 3 are the tags the user selected that they would like to see.

Collect values from DB, group matching values, count it and use in other code

This is what my customers_basket table looks like:
customers_id | products_id | basket_quantity
3 | 56:3121fefbe6043d6fc12e3b3de2c8fc38 | 3
3 | 56:fb4c9278fcfe6225b58c06711a7e62ef | 1
3 | 56:8e334fce09556108f5416e27154b6c27 | 1
3 | 52:f3b9f38e4ddd18035bc04cd264b0f052 | 1
This is the query I'm using:
$products_in_cart_query = "SELECT products_id FROM customers_basket WHERE customers_id = " . $_SESSION['customer_id'] ."";
$products_in_cart = $db->Execute($products_in_cart_query);
$products_in_cart_model = $products_in_cart->fields['products_id'];
$products_in_cart_model = substr($products_in_cart_model, 0, strpos($products_in_cart_model, ":"));
The end result I get is 56,56,56,52
First of all, how do I use the first line's quantity field? I'd need to list that products_id 3 times since quantity is 3. Therefore, the end result needs to be: 56,56,56,56,56,52
or, for easier understanding (56,56,56),56,56,52
And second, how do I count how many same values I have? In this case, I have 5x56 and 1x52. I need to use those counts in my further calculation.
EDIT: further calculations explained
I need to know how many of each product_id I have and then run something like this:
foreach(product_id) {
$shipping_cost += FIXED_VALUE * basket_qty;
}
To get the basket quantity, you have to select it. It would be best if the first portion of the product ID was stored in a separate column, rather than having to do messy operations like substringing.
Query 1: 2-character codes and corresponding quantities
SELECT SUBSTR(products_id, 1, 2) AS product_code, basket_quantity
FROM Customers_Basket
WHERE customers_id = 3;
Query 2: 2-character codes and summed quantities
SELECT product_code, SUM(basket_quantity) AS total_quantity
FROM (SELECT SUBSTR(products_id, 1, 2) AS product_code, basket_quantity
FROM Customers_Basket
WHERE customers_id = 3
)
GROUP BY product_code;
If you really, really, really desperately want 3 rows of data for the product ID 56:3121fefbe6043d6fc12e3b3de2c8fc38, then you have to know ways to generate rows. They're truly painful in the absence of convenient SQL support (so much so, that you'd do better to select a row in PHP with the quantity and then generate the appropriate number of rows in your array in the client-side (PHP) code). I'm going to assume that some variation on these queries will get you the information you want.

sql query selecting one name no matter how many rows it was mentioned in

Basically what I'm trying to do is get the information from column x no matter how many times it was mentioned. means that if I have this kind of table:
x | y | z
------+-------+--------
hello | one | bye
hello | two | goodbye
hi | three | see you
so what I'm trying to do is create a query that would get all of the names that are mentions in the x column without duplicates and put it into a select list.
my goal is that I would have a select list with TWO not THREE options, hello and hi
this is what I have so far which isn't working. hope you guys know the answer to that:
function getList(){
$options="<select id='names' style='margin-right:40px;'>";
$c_id = $_SESSION['id'];
$sql="SELECT * FROM names";
$result=mysql_query($sql);
$options.="<option value='blank'>-- Select something --</option>" ;
while ($row=mysql_fetch_array($result)) {
$name=$row["x"];
$options.="<option value='$name'>$name</option>";
}
$options.= "</SELECT>";
return "$options";
}
Sorry for confusing... i edited my source
You seem to be using only x. So you can just use query:
SELECT DISTINCT x FROM names
if this is your query
$sql="SELECT * FROM names";
$result=mysql_query($sql);
Then
$sql="SELECT DISTINCT x FROM names";
$result=mysql_query($sql);
Change * to x if you want only one column as it is faster

Categories