Compare two tables from MYSQL - php

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']}";
}

Related

Indicating checkbox values from MySQL/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;
}

Mysql query array

I have two tables:
1 - hotels[id,name,extras] ( name of hotels with column extras which I've select for each one)
2 - extras[id,name] ( here's the extras of hotel like wifi,tv,swim... )
$name = $_GET['name'];
$hotels_q = mysql_query("SELECT * FROM `hotels` WHERE `name`='$name'") or die (mysql_error());
$hotels_row = mysql_fetch_array($hotels_q);
$id = $hotels_row['id'];
$extras = explode(",", $hotels_row['extras']);
$ekstras_q = mysql_query("SELECT * FROM `extras` order by id") or die(mysql_error());
While($ekstras_row = mysql_fetch_array($ekstri_q)){
$eid = $ekstras_row['id'];
$ename = $ekstri_row ['name'];
echo '<ul><li><input type="checkbox" name="extras['.$eid.'][]" value="'.$ename.'"';
if (in_array($eid, $ekstras)) echo'checked';
echo'/>'.$ename.'</li></ul>';
Problem is here extras_q displays all entries with checked ones from table, but I want only to display only checked items!
Since you're storing your extra IDs in one column as a comma separated string, I think you should be able to do this by not exploding that value, and then using the CSV string as an IN criteria in your second query.
//...
$extras = $hotels_row['extras']; // don't explode
// Use IN with the $extras CSV here
$ekstras_q = mysql_query("SELECT * FROM `extras`
WHERE id IN ($extras) ORDER BY id") or die(mysql_error());
If you are able to modify your database, you can instead create a many-to-many relationship between hotels and extras by adding a table to join those two items together instead of using a CSV column as you currently are. This can make it easier to write queries to select the related records.
If you add a third table hotel_extras with columns hotel_id and extra_id, you can insert one row for each extra that each hotel has. For example, if the hotel with id 1 has several different extras, its entries in that table would look like this:
table: hotel_extras
_______________________
| hotel_id | extra_id |
=======================
| 1 | 1 |
| 1 | 3 |
| 1 | 4 |
-----------------------
Here is an example using PDO of how you could query data from a setup like that:
$sql = "SELECT e.id, e.name
FROM hotels h
INNER JOIN hotel_extras he ON h.id = he.hotel_id
INNER JOIN extras e ON he.extra_id = e.id
WHERE h.`name` = ?";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(1, $_GET['name']);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$eid = $row['id'];
$ename = $row['name'];
'<li><input type="checkbox" name="extras['.$eid.'][]" value="'.$ename.'" checked/>'.$ename.'</li>';
}

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;

Mysql reducing number of queries

I have 3 columns in table1: book, key and value.
| book | key | value |
------------------------------
| 1 | author | a |
| 1 | editor | b |
| 1 | book | c |
Instead of runnuing three queries
$data = mysql_query("
SELECT * FROM table1 WHERE book = '1' AND key = 'author'
") or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$value1 = $info['value'];
}
Then repeat this for editor and book.
$value1 $value2 $value3 are inserted in different places on page
Could I do this with one query?
Yes. If there are no other entries with "book = 1" you just query
SELECT * FROM table1 WHERE book = '1'
If there are more entries you can use this query:
SELECT * FROM table1 WHERE book = '1' AND key IN('author','editor','book')
And then create an assoc array:
while($info = mysqli_fetch_assoc( $data ))
{
$value[$info['key']] = $info['value'];
}
...
echo "the book {$value['book']} was written by {$value['author']}";
for create a $value array you have to use this :
$value[] = $info['value'];
instead of this :
$value1 = $info['value'];
Also you can use this code :
$value[]["key"] = $info['key'];
$value[]["value"] = $info['value'];
And for example you can call first row's value with $value[0]["value"]
If you want the values in a single record try this:
SELECT `t1`.`value` AS `value1`, `t2`.`value` AS `value2`, `t3`.`value` AS `value3`
FROM
`table1` AS `t1` CROSS JOIN
`table1` AS `t2` CROSS JOIN
`table1` AS `t3`
WHERE
(`t1`.`book` = 1) AND (`t1`.`key` = 'author')
AND (`t2`.`book` = 1) AND (`t2`.`key` = 'editor')
AND (`t3`.`book` = 1) AND (`t3`.`key` = 'book');

Categories