Adding Option Group to Query - php

I am trying to add an Option Group to this select box. I am getting the rows and the count of the number of options in the record set. I can either get the count or set the group. I have yet to do both!
<select name="DETAILS">
<?php
include("config.php");
$sql = "SELECT tblDetails.DetailType AS type, CONCAT(tblDetails.DetailName,' (', Count(tblLocDet.DetailID),')') AS DetailName
FROM tblLocations INNER JOIN (tblLocDet INNER JOIN tblDetails ON tblLocDet.DetailID = tblDetails.DetailID) ON tblLocations.LocationID = tblLocDet.LocationID
GROUP BY tblDetails.DetailType, tblDetails.DetailName, tblLocations.CityID, tblLocations.AreaID, tblLocations.CuisineID
HAVING (((tblLocations.CityID)=16) AND ((tblLocations.AreaID)=131) AND ((tblLocations.CuisineID)=3));";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<optgroup label='{$row['type']}'>";
$DetailNames = explode('|', $row['DetailName']);
foreach($DetailNames as $DetailName) {
echo "<option value='".$DetailName."'>".$DetailName."</option>";
}
echo "</optgroup>";
}
?>
</select>
Help is appreciated.

Related

Check if there is a value in db with if

I have to check if a value is present in two tables, through a left join, if there is a relationship write yes, otherwise no
every time I associate an evidence (tev_Evidenze) to the structure (tev_Tipi_accreditamento) the query should tell me for that structure there is evidence, only now at structure n6. no evidence is present and anyway I answer yes
code:
<?php
$CONTROLLA = mysqli_query($riskmanagement,
"SELECT * FROM tev_Tipi_accreditamento LEFT JOIN tev_Evidenze
ON tev_Tipi_accreditamento. ID_tipo_acc = tev_Evidenze.id_tipo_accreditamento
WHERE tev_Tipi_accreditamento.id_struttura = tev_Evidenze.id_struttura GROUP BY tev_Evidenze.id_struttura");
$EVIDENZE=mysqli_num_rows($CONTROLLA);
if($EVIDENZE==0) {
echo "SI";
}else{
echo "no";
}
?>
The cycle is correct I am sure that in the db, there are no values ​​present in both tables but my if does not seem to work
NOTE:
<?php
$query_string = "SELECT * FROM tev_Tipi_accreditamento LEFT JOIN tev_Evidenze
ON tev_Tipi_accreditamento. ID_tipo_acc = tev_Evidenze.id_tipo_accreditamento
WHERE tev_Tipi_accreditamento.id_struttura = tev_Evidenze.id_struttura GROUP BY tev_Evidenze.id_struttura";
$query = mysqli_query($riskmanagement, $query_string);
?>
<?php
while($row = mysqli_fetch_assoc($query)){ ?>
<?php echo $row['id_struttura'] ;
if($query_string==0) {
echo "SI";
}else{
echo "no";
}?>
<?php } ?>
You're counting ALL the matches, not the number of matches for each structure. You can use the following:
SELECT s.id_struttura, IF(COUNT(e.id_struttura) > 0, 'Yes', 'No') AS matches
FROM tev_Tipi_accreditamento AS s
LEFT JOIN tev_Evidenze AS e ON s.id_struttura = e.id_struttura AND s.ID_tipo_acc = e.id_tipo_accreditamento
GROUP BY s.id_struttura
This will return a table like:
1 Yes
2 No
3 No
4 Yes
for each structure ID.
DEMO
You can show the result with:
$CONTROLLA = mysqli_query($riskmanagement, "
SELECT s.id_struttura, IF(COUNT(e.id_struttura) > 0, 'Yes', 'No') AS matches
FROM tev_Tipi_accreditamento AS s
LEFT JOIN tev_Evidenze AS e ON s.id_struttura = e.id_struttura AND s.ID_tipo_acc = e.id_tipo_accreditamento
GROUP BY s.id_struttura") or die(mysqli_error($riskmanagement));
echo "<table>";
while ($row = mysqli_fetch_assoc($CONTROLLA)) {
echo "<tr><td>{$row['id_struttura']}</td><td>{$row['matches']}</td>
}
echo "</table>";

Select distinct in SQL?

The select distinct not working and the count(*) is not selecting the number of grouped rows but it is selecting the duplicate msg_contents.Please help..
I wanted to select distinct username and the number of duplicate usernames.
<?php
require_once"cnc.php";
$sort = "SELECT hate_p FROM hate_t";
$qry = mysql_query($sort);
while($fet = mysql_fetch_assoc($qry)) {
if($fet == 0) {
echo "No Entries";
} else {
$sql = mysql_query("
SELECT DISTINCT
username,
msg_content,
COUNT(*) c
FROM messages
WHERE msg_content LIKE '%".$fet['hate_p']."%'
GROUP BY username HAVING c>0"
);
while($messages = mysql_fetch_assoc($sql)) {
?>
<tr>
<td><?php echo $messages['username'];?></td>
<td><?php echo $messages['c'];?></td>
</tr>
<?php
}
}
}
?>
you don't need distinct in this case, you can use group by only, distinct get all rows with distinct all columns you select (username,meg_content,count):
SELECT username,msg_content,COUNT(*) c
FROM messages WHERE msg_content LIKE '%".$fet['hate_p']."%'
GROUP BY username,msg_content
HAVING c>0
remove msg_content from distinct? you already have it. and #gouda is right, you probably don't need the distinct at all.

Displaying name from an inner joined table?

I've got two tables, one called category, which has the rows id and name, and another called placecategory, which has the tables id, place_id and category_id. I need to inner join these two to echo out the names of the categories where the placecategory.place_id is equal to a $GET[ID].
I've got this so far, but it echo's out nothing.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name FROM category
INNER JOIN placecategory
ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id.'';
$result = mysqli_query($dbc,$qry);
while ($row = mysqli_fetch_array($result))
{
echo ''.$row['name'].'';
};
?>
This wont fix your query, but it will display the error generated by the incorrect query. Its a start.
I cannot solve the query issue without a better understanding of your schema.
<?php
include('includes/connectdb.php');
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$qry = 'SELECT id, name
FROM category
INNER JOIN placecategory ON category.id = placecategory.category_id
WHERE placecategory.place_id = '.$id;
$result = mysqli_query($dbc,$qry);
// test the status before continuing
if ( ! $result ) {
echo mysqli_error($dbc);
exit;
}
while ($row = mysqli_fetch_array($result))
{
echo $row['name'];
}
?>

Get result of mysql_query inside while of mysql_fetch_array

I am using a code something like below to get data from the second table by matching the id of first table. Code is working well, but I know it slow down the performance, I am a new bee. Please help me to do the same by an easy and correct way.
<?php
$result1 = mysql_query("SELECT * FROM table1 ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ))
{
$tab1_id = $row1['tab1_id'];
echo $row['tab1_col1'] . "-";
$result2 = mysql_query("SELECT * FROM table2 WHERE tab2_col1='$tab1_id' ") or die(mysql_error());
while( $row2 = mysql_fetch_array( $result2 ))
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
}
?>
You can join the two tables and process the result in a single loop. You will need some extra logic to check if the id of table1 changes, because you'll only want to output this value when there's a different id:
<?php
// Join the tables and make sure to order by the id of table1.
$result1 = mysql_query("
SELECT
*
FROM
table1 t1
LEFT JOIN table2 t2 ON t2.col1 = t1.id
ORDER BY
t1.id") or die(mysql_error());
// A variable to remember the previous id on each iteration.
$previous_tab1_id = null;
while($row = mysql_fetch_array( $result1 ))
{
$tab1_id = $row['tab1_id'];
// Only output the 'header' if there is a different id for table1.
if ($tab1_id !== $previous_tab1_id)
{
$previous_tab1_id = $tab1_id;
echo $row['tab1_col1'] . "-";
}
// Only output details if there are details. There will still be a record
// for table1 if there are no details in table2, because of the LEFT JOIN
// If you don't want that, you can use INNER JOIN instead, and you won't need
// the 'if' below.
if ($row['tab2_col1'] !== null) {
echo $row['tab2_col2'] . "-";
echo $row['tab2_col3'] . "</br>";
}
}
Instead of having 2 while loops, what you can do is join the 2 tables and then iterate over the result.
If you're not sure what join is look here: https://dev.mysql.com/doc/refman/5.1/de/join.html
Also here is a fairly simple query written using join: Join Query Example
You can use this. One relation with two tables:
<?php
$result1 = mysql_query("SELECT tab2_col2, tab2_col3 FROM table1, table2 where tab2_col1 = tab1_id ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ),)
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
?>
Like Sushant said, it would be better to use one JOIN or simpler something like that:
SELECT * FROM table1, table2 WHERE `table1`.`id` = `table2`.`id

Keeping lastly selected value from a dropdownlist after button click

Just like the title says i'm having difficulties in achieving it.
Here's my dropdownlist:
<?php
$query = "SELECT data, rel_id FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]' group by data";
$result = mysql_query ($query);
echo "<select name=data value=''>Data</option>";
while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[data] name=\"blabla\">$nt[data]</option>";
}
echo "</select>";
?>
Here's the buttonclick:
<?php
if(isset($_POST['Submit']))
{
$query = "SELECT SUM(suma), paskirtis FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]' AND data ='".$_POST['data']."' group by paskirtis";
$result = mysql_query ($query);
echo "<tr><td>Paskirtis:</td><td>Biudzetas:</td><td>Isleista:</td><td>Likutis:</td></tr>";
while($nt=mysql_fetch_array($result)){
if($nt['SUM(suma)'] != null){
$suma = $nt['SUM(suma)'];
}
echo "<tr><td>$nt[paskirtis]</td>
<td><input type=\"text\" name=\"isleista[]\" value=\"Skiriamų pinigų kiekis...\" method=\"post\"></td><td>".$suma." Lt</td><td>--</td></tr> <br>";
}
}
?>
After I press it, it retrieves the data I want from the date I've chosen from the drop down list and also reset whole drop down list showing the first value of the dates from sql database, not the one I selected. If anyone knows how to keep the selected value in the list any help is greatly appriciated!
Try this, you need to place select="selected" in the while loop. See below code how I placed the $selected
<?php
$query = "SELECT data, rel_id FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]' group by data";
$result = mysql_query ($query);
echo "<select name=data value=''>Data</option>";
while($nt=mysql_fetch_array($result)){
$selected = ($_POST['blabla'] == $nt[data])?'selected="selected"':NULL;
echo "<option value=$nt[data] name=\"blabla\" $selected >$nt[data]</option>";
}
echo "</select>";
?>

Categories