How to remove the same name occurrences in mysql left join? - php

I am using the following query.
SELECT DISTINCT ph.module_head_id,
ph.module_head, pm.module_id,
pm.module_name, pm.module_url
FROM pms_module_header ph
LEFT JOIN pms_module pm
ON ph.module_head_id = pm.module_head_id
Now i am getting the following output
Module_head_id Module_head module_id module_name module_url
1 dashboard Null Null Null
2 Employee 1 Add test.php
2 Employee 2 View test1.php
3 Report 3 Project project.php
3 Report 4 Client client.php
How to remove the same name occurences in module_head
I Want to display the out like these in codeigniter view
dashboard
Employee Add
View
Report Project
Client
I am using array_unique function but its not work.Please help me

Here is the query,
SELECT DISTINCT ph.module_head_id,
ph.module_head, pm.module_id,
pm.module_name, pm.module_url
FROM pms_module_header ph
LEFT JOIN pms_module pm
ON ph.module_head_id = pm.module_head_id
group by ph.module_head_id
Just apply group by on module_head_id, it will work.
EDIT
<table border="1" width="100%">
<tr>
<th>Module head</th>
<th>Module name</th>
</tr>
<?php
$module_head = '';
foreach ($arr as $k => $v) {
echo "<tr>";
echo "<td>";
if ($v['module_head'] == '' || $v['module_head'] != $module_head) {
$module_head = $v['module_head'];
echo $v['module_head'] . "<br/>";
} else {
echo " ";
}
echo "<td>";
echo "<td>" . $v['module_name'] . "</td>";
echo "<tr>";
}
?>
<table>
Manipulate as per your view. It will work.

Related

SQL PHP : How to SELECT and fetch like this?

Hello I'm know how to use basic SQL about select, join, fetch
but don't have idea how fetch like this to my website (see screenshot)
From screenshot It has column room_number too.
<table>
<tr>
<td>room no.</td>
<td>room name</td>
</tr>
<?php
$sql = SELECT * FROM si_room;
$query = $db->query($sql);
while($row = $query->fetch(PDO::FETCH_ASSOC))
{ ?>
<tr>
<td><?php echo ????? ; ?></td>
<td><?php echo ?????; ?></td>
</tr>
<?php } ?>
</table>
UPDATE :
I try with this code
<?php
$sql = "SELECT * FROM si_room";
$querymain = $db->query($sql)->fetchAll(PDO::FETCH_GROUP);
?>
<table>
<tr>
<td>room no.</td>
<td>room_name</td>
</tr>
<?php
foreach ($querymain as $list_id => $list_data)
{
echo "<tr>";
echo "<td> floor ".$list_data[0]['room_floor']."<br>";
foreach ($list_data as $row)
{
echo $row['room_no']."</td>";
echo "<td>".$row['room_name']."</td>";
}
} ?>
</tr>
</table>
but the result is
floor 2
201 | ROOM A
floor 2
202 | ROOM B
floor 3
301 | ROOM E
floor 3
302 | ROOM F
That's not I want.
Luckily you are using PDO which already has this functionality for you, that can do exactly what you want - group the data based on some column.
PDO can group results into the nested arrays, based on the first field selected. So you need to list your list id as the first field in the field list , and then get your rows using fetchAll() with aforementioned fetch mode:
$sql = "select room_floor, room_name, room_no from si_room";
$building = $dbh->query($sql)->fetchAll(PDO::FETCH_GROUP);
and now you get a neat nested array where your rows are grouped by list id!
To make it output neatly you have to use two nested foreach operators
foreach ($building as $floor_no => $rooms)
{
echo $floor_no."\n";
foreach ($rooms as $row)
{
echo $row['room_name']."\n";
}
}

PHP SQL Query - unable to add HTML formatting

I have a database with three tables. A, B and C. Table A has one column: entity_id. Table B has two columns; entity_id, entity_name. Table C has two columns; entity_id, entity_body.
I am trying to use php to create an html table that displays entity_name and entity_body for all entity_id that appear in Table A.
$sql1 = $dbh->prepare('Select B.entity_name, C.entity_body FROM A
INNER JOIN B ON A.entity_id = B.entity_id
INNER JOIN C on A.entity_id = C.entity_id');
$sql1->execute();
while ($row = $sql1->fetchObject()) {
echo '<br><tr><td>';
echo $row->body_value;
echo '</td><td>';
echo $row->title;
echo '</td></tr>';
}
The above query is returning the correct database records: it shows all the relevant rows separated by a line-break.
However, the and HTML tags never seem to be added. The tags are added. All other tags are recognised and work as expected (e.g. p, div etc.).
Is it possible to format the outputs of a query as a table with HTML tags around the cells and the rows?
Apologies if this is obvious - this is my first attempt at using php with a database. Many thanks,
Ben
try
$sql1 = $dbh->prepare('Select B.entity_name, C.entity_body FROM A
INNER JOIN B ON A.entity_id = B.entity_id
INNER JOIN C on A.entity_id = C.entity_id');
$sql1->execute();
echo '<table width="100%">';
while ($row = $sql1->fetch(PDO::FETCH_OBJ)) {
echo '<tr>
<td>';
echo $row->entity_body;
echo ' </td>
<td>';
echo $row->entity_name;
echo '</td>
</tr>';
}
echo '</table>';
Looks like you are missing table tag before ''
//add table tag here.
echo '<table>'; //you can set table style using css as well
while ($row = $sql1->fetchObject()) {
echo '<tr><td>'; // no need to add <br> here
echo $row->body_value;
echo '</td><td>';
echo $row->title;
echo '</td></tr>';
}
//close table tag here
echo '</table>';
Hope this helps!

remove duplicate values in foreach

Hello Developers I have to print a report in my application. I am using codeigniter. I have a table like this in my database.
Report Detail
---------------------------------------------------------------------------
ID Test_ID Description Description_Group Test_Name
---------------------------------------------------------------------------
1 117 value 1 group 1 Test 1
2 117 value 2 group 1 Test 1
3 4 another 1 group 2 Test 2
4 4 another 2 group 2 Test 2
5 4 another 3 group 2 Test 2
I want to print like this
desired print format
-----------------------------------------------
Description
-----------------------------------------------
**Test 1**
group 1
value 1
value 2
**Test 2**
group 2
another 1
another 2
another 3
Here is my Model Codel
public function print_report($Patient_ID, $ID)
{
$query = $this->db->query('select a.ID, a.Description, a.Description_Group, a.Normal_Range, a.Measure_Unit,
b.Result_Value
from tbltestdefault a
inner join tblreportdetail b on a.ID = b.Test_Default_ID
where b.Patient_ID = '.$Patient_ID.' and b.Patient_Test_ID = '.$ID.'');
return $query->result_array();
}
Controller
public function print_report($ID, $Patient_ID, $Test_ID)
{
$data['patient'] = $this->Report_Model->getPatientinfo($Patient_ID);
$data['testname'] = $this->Report_Model->gettestnameonly($Test_ID);
$data['tests'] = $this->Report_Model->print_report($Patient_ID, $ID);
$this->load->view('report_view', $data);
}
and a view to display data
<table class="table table-bordered">
<thead>
<tr>
<th> <h4>Description</h4>
</th>
<th> <h4>Result</h4>
</th>
<th> <h4>Units</h4>
</th>
<th> <h4>Normal Value</h4>
</th>
</tr>
</thead>
<tbody>
<?php foreach($tests as $t): ?>
<tr>
<td>
<?php echo $t['Description_Group']; ?>
<?php echo $t['Description']; ?>
</td>
<td><?php echo $t['Result_Value']; ?></td>
<td><?php echo $t['Measure_Unit']; ?></td>
<td><?php echo $t['Normal_Range']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
man, i think you are taking this site for granted.. i already provided you the main logic.you just need to expand it depending on your additional needs.. btw here's the expanded logic
<?php
$get_title = '';
$get_subtitle = '';
foreach($tests as $t)
{
//if start of new test name
if($get_title != $t['Test_Name'])
{
echo $t['Test_Name'];
//if start of new desc group
if($get_subtitle != $t['Description_Group'])
{
echo $t['Description_Group'];
echo $t['description'];
$get_subtitle = $t['Description_Group'];
}
//if same desc with previous
elseif($get_subtitle == $t['Description_Group'])
{
echo $t['description'];
}
$get_title = $t['Test_Name'];
}
//if same title with previous
elseif($get_title == $t['Test_Name'])
{
//if start of new desc group
if($get_subtitle != $t['Description_Group'])
{
echo $t['Description_Group'];
echo $t['description'];
$get_subtitle = $t['Description_Group'];
}
//if same desc with previous
elseif($get_subtitle == $t['Description_Group'])
{
echo $t['description'];
}
}
}
add this at the last part of your sql query
ORDER BY Test_Name ASC, Description_Group ASC, Description ASC
not sure if this would work, because i haven't tried it.. hit me with some comments if something went wrong..cheers

Creating Categories using database in PHP

Hi I want to create Categories listed which are saved in my database so when user upload his images and he select the category it saves the data in database in Cat column
Now I want to show category in PHP like this
Categories Total
Animals (4)
Celebrations (2)
Locations And Travel (11)
Object or still life (1)
Transportation (9)
Here is my PHP I am succeeded to show Categories names but not total category in each category
<?php
$con=mysqli_connect("localhost","root","123","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"Select Cat from save_data Group By Cat ")
or die(mysql_error());
echo "<table border='1'>
<tr>
<th>Categories</th>
<th>Total</th>
</tr>";
while($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['Cat'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Extend the table cell:
<td colspan="2"></td>
This way it extends over another cell.
Also I notice you are mixing mysqli and mysql:
or die(mysql_error());
Try to use mysqli as objects and \Exceptions instead of errors. It's worth learning about :-)
Update:
I did not understand your question at first. Please provide your schema so we can see your table structure.
Usually you would have 2 tables, one with categories and one with data and join them with a GROUP BY (if an item can be in several categories, you would have a third table like category_has_item!):
SELECT c.category AS cat,
COUNT(i.items) AS num
FROM category c
LEFT JOIN items i
ON c.category_id = i.category_id
GROUP BY c.category
Use LEFT JOIN to display empty categories and JOIN (without LEFT) to avoid empty categories.
Change your table echo:
echo "<td>" . $row['cat'] . "</td><td>(" . $row['num'] . ")</td>";
Update:
If you only have 1 table, I strongly suggest you to read about database normalization.
Update your query:
Select Cat,COUNT(Data) AS num from save_data Group By Cat
Replace Data by your data column
and your echo line:
echo "<td>" . $row['Cat'] . "</td><td>(" . $row['num'] . ")</td>";
try to change your sql query like this
SELECT count(*) AS total_count FROM (SELECT Cat FROM save_data GROUP BY Cat HAVING COUNT(Cat) > 1) AS t

split a string whilst use left join

I have two databases. The first contains a list of upload doucuments and who they are for when uploaded and expiry date. This is stored as numbers representing each grade of person using implode. so column name 'foagrade' has 10,11,12 in row one. The second database is a list of grades and there ID's eg 10 = manager, 11 = HR etc. I am using left join and a basic html table to display a query.
$result = mysqli_query($con,
"SELECT UPLOAD.id, UPLOAD.title, UPLOAD.faoGrade,UPLOAD.faoLocation, UPLOAD.date, UPLOAD.expiry, GRADE.ID, GRADE.GRADE as GR, GRADE.id
FROM UPLOAD
LEFT JOIN GRADE ON
UPLOAD.faoGrade=GRADE.ID
where owner=$user");
echo "<table id='previous'>
<tr>
<th>Title/Document name:</th>
<th>For attention of Grade</th>
<th>For Location</th>
<th>date</th>
<th>Date expires</th>
<th>Delete this briefing</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
$id=$row['id'];
echo "<tr>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['GR'] . "</td>";
echo "<td>" . $row['foaLocation']."</td>";
echo "<td>" . date("D, d M Y ",($row['date']));
echo "<td>" . date("D, d M Y ",($row['expiry']));
echo "<td>delete</td> ";
echo "</tr>";
}
echo "</table>";
The query shows all the details but only shows the first grade stored in the column faograde (MANAGER) not 11 or 12.
How would I explode or split this? So for each number in this column a grade name is shown. i will also have to do the same for column 'faoLocation', but working on one issue at a time.
These tables should be normalized, but with what you have already you can do something like this:
SELECT UPLOAD.id as uploadID,
UPLOAD.title,
UPLOAD.faoLocation,
UPLOAD.date,
UPLOAD.expiry,
GRADE.ID as gradeID1,
GRADE.GRADE as GR,
GRADE.id as gradeID2 FROM UPLOAD, GRADE
WHERE
FIND_IN_SET(gradeID2,UPLOAD.faoGrade)
and UPLOAD.owner=$user;
Update
Here's the SQL Fiddle.
It is a bit confusing that there are multiple columns called id & ID. It's best to give them intuitive names like grade_ID or user_ID. From a normalization standpoint you could be using a relational table instead of the comma separated column (depending on how this data enters the database). Here's a video about normalization.

Categories