SQL PHP : How to SELECT and fetch like this? - php

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

Related

php table <th> and <td> from Database Selected but they are not Matching in the right indexing position

all Developers.
I am developing School Management System, in the Database, I have two tables one is For Subjects, and the other one is designed for obtained marks of the Subjects and it is called scores.
So I am trying to fetch subject Names as Table Head
I have another Query below this query and I am trying to fetch from scores as table data .
At this point, I failed to match the subject name and its score from the scores table.
Here is my code:
<table class="table table-striped table-bordered">
<head>
<tr>
<?php
// Query for Subject Names
$view_subject = $config->prepare("SELECT * FROM subjects");
$view_subject->execute();
while($row = $view_subject->fetch()){
$sub_name = htmlspecialchars($row['sub_name']);
?>
<th class="text-center"style="background-color:#395C7F;color:#fff;"><?php echo $sub_name;?></th>
<?php } ?>
</tr>
</thead>
<body>
<?php
// Query for Subject Scores
$view_scores = $config->prepare("SELECT * FROM scores INNER JOIN subjects ON scores.score_sub_id = subjects.sub_id WHERE scores.std_rand = :random_id ORDER BY scores.score_sub_id ASC");
$view_scores->execute(['random_id' => $rand_ID]);
while($row = $view_scores->fetch()){
$score_id = htmlspecialchars($row['score_id']);
$score_sub_id = htmlspecialchars($row['score_sub_id']);
$score_mid_amount = htmlspecialchars($row['score_mid_amount']);
$score_final_amount = htmlspecialchars($row['score_final_amount']);
?>
<tr>
<td class="text-black" data-title="Subject"><?php echo $score_mid_amount;?></td>
</tr>
<?php } ?>
</tbody>
</table>
Database images:
1- Subjects table
2- Scores table
** Browser UI **
On your second loop you have entered '<tr>' wrapping each '<td>' that means that each one arrives at a different line , '<td>'s should be as much as there are '<th>' for each line.... so :
<?php
// Query for Subject Scores
$view_scores = $config->prepare("SELECT * FROM scores INNER JOIN subjects ON scores.score_sub_id = subjects.sub_id WHERE scores.std_rand = :random_id ORDER BY scores.score_sub_id ASC");
$view_scores->execute(['random_id' => $rand_ID]);
?>
<tr>
<?php
while($row = $view_scores->fetch()){
$score_id = htmlspecialchars($row['score_id']);
$score_sub_id = htmlspecialchars($row['score_sub_id']);
$score_mid_amount = htmlspecialchars($row['score_mid_amount']);
$score_final_amount = htmlspecialchars($row['score_final_amount']);
?>
<td class="text-black" data-title="Subject"><?php echo $score_mid_amount;?></td>
<?php } ?>
</tr>
</tbody>
</table>
This should fix your table but it will only create one line! if you have more than one line you will need to add another loop to wrap this one and it will create the new '<tr>' outside the inner loop.
BTW: I assume that the 2nd while loop is exactly long as the first one... since you are supposed to have the same amount of <td> per line per <th> if it's not in the same length or not sorted the same way you will have an issue... which can be resolved either by adjusting your SELECT or creating an array with ids and injecting to it the data from the second loop according to the keys brought in the first.

PHP - SUM number according to item name

Am new in PHP, I need help in my scripts since I don't get preferred answer.
I have a "bills" table which store information's of sales items. as folows
id | gid | drinks | no_drinks | servicetime | date
1 2 Orange 4 1 2018-08-16
2 2 Orange 2 1 2018-08-16
3 2 Orange 3 1 2018-08-16
Below file (BillsController.php) query gid, servicetime and date, and the query is equal to true.
BillsController.php
$bi = Barz::whereRaw('gid=? and servicetime=? and date=?', array($gid, $t,date('Y-m-d')))->get();
return View::make('bills.show', compact('bi'));
Below is "show.php" file which display the information's from Database. I will just shows you few things in it.
<?php
$foods = array();
foreach($bi as $row){
$foods[] = $row->drinks;
$idadi[] = $row->no_drinks;
$unique = array_keys(array_count_values($foods));
$l = count($unique);
}
$newarr = array();
foreach ($unique as $key => $value) {
array_push($newarr, $value);
}
?>
<table class="table table-bordered" id="gt">
<tr style="background-color: #f5f5f5">
<th>Drink</th>
<th>Qty...sx</th>
<th>Time</th>
<th>#cost</th>
<th>Total#</th>
<th>
<select class="form-control active" id="tserv">
<option value="{{$row->servicetime}}">{{Bill::tm($row->servicetime)}}</option>
<select>
</th>
</tr>
<?php $total = 0; ?>
#for($i=0; $i < $l; $i++)
<tr>
<td>{{$newarr[$i]}}</td>
<td>{{$idadi[$i]}}</td> // Only problem is here
<td>{{Bill::appears($newarr[$i], $foods)}}</td>
<td>{{Bar::where('name', $newarr[$i])->first()->cost}} /=</td>
<td>{{($idadi[$i])*(Bar::where('name', $unique[$i])->first()->cost)}}/= </td>
</tr>
<?php $total = $total + (($idadi[$i])*(Bar::where('name', $newarr[$i])->first()->cost)); ?>
#endfor
<tr style="background-color: #f5f5f5">
<td ></td>
<td ></td>
<td></td>
<td><b>Total</b></td>
<td id="ttl">
{{$total}} /=
</td>
</tr>
When I run above query, I get 4 from ("{{$idadi[$i]}}"), which means it take only first row, and the rest is not selected. I want it to do like this (4+2+3) = 9.
To add columns together;
SELECT col1, col2, col3, (col1+col2+col3) AS Total FROM
To add rows together, use the SUM()
Aggregate below;
SELECT userid, SUM(col1) AS col1_total, SUM(col2) AS col2_total FROM table GROUP BY userid
Try this out :
select SUM(no_drinks) no_drinks from table_name GROUP BY drinks

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

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.

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

Display MySQL table ( number of rows are not same ) in PHP

I have one MySQL table and it has two columns -
I want to display in my site like this -
I can easily take the table name Boy | Girl . But when i try to display the table I get like this -
I am just showing one example here. There may be 50 boys and 10 girls.. So I need help.
After displaying the heading
while($row_type = mysql_fetch_array($type))
{
$type_name = $row_type['type_name']; //Boy (or) Girl taking from another table
$type_name = Database::getInstance()->query("SELECT * FROM details WHERE type='type_name'");
echo "<tr>";
while($row_name = mysql_fetch_array($type_name))
{
echo "<td>$row_name[type_name]</td>"; //Displaying the names
}
echo "</tr>";
}
So many views but not getting any answer. Please help guys. Please catch my mistake.
Try with two queries.
Make an array for each category(Male & Female)
It Works.
$maleQuery = mysql_query("SELECT * FROM table WHERE category='male'");
$femaleQuery = mysql_query("SELECT * FROM table WHERE category='female'");
while(($row = mysql_fetch_assoc($maleQuery))) {
$males[] = $row['name'];
}
while(($row = mysql_fetch_assoc($femaleQuery))) {
$females[] = $row['name'];
}
$number_of_rows = max(sizeof($males),sizeof($females));
echo "<table border='1'>";
echo "<tr><td>Male</td><td>Female</td></tr>";
for($i=0;$i<$number_of_rows;$i++)
{
echo "<tr><td>".#$males[$i]."</td><td>".#$females[$i]."</td></tr>";
}
Try this query 100% working but set php code.
SELECT IFNULL(c.Boy,'')AS Boy,IFNULL(c.Girl,'')AS Girl FROM
(SELECT x.name,CASE WHEN (x.category = 'boy') THEN x.name END AS Boy,CASE WHEN (x.category = 'girl') THEN x.name END AS Girl FROM (SELECT * FROM tablename) X)c
Is your problem to do with the creation of the table using PHP or is it related to the SQL query itself?
If it is the creation of the table then I suggest you use two tables embedded in a single table like this. That way you can build the first table using one SQL query, then build the second table using a second query, then display the table and girls and boys will appear side by side regardless of how many entries on each side. Your code would look a bit like this:
echo "<table>
<tr>
<td>
<table>
<tr><th>Boy</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Boy'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
<td>
<table>
<tr><th>Girl</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = 'Girl'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
</tr>
</table>";
If you need to cater for more categories, do an initial search to determine the distinct categories, then put the section of code above that creates the inner table in a loop.
eg. in pseudo code:
echo the outer table <table><tr>
SELECT DISTINCT Category FROM details
while row1=get next category
$cat = row1[0];
echo "<td>
<table>
<tr><th>".$cat."</th></tr>";
$table = mysql_query("SELECT Name FROM details WHERE Category = '".$cat."'") or die(mysql_error());
while($row = mysql_fetch_row($table))
echo "<tr><td>".$row[0]."</td>";
echo "</table>
</td>
echo the </tr></table> to close the outer table

Categories