MySQL query to group results - php

I'm trying to do a multi table query and contain the results to records in a specific table. I'm sure that's not very clear, so here are the tables with relevant fields:
waitingroom
+----------------+-------------+
| waitingroom_pk | waitingroom |
+----------------+-------------+
| 1 | PATH2201 |
+----------------+-------------+
| 2 | PATH2202 |
+----------------+-------------+
waitingroom_case_lookup
+----------------------------+----------------+---------+
| waitingroom_case_lookup_pk | waitingroom_fk | case_fk |
+----------------------------+----------------+---------+
| 1 | 1 | 1 |
+----------------------------+----------------+---------+
| 2 | 1 | 2 |
+----------------------------+----------------+---------+
| 3 | 2 | 3 |
+----------------------------+----------------+---------+
vcase
+---------+------------+------------+
| case_pk | case_title | patient_fk |
+---------+------------+------------+
| 1 | Case One | 1 |
+---------+------------+------------+
| 2 | Case Two | 2 |
+---------+------------+------------+
| 3 | Case Three | 3 |
+---------+------------+------------+
patient
+------------+------------+-----------+---------+
| patient_pk | first_name | last_name | case_fk |
+------------+------------+-----------+---------+
| 1 | John | Smith | 1 |
+------------+------------+-----------+---------+
| 2 | Will | Jones | 2 |
+------------+------------+-----------+---------+
| 3 | Mary | Ryan | 3 |
+------------+------------+-----------+---------+
The query that I'm using is:
SELECT * FROM
waitingroom, waitingroom_case_lookup, vcase, patient
WHERE vcase.patient_fk = patient.patient_pk
AND waitingroom.waitingroom_pk = waitingroom_case_lookup.waitingroom_fk
AND vcase.case_pk = waitingroom_case_lookup.case_fk
AND vcase.active = 'y'
AND vcase.case_pk NOT IN (SELECT case_fk FROM user_case_lookup WHERE user_id = '$user_id')
This query returns results showing three waitingrooms instead of two, presumably because there are three records in table waitingroom_case_lookup. What I want is to group the vcase data according to the waitingrooms using waitingroom_case_lookup.
As for printing the results, the waitingrooms show as JQuery accordions and I have a nested foreach loop which shows the case data in each waitingroom accordion. The problem is, as I said before, that three waiting rooms show, not two. The second and third waitingroom accordions appear OK, with case_pk one and two showing in the second accordion and case_pk three showing in the third. The first accordion shows case_pk one as well, and this accordion shouldn't show.
The results are printed using the following code:
<?php
$waitingRooms = array();
while ($row_waitingrooms = mysql_fetch_assoc($result_waitingrooms)){
if($row_waitingrooms['gender'] == 'f'){
$gender = 'Female';
} else if ($row_waitingrooms['gender'] == 'm'){
$gender = 'Male';
}
$waitingRoomPK = $row_waitingrooms['waitingroom_pk'];
if (!isset($waitingRooms[$waitingRoomPK])) {
$waitingRooms[$waitingRoomPK] = array(
'waitingroom_pk' => $waitingRoomPK,
'waitingroom' => $row_waitingrooms['waitingroom'],
'cases' => array()
);
}
$waitingRooms[$waitingRoomPK]['cases'][] = array(
'case_pk' => $row_waitingrooms['case_pk'],
'patient_icon' => $row_waitingrooms['patient_icon'],
'first_name' => $row_waitingrooms['first_name'],
'last_name' => $row_waitingrooms['last_name'],
'age' => $row_waitingrooms['age'],
'gender' => $gender,
'presenting_complaint' => $row_waitingrooms['presenting_complaint']
);
echo "<h6>" . $row_waitingrooms['waitingroom'] . "</h6><div><p><span class='text'>";
foreach ($waitingRooms[$waitingRoomPK]['cases'] as $wcase){
echo "<table width='100%'><tr><td><input name='case' id='case_" . $wcase['case_pk'] . "' type='radio' value='" . $wcase['case_pk'] . "' /></td><td width='65' align='left'><div class='case_list'><img src='images/case_icons/" . $wcase['patient_icon'] . "' width='44' height='45' /></div></td><td width='350' align='left'>" . $wcase['first_name'] . ' ' . $wcase['last_name'] . ' &nbspGender: ' . $wcase['gender'] . ' Age: ' . $wcase['age'] . '<br />Presenting Complaint: ' . $wcase['presenting_complaint'] . "</td></tr></table>";
}
echo "</span></p></div>";
}
?>
I suspect that the query needs to be changed to group the case data accordion to the waitingrooms tables, any ideas how I should do this?
EDIT
Thanks to developerCK I now have the following working code:
<?php
while ($row_waitingrooms = mysql_fetch_assoc($result_waitingrooms)){
if($row_waitingrooms['gender'] == 'f'){
$gender = 'Female';
} else if ($row_waitingrooms['gender'] == 'm'){
$gender = 'Male';
}
$waitingRoomPK = $row_waitingrooms['waitingroom_pk'];
if (!isset($waitingRooms[$waitingRoomPK])) {
$waitingRooms[$waitingRoomPK] = array(
'waitingroom_pk' => $waitingRoomPK,
'waitingroom' => $row_waitingrooms['waitingroom'],
'cases' => array()
);
}
$waitingRooms[$waitingRoomPK]['cases'][] = array(
'case_pk' => $row_waitingrooms['case_pk'],
'patient_icon' => $row_waitingrooms['patient_icon'],
'first_name' => $row_waitingrooms['first_name'],
'last_name' => $row_waitingrooms['last_name'],
'age' => $row_waitingrooms['age'],
'gender' => $gender,
'presenting_complaint' => $row_waitingrooms['presenting_complaint']
);
}
foreach($waitingRooms as $val){
echo "<h6>" . $val['waitingroom'] . "</h6><div><p><span class='text'>";
foreach ($val['cases'] as $wcase){
echo "<table width='100%'><tr><td><input name='case' id='case_" . $wcase['case_pk'] . "' type='radio' value='" . $wcase['case_pk'] . "' /></td><td width='65' align='left'><div class='case_list'><img src='images/case_icons/" . $wcase['patient_icon'] . "' width='44' height='45' /></div></td><td width='350' align='left'>" . $wcase['first_name'] . ' ' . $wcase['last_name'] . ' &nbspGender: ' . $wcase['gender'] . ' Age: ' . $wcase['age'] . '<br />Presenting Complaint: ' . $wcase['presenting_complaint'] . "</td></tr></table>";
}
echo "</span></p></div>";
}
?>

use it after while loop, and remove your foreach loop.
your query is right. just need to change some php code
foreach(waitingRooms as $val){
echo "<h6>" . $val['waitingroom'] . "</h6><div><p><span class='text'>";
foreach ($val['cases'] as $wcase){
echo "<table width='100%'><tr><td><input name='case' id='case_" . $wcase['case_pk'] . "' type='radio' value='" . $wcase['case_pk'] . "' /></td><td width='65' align='left'><div class='case_list'><img src='images/case_icons/" . $wcase['patient_icon'] . "' width='44' height='45' /></div></td><td width='350' align='left'>" . $wcase['first_name'] . ' ' . $wcase['last_name'] . ' &nbspGender: ' . $wcase['gender'] . ' Age: ' . $wcase['age'] . '<br />Presenting Complaint: ' . $wcase['presenting_complaint'] . "</td></tr></table>";
}
echo "</span></p></div>";
}

Related

PHP SQL integration

I am connected to my database.
Created a drop down-box. Which works fine:
$sql = "SELECT * FROM Customer";
$result = mysql_query($sql);
echo "<b>Customer Name : </b>" . "<select id='CustomerName' name='CustomerName'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['CustomerName'] . "'>" . $row['CustomerName'] . "</option>";
}
Now I am stuck trying to put the values from table Customer into an array
Which looks like this:
$types = array (
'A' => 10.99,
'B' => 4.99,
'C' => 13.99);
What I intend to do is to create this array where,
Instead of A B C, there are CustomeName and CustomerPrice in place of the price.
The Customer table has
+----------------+-----------------+---------------+
| Customer_ID | CustomerName | CustomerPrice |
+----------------+-----------------+---------------+
| 1 | A | 10.99 |
| 2 | B | 4.99 |
| 3 | C | 13.99 |
+----------------+-----------------+---------------+
Please help
You basically do the same thing you did with the drop down except to generate the array. You could do it in the same loop:
$sql = "SELECT * FROM Customer";
$result = mysql_query($sql);
$array = array();
echo "<b>Customer Name : </b>" . "<select id='CustomerName' name='CustomerName'>";
while ($row = mysql_fetch_array($result)) {
$array[$row['CustomerName']] = $row['CustomerPrice'];
echo "<option value='" . $row['CustomerName'] . "'>" . $row['CustomerName'] . "</option>";
}
Hope this helps

PHP : show all rows in MySQL that contain the same value in a column

I am trying write code in PHP with a Mysql database, and the problem is I want to show all rows with a same column value. for example like this:
id | Name | age | Location | type
----+----------+-----+----------+------
1 | Ane | 22 | SG | 1
2 | Angi | 19 | IND | 2
3 | Bobby | 23 | PH | 1
4 | Denis | 26 | IND | 1
5 | Jerry | 21 | SG | 1
6 | Mikha | 25 | JP | 2
I want only show the rows with value in column type = 1 or value in column Location and showing as table in html view.
The result what I want is like this:
id | Name | age | Location | type
---+----------+-----+----------+------
1 | Ane | 22 | SG | 1
3 | Bobby | 23 | PH | 1
4 | Denis | 26 | IND | 1
5 | Jerry | 21 | SG | 1
This is my code:
<?php
$con = mysqli_connect("localhost","root","","testuser");
$query = mysqli_query("SELECT * FROM `usersdata` WHERE `type`='1'");
$result = mysqli_query($con,$query);
echo "<table class='tmaintable' border='0' cellpadding='3' width='99%' align='center' cellspacing='1'>
<tr class='theader'>
<td>ID</td>
<td>Name</td>
<td>Age</td>
<td>Location</td>
<td>Type</td>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr class='todd'>";
echo "<td style='text-align:center;' >" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
But I got errors like this:
Warning: mysqli_query() expects at least 2 parameters, 1 given in www.myweb.com\users_list\type.php on line 94 << this point "$query" line
Warning: mysqli_query(): Empty query in www.myweb.com\users_list\type.php on line 95 << this point "$result" line
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in www.myweb.com\users_list\type.php on line 109 << this point "while ($row=" line
I was trying understand and still i don't get it, anyone can help me please?! thanks.
Change
$query = mysqli_query("SELECT * FROM usersdata WHERE type='1'");
to
$query = "SELECT * FROM usersdata WHERE type='1'";
EDIT
Just for explanation:
mysqli_query takes 2 arguments: connection and query. I assumed that you wanted to just create query string in this line where this error arouse since it is used one line furter as a query string.
Issue is in bolow lines.
$query = mysqli_query("SELECT * FROM usersdata WHERE type='1'");
$result = mysqli_query($con,$query);
You have 2 ways to resolve this.
1. $query = "SELECT * FROM `usersdata` WHERE `type`='1'";
$result = mysqli_query($con,$query);
2. $query = mysqli_query($con,"SELECT * FROM `usersdata` WHERE `type`='1'");
Try this one. It should be working fine
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM `usersdata` WHERE `type`='1'";
$result = mysqli_query($conn, $sql);
echo "<table class='tmaintable' border='0' cellpadding='3' width='99%' align='center' cellspacing='1'>
<tr class='theader'>
<td>ID</td>
<td>Name</td>
<td>Age</td>
<td>Location</td>
<td>Type</td>
</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr class='todd'>";
echo "<td style='text-align:center;' >" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>

PHP MYSQL while loop till same value than break and sum, than do the same with next value

I try to loop all my rows from MySQL, and I got it. The problem is I want to case them, I think its the correct expression.
For example: MYSQL
+----+----------+-------------+------------+
| id |abholdatum| fahrer | preis |
+----+----------+-------------+------------+
| 6 |14 11 15 | martin| 22 |
| 7 |14 11 15 | david | 25 |
| 8 |31 12 15 | david | 22 |
| 10|29 12 15 | martin| 23 |
| 12|30 12 15 | david | 29 |
+----+----------+-------------+------------+
now I get this:
ID Abholdatum Fahrer Preis
7 14 November 2015 david 25
8 31 Dezember 2015 david 22
12 30 Dezember 2015 david 29
6 14 November 2015 martin 22
10 29 Dezember 2015 martin 23
and I actually want this:
ID Abholdatum Fahrer Preis
--------------------------------------
David
7 14 November 2015 david 25
8 31 Dezember 2015 david 22
12 30 Dezember 2015 david 29
--------------------------------------
Summ 76
--------------------------------------
--------------------------------------
Martin
6 14 November 2015 martin 22
10 29 Dezember 2015 martin 23
--------------------------------------
Summ 45
--------------------------------------
and this is my simple php script:
$sql = mysqli_query($dbc, "select * from fahrten ORDER BY fahrer ASC");
while ($row = mysqli_fetch_array($sql)){
echo "<tr>"
. "<td>" . $row['id'] ."</td>"
. "<td>" . $row['abholdatum'] ."</td>"
. "<td>" . $row['fahrer'] . "</td>"
. "<td>" . $row['preis'] . "</td>"
. "</tr>";
}
echo "</table>"
. "</div>";
use this code
$sql = mysqli_query($dbc, "select * from fahrten ORDER BY fahrer ASC");
$fahrer = array();
while ($row = mysqli_fetch_array($sql)){
if (!in_array($row['fahrer'], $fahrer))
{
$fahrer[] = $row['fahrer'];
}
}
foreach($fahrer as $value){
echo "<tr>". $value ."</tr>";
$sum=0;
while ($row1 = mysqli_fetch_array($sql)){
if($value = $row1['fahrer']){
echo "<tr>"
. "<td>" . $row1['id'] ."</td>"
. "<td>" . $row1['abholdatum'] ."</td>"
. "<td>" . $row1['fahrer'] . "</td>"
. "<td>" . $row1['preis'] . "</td>"
. "</tr>";
$sum=$sum+$row1['preis'];
}
}
echo "Summ = ".$sum; }
echo "</table>"
. "</div>";
I tested this, It should work:
$new = 1;
$sum = 0;
$last_fahrer = 'initial';
while($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {
if($last_fahrer != $row['fahrer'] && $last_fahrer != 'initial') {
echo "<tr>"
. '<td colspan="3">Summ</td>'
. "<td>" . $sum . "</td>"
. "</tr>";
$sum = 0;
$new = 1;
}
if($new == 1) {
echo "<tr>"
. '<td colspan="4">' . ucwords($row["fahrer"])
. '</td>'
. '</tr>';
$new = 0;
}
echo "<tr>"
. "<td>" . $row['id'] ."</td>"
. "<td>" . $row['abholdatum'] ."</td>"
. "<td>" . $row['fahrer'] . "</td>"
. "<td>" . $row['preis'] . "</td>"
. "</tr>";
$last_fahrer = $row['fahrer'];
$sum = $sum + $row['preis'];
}
echo "<tr>"
. '<td colspan="3">Summ</td>'
. "<td>" . $sum . "</td>"
. "</tr>"
. "</table>"
. "</div>";

SELECT SUM data rank and Resource id #9 error PHP

I have a website in which logged in members are stored under a table called ‘users’
‘users’ table
users_sales_guild_id | users_first_name | users_surname
555 | Jane | Smith
333 | John | Smith
111 | Mike | Myers
The users have sales data in a 'sales_points' field which is in a separate table called ‘sales_list’.
‘sales_list’ table
sales_id | users_sales_guild_id | sales_points | sales_entry_date
1 | 555 | 50 | 2013-02-31 00:00:00
2 | 333 | 30 | 2013-02-31 00:00:00
3 | 111 | 10 | 2013-02-31 00:00:00
4 | 555 | 50 | 2013-03-31 00:00:00
5 | 333 | 30 | 2013-03-31 00:00:00
6 | 111 | 10 | 2013-03-31 00:00:00
Essentially what I am trying to do is a query which:
A. Calculates the total amount of 'sales_points' for each user from 'sales_list'
B. Lists 100 users with the user having the most points at the top, then ranking the next highest below and so on...
C. Im not after a ranking number, just the order itself.
With the code below I am getting 100 users printing ok, however I am getting a ‘Resource id #9’ message in the ’Total Points’ column when it prints. Can anyone help?
What I am trying to print
Jane Smith | 100
John Smith | 60
Mike Myers | 20
Code:
<?php
require_once ('config.inc.php');
$page_title = '';
include ('header.html');
if (!isset($_SESSION['users_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= 'login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}?>
<h1>Rankings</h1>
<?php require_once ('database.php'); // Connect to the database.
$total = mysql_query("SELECT SUM(sales_points) FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
$query = "SELECT us.users_id, us.dealership_id, us.users_sales_guild_id, us.users_first_name, us.users_surname, us.users_type,
de.dealership_id, de.users_dealer_name, de.class , de.region, de.state, de.users_dealer_code_id, de.users_dealer_code_new_id, de.users_model, de.pma
FROM users AS us, dealerships AS de
WHERE us.dealership_id = de.dealership_id
ORDER BY ’$total’ DESC
LIMIT 100";
$result = #mysql_query ($query);
// Table header.
echo '<table width="680"cellpadding="5" cellspacing="1" style="font-size:12px;">
<tr class="orangehead">
<td align="center"><b>Member</b></td>
<td align="center"><b>Title</b></td>
<td align="center"><b>Dealer</b></td>
<td align="center"><b>Category</a></b></td>
<td align="center"><b>Dealer Code</a></b></td>
<td align="center"><b>Total Points</a></b></td>
</tr>';
// Fetch and print all the records. echo '<td align="left"><strong>' . $row['sp_invoice_no'] . '</strong></td> ';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced'); // Switch the background color. New: ' . $row['users_sales_guild_new_id'] . '
// $entries = floor($row['sp_entry_amount']/200);
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left"><strong>' . $row['users_first_name'] . ' ' . $row['users_surname'] . '</strong></td> ';
echo '<td align="center">' . $row['users_type'] . ' </td>';
echo '<td align="center"> ' . $row['users_dealer_name'] . ' </td>';
echo '<td align="center"> ' . $row['class'] . ' </td>';
echo '<td align="center"> ' . $row['users_sales_guild_id'] . ' </td>';
echo '<td align="center"> ' . $total . '</td>';
echo '</tr>
';
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
include ('footer.html'); // Include the HTML footer.
?>
You don't fetch you first result. Fetch it as an array (mysql_fetch_array()) for example.
// Execute query
$total_query = mysql_query("SELECT SUM(sales_points)
FROM sales_list, users
WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'");
// Fetch result
$total = mysql_fetch_array($total_query);
You echo this:
$total = mysql_query("SELECT SUM(sales_points) FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
The variable $total contains the result of the query, which is a Resource. You should use mysql_fetch_assoc or a similar function to extract the result itself. It's best to give the SUM(sales_points) an alias, i.e. AS total_sales_points so you can fetch is easily.
By the way, the mysql_*-extension is soon-to-be deprecated. Good alternatives include MySQLi and PDO.
$query = mysql_query("SELECT SUM(sales_points) as points FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
$row = mysql_fetch_object($query);
$total = $row->points;
You are echoing the mysql resource, you first need to fetch the results, then you can echo them.

I want to show data from one column of mysql table in a drop down list,But in drop down it show every entry two times.But i want it only one time

|===============================|
| customer_id | customer_name |
|===============================|
| 1 | vick |
| 2 | bawa |
| 3 | smith |
| 4 | goldy |
| 5 | jojo |
=================================
There are two columns in table. I have applied the following query.But it shows every name two times but i want every name one time in dropdown.
Please tell me how to show every name only one time in drop down....My second question is that..i want to take the selected value to next page....But first problem is that how to show every name from customer_name single time...But it shows every name two times....Thank you sir
<table>
<tr>
<td>customer name</td>
<td><select name="customer_name">
<?php
$query = 'SELECT customer_id, customer_name FROM customer_table';
$result = mysql_query($query, $db) or die(mysql_error($db));
while ($row = mysql_fetch_assoc($result))
{
foreach ($row as $value)
{
echo '<option value="' . $row['customer_id'] . '"> ' . $row['customer_name'] . '</option>';
}
}
?>
</select></td>
</tr>
</table>
your suolution :
no need of for each...
while ($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['customer_id'] . '"> ' . $row['customer_name'] . '</option>';
}
You have 2 loops here which is making it to be repeated.Just remove foreach($row as $value) loop and you will get the result.
while ($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['customer_id'] . '"> ' . $row['customer_name'] . '</option>';
}
This would work .

Categories