Indicating checkbox values from MySQL/PHP - php

I have 4 MySQL tables:
properties (these are properties)
id | address | price
1 | 123 St. | 100,000
2 | 456 St. | 200,000
categories (these are categories of amenities for properties)
id | title
1 | Kitchen
2 | Entertainment
items (these are items under the categories above)
id | catid | item
1 | 1 | Stove
2 | 1 | Fridge
3 | 2 | TV
4 | 2 | Couch
propertyamenities (these are the particular amenities for a property)
id | listingid | amenityid
1 | 1 | 3
2 | 1 | 4
I have built a form where the user can select the various amenities for a given property using checkboxes, which inserts from PHP into MySQL tables above.
I now need to allow the user to edit the amenities (using checkboxes) for a given property. The code I am currently using is:
$result = mysqli_query($con,"SELECT DISTINCT a.title AS maincategory, b.item AS smallcategory, b.id as itemid FROM categories a, items b WHERE a.id = b.catid ORDER BY maincategory ASC, smallcategory ASC") or die(mysqli_error($con));
// keep track of previous maincategory
$previous_maincategory = NULL;
while ($row = mysqli_fetch_assoc($result))
{
// if maincategory has changed from previouscategory then display it
if ($previous_maincategory != $row['maincategory']) {
echo '<tr>
<td colspan="2" valign="top"><strong>';
echo $row['maincategory'];
echo '</strong></td>
</tr>';
}
echo "<tr>";
echo "<td>";
echo "<input type='checkbox' name='amenities[]' value='".$row['itemid']."'>".$row['smallcategory'];
echo "</td>";
echo "</tr>";
// record what the previous category was
$previous_maincategory = $row['maincategory'];
}
This displays the categories and the items as checkboxes. I'm not sure how for a given property, to modify this script and have the associated checkboxes "checked". I presume I need to add in the propertyamenities table to the query, and a WHERE clause to indicate which property (e.g.,1) is being edited, but not sure how to add in the third table.
EDIT
I am closer, but it is returning the same item twice.
$result = mysqli_query($con,"SELECT DISTINCT a.title AS maincategory, b.item AS smallcategory, b.id as itemid, c.amenityid as amenity FROM categories a, items b, propertyamenities c WHERE a.id = b.catid and c.listingid = '$id' ORDER BY maincategory ASC, smallcategory ASC") or die(mysqli_error($con));
// keep track of previous maincategory
$previous_maincategory = NULL;
$myprevious_maincategory = NULL;
while ($row = mysqli_fetch_assoc($result))
{
// if maincategory has changed from previouscategory then display it
if ($previous_maincategory != $row['maincategory']) {
echo '<tr>
<td colspan="2" valign="top"><strong>';
echo $row['maincategory'];
echo '</strong></td>
</tr>';
}
echo "<tr>";
echo "<td>";
if ($row['amenity'] == $row['itemid'])
{
echo "<input type='checkbox' name='amenities[]' value='".$row['itemid']."' checked>".$row['smallcategory'];
}
else
{
echo "<input type='checkbox' name='amenities[]' value='".$row['itemid']."'>".$row['smallcategory'];
}
echo "</td>";
echo "</tr>";
// record what the previous category was
$previous_maincategory = $row['maincategory'];
}
?>
EDIT
Screenshot of current state:

Here is a possible solution:
/* Arrays will be used to store the property address and amenity ids */
/* in order to check against undesired duplicate echoing. */
$arr_address = [];
$arr_amenity_ids = [];
/* The four tables are joined here to get the required fields. */
/* Here, let $pid be the id of the property being considered: */
$s = "SELECT a.address as Address, b.title as Amenity, c.item as Item, b.id, c.id FROM properties a JOIN categories b JOIN items c JOIN propertyamenities d ON b.id = c.catid AND a.id = d.listingid AND c.id = d.amenityid AND a.id = '$pid';";
$q = mysqli_query($con,$s);
while(list($address, $amenity, $item, $amenity_id, $item_id) = mysqli_fetch_array($q)){
/* Can have a heading for the property address */
if(!in_array($address, $arr_address)){
echo '<h2>Property Address: '.$address.'</h2>'; $arr_address[] = $address;
}
/* A heading for each amenity once: */
if(!in_array($amenity_id,$arr_amenity_ids)){
echo '<strong>'.$amenity.'</strong>'; $arr_amenity_ids[] = $amenity_id;
}
echo '<br/><input type="checkbox" value="'.$item_id.'"/> '.$item;
}

Related

PHP, MySQL Junction Table displays information incorrectly

My tables are as follows:
person2: personID
validPositions: positionID, positionDesc
personPositions: personID, positionID
I want to be able to display a person with their multiple positions (some may only have one position) on one line. Example: Sierra's Positions: s1, s2
Currently it displays each position they have, however on different lines AND it repeats the last position in the database twice. Example:
Sierra's Positions: S1
Sierra's Positions: S2
Sierra's Positions: S2
$sql = "SELECT * FROM person2";
// LEFT JOIN validTitles ON personTitle.positionID=validTitles.positionID GROUP BY person2.personID";
if ($result = mysqli_query($connection, $sql)) {
// loop through the data
//create 4 columns for the table
$columns=5;
$i = 0;
while($row = mysqli_fetch_array($result))
{
// the % operator gives the remainder of a division of two values
// in this case, 0/4, this tells the table row to jump to a new row
// if there are already 4 columns in one row
if($i % $columns == 0){
//begin table row
echo "<tr>";
} //end if
echo '<td class="staffImage badgeText frameImage displayInLine">
<br>
<strong>'.$row["firstName"].'</strong>
<strong>'.$row["lastName"].'</strong><br>'
.$row["position"].
'<div id="openModal'.$row["personID"].'" class="modalDialog">
<div>
X
<h2>' . $row["firstName"] . " " .
$row["lastName"].'</h2><br>
<img class="floatLeft" src="images/staff/'.$row["imgName"] .'.jpg">
<p><strong>Hire Date: </strong>'.$row["hireDate"].'<br>
<p><strong>Major: </strong>'.$row["major"].'<br>';
//if the field "major2" (Double Major) is not null, display it
if($row["major2"] != NULL)
{
echo ' & '.$row["major2"].'<br>';
}
//if the field "minor" is not null, display it
if($row["minor"] != NULL)
{
echo '<p><strong>Minor: </strong>'.$row["minor"].'<br>';
}
//if the field "concentration" is not null, display it
if($row["concentration"] != NULL)
{
echo '<p><strong>Concentration: </strong>'.$row["concentration"];
}
**$sql2 = "SELECT * FROM personPositions LEFT JOIN validPositions ON personPositions.positionID=validPositions.positionID ";
if ($result2 = mysqli_query($connection, $sql2)) {
// loop through the data
while($row2 = mysqli_fetch_array($result2))
{
echo '<p><strong>Position(s): </strong>'.$row2["positionDesc"];
}//end second while**
} //end second if
'</div>
</div>
</div> ';
echo '</td>';
Any help is greatly appreciated, I am new to PHP and MySQL and unsure what to do!
SAMPLE DATA:
personPositions table:
personID 1 | positionID 11
personID 1 | positionID 22
personID 2 | positionID 22
personID 2 | positionID 55
validPositions table:
positionID 11 | positionDesc S1
positionID 22 | positionDesc S2
positionID 55 | positionDesc S3
Something like this should work for you:
SELECT p.personID, GROUP_CONCAT(DISTINCT positionDesc ORDER BY positionDesc) AS positions
FROM person AS p
LEFT JOIN personPositions AS pp ON p.personID = pp.personID
LEFT JOIN validPositions AS vp ON pp.positionID = vp.positionID
GROUP BY p.personID
Output:
personID | positions
----------+-----------
1 | S1,S2
2 | S2,S3
Demo here

How can i exclude some records from an mysql query based on another query

I need to exclude some records from a table, and show them, then, i need to show the other records, which were excluded.
I got 3 tables:
+----Songs----+ +----Tags----+ +----s_in_tag----+
| id | | id | | id |
| title | | name | | song_id |
+-------------+ +------------+ | tag_id |
+----------------+
In table Songs I store a list of songs, table Tags have a list of tags, and table s_in_tag bind those 2 tables.
Let say i have in Songs: 1, song nr1. In Tags: 1, POP; 2, Rap; 3, Classical. And in s_in_tag: 1, 3, 2.
This means that song nr1 has tag Classical
I want to be able to add/remove tags in my dashboard, but how do i make a right query which will get all song tags, and will show them as a checked checkbox, and then other tags from table Tags as unchecked checkboxes?
I've got this so far:
SELECT * FROM tags
JOIN s_in_tag
ON tags.id = s_in_tag.tag_id
WHERE s_in_tag.song_id = *song id*
AND s_in_tag.tag_id NOT IN (SELECT tags.id FROM tags) GROUP BY tags.id
Im just trying what I found on internet, hope someone can help me there.
Why don't you include them both in the same query?
SELECT t.id, t.name, st.id IS NOT NULL AS is_checked
FROM Tags t
LEFT JOIN s_in_tag st ON t.id = st.tag_id AND st.song_id = [song_id];
Try this:
<?php
// Query
$sql = "SELECT t.id, t.`name` AS tag, IF(st.`id`, 'checked', 'unchecked') AS checkstatus
FROM tags t
LEFT JOIN s_in_tag st ON st.`tag_id` = t.`id`";
$rs = mysql_query($sql);
while ($row = mysql_fetch_assoc($rs)) {
$checked = $row['checkstatus'] ? ' checked="checked" ' : '';
?>
<p><input type="checkbox" <?php print $checked; ?> /> <?php print $row['tag']; ?> </p>
<?php } ?>
I would create two sql queries. One that gets you all tags and the other that gets you all used tags.
$allTags = "SELECT * FROM tags";
$usedTags = "SELECT * FROM s_in_tag;
On php layer you iterate through the $allTags array and on every iteration you look in the $usedTags array and if it contains the current tag you mark it as checked.
foreach($allTags as $key=>$value)
{
if (in_array($value, $usedTags))
{
echo "<input type='checkbox' checked /> ".$value;
}
else
{
echo "<input type='checkbox' /> ".$value;
}
}
The php part is not tested but should work.

Get column value (name) from a Foreign Key reference in PHP

I've got two databases fruit and fruit-prices (for arguement's sake).
In fruit there are two columns id | name
Fruit table
id | name
1 | Apple
2 | Banana
In fruit_prices there are three columns id | fruit_id | price where fruit_id is a FOREIGN KEY reference.
id | fruit_id | price
1 | 1 | £2.00
2 | 2 | £3.00
Now I have a PHP function that will print out a table row and cells with the information from the database but currently if I am printing two fruits out my table looks like this.
Name | Price
1 | £2.00
2 | £3.00
PHP Code:
$query = mysqli_query($conn, "SELECT * FROM fruits ");
while($row = mysqli_fetch_assoc($query)) {
$name = $row['fruit_id']; //for comma separation
$price = $row['price'];
echo "<tr>";
echo "<td>" .$name. "</td>" .
"<td>" .$price. "</td>";
echo "</tr>";
}
Is there an elegant way I can retrieve the name of the fruit (i.e. 1 = Apple, 2 = Banana). Rather than using the unique ID of each fruit.
So then my table will look like this
Name | Price
Apple | £2.00
...
I hope this makes sense? I'm new to RD concepts. This is a very simple example and does not reflect my entire project so I'm just wondering if this is achievable?
This can be done by joining both the tables.Change your sql query with below one.I think it will solve your problem.
"SELECT fruit.name,fruit_prices.price FROM fruit,fruit_prices WHERE fruit_prices.fruit_id = fruit.id";
You would want to use a join and specify the columns you would like to select.
SELECT f.name, fp.price FROM fruit as f
JOIN fruit-prices as fp ON f.id=fp.fruit_id;
It is achievable using JOIN:
SELECT * FROM fruits a JOIN fruits-prices b ON b.fruit_id = a.id
For more friendly column names you can add column aliases and use them further.
You say they are in two databases, but I think it might just be two tables. If so:
select * from fruit f
left outer join fruit-prices fp
on f.id = fp.fruit_id
The left outer join ensures that if a fruit doesn't have a price it will be returned will null as the price. If you don't want that replace it with an inner join.
Use of JOIN does what you need.
"SELECT `p`.`price`, `f`.`name` FROM `fruit_prices` `p`
JOIN `fruits` `f` ON `f`.`id` = `p`.`fruit_id`"
Be wary - use of SELECT * here will lead to an error, as both tables have an id field, and the query will break.
You need a join between the tables,
SELECT f.name, fp.price
FROM fruit f
INNER JOIN fruit_price fp ON f.id = fp.fruit_id
Well, you need to take a look to SQL Joins
query = mysqli_query($conn, "SELECT FRUIT.name,FRUIT_PRICES.price FROM fruits INNER JOIN FRUIT_PRICES ON FRUIT.id = FRUIT_PRICES.fruit.id");
while($row = mysqli_fetch_assoc($query)) {
$name = $row['name']; //for comma separation
$price = $row['price'];
echo "<tr>";
echo "<td>" .$name. "</td>" .
"<td>" .$price. "</td>";
echo "</tr>";
}
What I wrote means : "Select FRUIT.Name,FRUIT_PRICES.price in FRUIT AND FRUIT_PRICES, considering that FRUITS.id is related to FRUIT_PRICES.id_fruit"
Suggestion : You can have a single table viz fruits with 3 columns id, fruit_name, price.
for your table structure :
SELECT fruits.id, name, price
FROM fruits, fruit-prices
WHERE fruit_id=fruits.id;

Compare two tables from MYSQL

I have to compare two tables , then list all of them as check boxes, while matched values should be checked and non matching without checked
//table 1
rid| role_name
1 | school
2 | college
3 | University
//table2
id|rid | category
1 | 1 | uniform
2 | 2 | uniform
match rid from both table where category = 'uniform'
list all and checked the matching rid
$query = "select t1.rid, 'matched' as matching from table1 t1 where t1.rid in (
select rid from table2 where category = 'uniform')
union
select t1.rid ,'notmatched' from table1 t1 where t1.rid not in (
select rid from table2 where category = 'uniform')";
$result = mysqli->query($query);
$fetched = $result->fetch_assoc();
foreach($fetched as $row){
if($row['matching'] = 'matched'){
echo "<input type='checkbox' name='{$row['rid']}' value='' checked='checked' >"; }
else{
echo "<input type='checkbox' name='{$row['rid']}' value='' >"; }
}
SQL DEMO
$query = "select a.* from table1 a, table b where a.rid = b.rid and a.category = b.category";
$result = mysqli->query($query);
$fetched = $result->fetch_assoc();
foreach($fetched as $row){
echo "<input type='checkbox' name='{$row['rid']}' value='' checked > {$row['category']}";
}

How do I display all records from a SQL table and match those records to another table?

I have set the PHP variable $accountnumber to be that of the user who is viewing their profile page. On the page, I have a block with the user's information populated from the database, and I have a list of all products that we have, and I want to put a check mark next to each one that the customer has by assigning a class to it.
Here are my tables:
products
id | name | url | weight
100 p1 p1.html 1
101 p2 p2.html 2
102 p3 p3.html 3
103 p4 p4.html 4
104 p5 p5.html 5
105 p6 p6.html 6
products_accounts
account_number | product_id
0000001 100
0000001 104
0000001 105
0000002 101
0000002 103
0000002 104
0000002 105
0000003 100
0000003 102
I tried a LEFT OUTER JOIN, but was not able to determine if the $accountnumber matched an account_number in the products_accounts table for a specific product_id. The only way that I was able to accomplish this was to add a WHERE statement like this:
WHERE products_acccounts.account_number = '$accountnumber'
It gave the proper class to the product, but only showed the product that they had instead of all.
Here's my code:
$sql ="
SELECT
products.id,
products.name,
products.url,
products_accounts.account_number
FROM
products
LEFT OUTER JOIN
products_accounts
ON
products.id = products_accounts.product_id
";
$sql .="
GROUP BY
products.id
ORDER BY
products.weight
";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo '<span class="'; if($row['account_number'] == '$accountnumber')
{ echo'product_yes">'; } else { echo 'product_no">'; }
echo '' . $row['name'] . '<br /></span>';
}
If a customer has all product except P2 and P5, it SHOULD display like this:
✓P1
P2
✓P3
✓P4
P5
✓P6
It's better to filter out rows using SQL than PHP, like below:
$sql ="
SELECT
p.id,
p.name,
p.url,
pa.account_number
FROM
products p
LEFT OUTER JOIN
products_accounts pa
ON
p.id = pa.product_id
AND
pa.account_number = ".mysql_real_escape_string($accountnumber)."
ORDER BY
p.weight
";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo '<span class="'; if(!is_null($row['account_number']))
{ echo'product_yes">'; } else { echo 'product_no">'; }
echo '' . $row['name'] . '<br /></span>';
}
$getproducts = mysql_query("
SELECT id, name, url
FROM products
ORDER BY weight ASC");
while ($rowproducts = mysql_fetch_assoc($getproducts)) {
$product_id = $rowproduct['id'];
$product_name = $rowproduct['name'];
$product_url = $rowproduct['url'];
$getuserhasproduct = mysql_query("
SELECT DISTINCT product_id
FROM products_accounts
WHERE account_number = $accountnumber
AND product_id = $product_id");
$user_has_product = mysql_num_rows($getuserhasproduct);
if($user_has_product){
$class = "checked";
}
echo "<span class='$class'><a href='$product_url'>$product_name</a></span>";
unset($class);
} // end loop
This might help with performance
$getproducts = mysql_query("SELECT id, name, url,
(SELECT DISTINCT product_id
FROM products_accounts
WHERE account_number = '$accountnumber'
AND product_id = products.id) AS product_count
FROM products
ORDER BY weight ASC");
while ($rowproducts = mysql_fetch_assoc($getproducts)) {
$product_id = $rowproduct['id'];
$product_name = $rowproduct['name'];
$product_url = $rowproduct['url'];
$product_count = $rowproduct['product_count'];
if($product_count > 0){
$class = "checked";
}
echo "<span class='$class'><a href='$product_url'>$product_name</a></span>";
unset($class);
} // end loop
SELECT
products.id,
products.name,
products.url,
products_accounts.account_number
FROM
products
LEFT OUTER JOIN
(SELECT * FROM products_accounts WHERE account_number = $account_number) as products
ON
products.id = products_accounts.product_id
WHERE
";
$sql .="
GROUP BY
products.id
ORDER BY
products.weight
";
i think this is your answer, you need to filter your join table before the join. please check the syntax as i am not that familiar with php.
You're trying to use GROUP BY in a context that doesn't make sense if you want to retrieve all of the records. The GROUP BY clause should only be used if you want to aggregate data (i.e. get the sum, average, etc. of a bunch of records).

Categories