Check if there is a value in db with if - php

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>";

Related

Echo rows via JOIN in MySQL/PHP (?)

I wanna be able to echo out if Groupname and Username are connected correctly, where the current userid (saved in a session) is $uid.
I've been sitting for hours trying all kinds of JOINs and the closest I've gotten is having it output 1/? members for each team, but not all of them.
EDIT:
$uid = $_SESSION['uid'];
$sql = "SELECT * FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user
INNER JOIN usergroup ON user.userid=usergroup.userid
WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
$row2 = mysqli_fetch_array($result2);
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
Thing is, that it kinda works well, except that it doesn't print all the groupmembers names out, it prints out just one. Which one seems to depend on the order in the table.
You did not have a loop on the second query's resultset. However, it is not needed to have a second SQL query. Just do it in one go; SQL was designed for that.
Also, you'll have much simpler code:
$uid = $_SESSION['uid'];
// Select everything you need in one go (join user table as well)
$sql = "SELECT group.group_id, group.groupname, user.username
FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
INNER JOIN user ON user.userid=usergroup.userid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
// Don't need to call mysqli_num_rows if you continue like this:
while($row = mysqli_fetch_array($result)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
Maybe you want to echo some <tr> and </tr> tags, or you"ll have everything in one row, like:
echo "<tr><td>".$row['groupname']."</td>"
."<td>".$row['username']."</td>"
."<td>".$row['groupid']."</td></tr>";
There you go: (you were missing nested while loop)
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user INNER JOIN usergroup ON user.userid=usergroup.userid WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
if(mysqli_num_rows($result2)>0) {
while($row2 = mysqli_fetch_array($result2)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
}
}
Side note: You could achieve the same results with just one SQL query, something like:
SELECT
*
FROM
usergroup ug
INNER JOIN
user u ON ug.userid = u.userid
GROUP BY
ug.id
and then in PHP (pseudo code just, do not copy-n-paste)
while($row => mysqli_fetch_array($result)) {
if (!isset($groupsWithUsers[$row['groupid']['users'])) {
$groupsWithUsers[$row['groupid']['users'] = array()
}
$groupsWithUsers[$row['groupid']['users'][$row['userid']] = $row;
}

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

Display data once if same

With this code:
$query = "select users.id_user, users.full_name, users.rights, users.group, group.id, group.name
from users
inner join group
on users.group=group.id
where users.rights= 2";
// connection code
while ($re = mysql_fetch_array($res))
{
$id_user = $re["id_user"];
$id_group = $re["id"];
$full_name= $re["full_name"];
$group_name= $re["name"];
echo "<div>";
echo "<p><strong>$group_name</strong></p>";
echo "$full_name<br />";
echo "</div>";
}
?>
I get this:
Group1
User1
Group1
User2
Group2
User3
Group2
User4
and I need it like this:
Group1
User1
User2
Group2
User3
User4
How to show group name just once?
Tweak your query that you use the database power to give you the information you need.
select
usergroup.name
, GROUP_CONCAT(user.name SEPARATOR '<br />') 'users'
from
user
inner join
usergroup
on
user.usergroup_id = usergroup.id
where
user.rights = 2
group by
usergroup.id
see demo http://sqlfiddle.com/#!2/0d104/1 in your php you can use $row['users']
You may use associative arrays for this task. For example, make an array $groups, and in your while loop do something like
$groups[$re["name"]]["full_name"][] = $re["full_name"];
Then, when you display your html loop through $groups and inside it loop though full names.
This is what I came up with:
$query = "SELECT users.id_user, users.full_name, users.rights, users.group, group.id, group.name
FROM users
INNER JOIN group
ON users.group=group.id
WHERE users.rights=2
ORDER BY group.name ASC";
// connection code
$group_name = '';
while ($re = mysql_fetch_array($res))
{
if( $group_name === '' )
{
$group_name = $re["name"];
echo "<div>";
echo "<p><strong>$group_name</strong></p>";
}
elseif( $group_name !== $re["name"] )
{
$group_name = $re["name"];
echo "</div>";
echo "<div>";
echo "<p><strong>$group_name</strong></p>";
}
$id_user = $re["id_user"];
$id_group = $re["id"];
$full_name= $re["full_name"];
echo "$full_name<br />";
}
?>
It's basically ordering the result by the group names, and while it iterates, the group name is being checked. If it's the same, only the name is printed, if it differs, the div is closed, a new one is made and the new group title is echoed.

Adding Option Group to Query

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.

Echoing users by group name in PHP

What I want to do is click a name of a group(every group what I create other than poweruser and admin groups) and that will echo all of the users in that group from the database. I have figured out the code so far but now my problem is how will I print it all out when clicking the name of the group?
My code so far is:
<h3>Groups</h3>
<?php
include('db.php');
if (isset($_GET["groupID"])) {
$sql="SELECT `group`.*, `user`.* FROM `user` inner join `group` on group.groupID=user.groupID where group.groupID= " . mysql_real_escape_string($_GET["groupID"]) ;
} else {
$sql="SELECT * FROM `group` WHERE groupName <> 'admin' AND groupName <> 'poweruser'" ;
}
$result=mysql_query($sql,$connection);
while($line=mysql_fetch_array($result)){
echo "<a href='index.php?page=groups&group=".$line['groupID']."'>".$line['groupName'].'</a><br />';
}
mysql_free_result($result);
mysql_close($connection);
?>
On top of the $_GET["group"] issue, it doesn't look like you're printing out the users anywhere.
You should move the output into the if block, and create new output for the first condition.
<?php
include('db.php');
if (isset($_GET["groupID"])) {
$sql="SELECT `group`.*, `user`.* FROM `user` inner join `group` on group.groupID=user.groupID where group.groupID= " . mysql_real_escape_string($_GET["groupID"]) ;
$result=mysql_query($sql,$connection);
//Output users after Group Selected
//Could be placed outside the if block to allow user to select a different group
echo("<h3>Users</h3>");
while($line=mysql_fetch_array($result)){
//echo out the user data here
}
} else {
$sql="SELECT * FROM `group` WHERE groupName <> 'admin' AND groupName <> 'poweruser'" ;
$result=mysql_query($sql,$connection);
//Output to let user select group.
echo("<h3>Groups</h3>");
while($line=mysql_fetch_array($result)){
echo "<a href='index.php?page=groups&group=".$line['groupID']."'>".$line['groupName'].'</a><br />';
}
}
mysql_free_result($result);
mysql_close($connection);
?>
if (isset($_GET["groupID"])) {
should that not be
if (isset($_GET["group"])) {
also change the $_GET["groupID"] to $_GET["group"] in ur $sql query
The following code is an example on how you could it. Just put it below the code you already have:
if ($_GET['page'] == 'groups'):
$groupID = $_GET['groupID'];
$sql = "SELECT * FROM users WHERE groupID = '$groupID'";
$res = mysql_query($sql); //MySQL query
$count = mysql_num_rows($res); //This counts our results
if($count != 0): //This makes sure we have at least 1 result
while($user = mysql_fetch_assoc($res)):
echo $user['name'];
endwhile;
endif;
endif;
Add Peter Stuart's code in your file and change
<a href='index.php?page ... > to <a href='groups.php?page ... >

Categories