Can I use a single SQL statement to return three separate results I can display through PHP? I'm looking to formulate three different "total" counts on a single table with three different conditions.
Eg something like....
$resultGetTotals = SELECT COUNT(Total1) FROM table_xyz WHERE Status = X AS Total1
SELECT COUNT(Total2) FROM table_xyz WHERE Status = X AND Person = Y AS Total2
SELECT COUNT(Total3) FROM table_xyz WHERE Status = Y AND Person = X AS Total3
while ($rGetTotals = mysql_fetch_array($resultGetTotals)){
$Total1 = $rGetTotals["Total1"]
$Total2 = $rGetTotals["Total2"]
$Total2 = $rGetTotals["Total2"];
}
Total One is: <?php print $Total1; ?><br>
Total Two is: <?php print $Total2; ?><br>
Total Three is: <?php print $Total3; ?><br>
Any help greatly appreciated :)
SQL:
SELECT SUM(CASE WHEN t.status = X THEN 1 ELSE 0 END) AS total1,
SUM(CASE WHEN t.status = X AND t.person = Y THEN 1 ELSE 0 END) AS total2,
SUM(CASE WHEN t.status = Y AND t.person = X THEN 1 ELSE 0 END) AS total3
FROM TABLE_XYZ t
PHPified:
$result = mysql_query("SELECT SUM(CASE WHEN t.status = X THEN 1 ELSE 0 END) AS total1,
SUM(CASE WHEN t.status = X AND t.person = Y THEN 1 ELSE 0 END) AS total2,
SUM(CASE WHEN t.status = Y AND t.person = X THEN 1 ELSE 0 END) AS total3
FROM TABLE_XYZ t");
while ($row = mysql_fetch_array($result)) {
echo "Total One is: $row['total1']<br>"
echo "Total Two is: $row['total2']<br>"
echo "Total Three is: $row['total3']<br>"
}
mysql_free_result($result);
Assuming you want the number of rows for each user (and not the number of non-null values in three different columns), and then for all users, and further assuming that there are only Person X and Y in the table, use:
SELECT Person, COUNT(*) FROM table_xyz GROUP BY Person
Retrieve the two totals (for person X and person Y) and add them together to get the grand total.
Related
Can't manage to come up with a correct query to compute the total no of students
I have three tables:
student - contains student profile either male or female
2.student_attendance - contains attendance details for whether a student was present a either "0" or "1"
attendance - contains all session details where by a one session can be attended by a number of students.
I need to calculate the number of boys/girls in present or absent for a session.
my major headache is to interpreate these logic to sql
if(in_attendace =1) then
sum the number of boys as boys_present
sum the number of girls as girls_present
else
sum the number of boys as boys_absent
sum the number of girls as girls_absent
# MY closest sql is its not working :(
select
case when a.in_attendance = 1 then
SUM(CASE b.gender when 1 then 1 else 0 end ) as male_present,
SUM(CASE b.gender when 2 then 1 else 0 end ) as female_present,
ELSE
SUM(CASE b.gender when 1 then 1 else 0 end ) as male_absent,
SUM(CASE b.gender when 2 then 1 else 0 end ) as female_absent
END
from attendance_student as a inner join student as b on a.student_id = b.id where a.session_details_id = 38
Well, you are not very far from the solution, you just need to separate them into different columns(I assume that's what you want) :
select COUNT(CASE WHEN a.in_attendance = 1 and b.gender = 1 then 1 END) as male_present,
COUNT(CASE WHEN a.in_attendance = 1 and b.gender = 2 then 1 END) as female_present,
COUNT(CASE WHEN a.in_attendance = 0 and b.gender = 1 then 1 END) as male_absent,
COUNT(CASE WHEN a.in_attendance = 0 and b.gender = 2 then 1 END) as female_absent
FROM attendance_student a
INNER JOIN student b
ON a.student_id = b.id
WHERE a.session_details_id = 38
I have a table named watersourcetype consisting of water types.
link : watersourcetype TABLE
and another table health_and_sanitation consisting of household no. and watersource_id
I have this query :
SELECT h.purok_number,
SUM(CASE WHEN hs.watersystem = 'Community water system-own' THEN 1 ELSE 0 END) AS a,
SUM(CASE WHEN hs.watersystem = 'Community water system-shared' THEN 1 ELSE 0 END) AS b,
SUM(CASE WHEN hs.watersystem = 'Deep well-own' THEN 1 ELSE 0 END) AS c,
SUM(CASE WHEN hs.watersystem = 'Deep well-shared' THEN 1 ELSE 0 END) AS d,
SUM(CASE WHEN hs.watersystem = 'Artesian well-own' THEN 1 ELSE 0 END) AS e,
SUM(CASE WHEN hs.watersystem = 'Artesian well-shared' THEN 1 ELSE 0 END) AS f,
SUM(CASE WHEN hs.watersystem = 'Dug/shallow well-own' THEN 1 ELSE 0 END) AS g,
SUM(CASE WHEN hs.watersystem = 'Dug/shallow well-shared' THEN 1 ELSE 0 END) AS h,
SUM(CASE WHEN hs.watersystem = 'River, stream, lake, spring, bodies of water' THEN 1 ELSE 0 END) AS i,
SUM(CASE WHEN hs.watersystem = 'Bottled water' THEN 1 ELSE 0 END) AS j,
SUM(CASE WHEN hs.watersystem = 'Tanker truck/Peddler' THEN 1 ELSE 0 END) AS k
FROM health_and_sanitation AS hs, house_hold AS h, f_member as f
WHERE
h.brgy_name='$brgy_name' AND
h.hh_number=hs.hh_number AND
h.hh_number=f.hh_number AND
f.is_household='HOUSEHOLD' AND
EXTRACT(YEAR FROM f.reg_date) BETWEEN '$sel_year' AND '$sel_year'
group by h.purok_number
order by h.purok_number
what i want is to put a for loop inside above sql query since table watersourcetype is dynamic another data will be added to watersourcetype soon so i dont have to define in my case statement on above query the watersystem . The query should look like this :
$qry = pg_query("select cwatertype from tbl_watersourcetype");
SQL:
SELECT h.purok_number,
// is this possible ? putting a while loop or forloop inside a query in PHP ?
while($row = pg_fetch_array($qry))
{
SUM(CASE WHEN hs.watersystem = '$row['cwatertype']' THEN 1 ELSE 0 END) AS a
}
FROM health_and_sanitation AS hs, house_hold AS h, f_member as f
WHERE
h.brgy_name='$brgy_name' AND
h.hh_number=hs.hh_number AND
h.hh_number=f.hh_number AND
f.is_household='HOUSEHOLD' AND
EXTRACT(YEAR FROM f.reg_date) BETWEEN '$sel_year' AND '$sel_year'
group by h.purok_number
order by h.purok_number
is that possible ?
If I understand your query correctly, you are trying to retrieve the number of watersourcetypes per household, with a single record returned per household. If that is indeed the case you need to use the crosstab() function from the tablefunc extension.
However, if you can get by with multiple rows giving the number of sources per watersourcetype per household then you can simply and more efficiently use the COUNT() aggregate in the SELECT statement (with some decent formatting for legibility):
SELECT h.purok_number, hs.watersystem, COUNT(hs.watersystem) AS num
FROM health_and_sanitation AS hs,
house_hold AS h,
f_member AS f
WHERE h.brgy_name='$brgy_name'
AND h.hh_number=hs.hh_number
AND h.hh_number=f.hh_number
AND f.is_household='HOUSEHOLD'
AND EXTRACT(YEAR FROM f.reg_date) BETWEEN '$sel_year' AND '$sel_year'
GROUP BY h.purok_number, hs.watersystem
ORDER BY h.purok_number;
Additionally, I am assuming that your health_and_sanitation table is a view on the watersourcetype table; otherwise you are duplicating data in two tables which is (generally) a big boo-boo. Given also your issue with additional water source type, you may want to see if your database design is in 3NF.
Cheers,
Patrick
this is an example on how to put for loop inside SELECT statement :
$qry_6_12 .= " SELECT count(ncropfarmingreasonid) as counted , " ;
for($i=2;$i<=$count_row;$i++) // loop the number of rows and used $i as ncropfarmingreasonid
{
if(($count_row-$i)==0)
{
$qry_6_12 .= "SUM(CASE WHEN ncropfarmingreasonid = ".$i." THEN 1
ELSE 0 END) a".$i."";
}
else
{
$qry_6_12 .= "SUM(CASE WHEN ncropfarmingreasonid = ".$i." THEN 1
ELSE 0 END) a".$i.",";
}
}
$qry_6_12 .= " FROM tbl_climatechange as c, tbl_household as h, tbl_barangay as b where h.chholdnumber=c.chholdnumber and b.cbrgycode=h.cbrgycode and b.cbrgyname = 'AMPAYON' ";
$query_6_12 = pg_query($qry_6_12);
I need to create a one day agenda, with the reservations of our study rooms in it.
This agenda should show all the rooms and show the occupied times, like:
8:00 8:15 8:30 8:45 9:00 9:15 9:30 ...
Room 1 | [username ] [username 2
Room 2 | [username 3 ]
Room 3 |[username 4 ] [username 5 ...
...and so on
So it should be clear from the table that Room 1 is occupied from 8:15-9:00 and 9:30-..., Room2 occupied from...
But also which times the study rooms are free.
And I'm a bit stuck at the mo.
This is the code I already have, but it's incomplete:
<table>
<tr>
<?php
$roomlist = "SELECT * FROM rooms";
$roomresult = mysql_query($roomlist);
while($roomnames=mysql_fetch_array($roomresult)) {
$roomid=$roomnames['roomid'];
$roomname=$roomnames['roomname'];
?>
<td><?= $roomname;?></td>
<?php
$query = "SELECT * FROM reservations WHERE roomid = '$roomid' AND (start LIKE '%" . $agenda . "%') ORDER BY start,roomid,end ";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$username=$row["username"];
$aantal=$row["numberingroup"];
$reservationid=$row["reservationid"];
$start=$row["start"];
$end=$row["end"];
$roomid=$row["roomid"];
$startdate = explode(" ",$start);
$startdate[0] = explode("-",$startdate[0]);
$startdate[1] = explode(":",$startdate[1]);
$StartFormat = mktime($startdate[1][0],$startdate[1][1],$startdate[1][2],$startdate[0][1],$startdate[0][2],$startdate[0][0]);
$StartDate = date("d/m/Y",$StartFormat);
$StartTime = date("H:i",$StartFormat);
$stopdate = explode(" ",$end);
$stopdate[0] = explode("-",$stopdate[0]);
$stopdate[1] = explode(":",$stopdate[1]);
$StopFormat = mktime($stopdate[1][0],$stopdate[1][1],($stopdate[1][2]+1),$stopdate[0][1],$stopdate[0][2],$stopdate[0][0]);
$StopDate = date("d/m/Y",$StopFormat);
$StopTime = date("H:i",$StopFormat);
$cell = (strtotime($StopTime)-strtotime($StartTime))/(60*15); //a quarter per cell
?>
<td><?= $username . " " . $cell;?></td>
<?php } ?>
</tr>
<?php
}
mysql_close();
?>
</table>`
$cell is calculated because I figured I needed to know how many cells a reservation needed (so one per quarter), but I'm stuck now on how to calculate the free slots, and how to implement all that in a table.
UPDATE:
structure of table 'reservations'
reservationid,start,end,roomid,username
41,2014-01-06 08:00:00.000000,2014-01-06 08:59:59.000000,28,stefdg
As basic example piece of SQL to give you some idea of how to return a range of possible time slots / room combinations and join that against your reservations
SELECT *
FROM rooms
CROSS JOIN
(
SELECT DATE_ADD(DATE_ADD(CURDATE(), INTERVAL 8 HOUR), INTERVAL ((units.a + tens.a * 10) * 15) MINUTE) AS TimeSlotStart
FROM
(SELECT 0 AS a UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units,
(SELECT 0 AS a UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
WHERE units.a + tens.a * 10 <= 40
) TimeSlots
LEFT OUTER JOIN reservations ON rooms.roomid = reservations.roomid AND TimeSlots.TimeSlotStart >= start AND TimeSlots.TimeSlotStart < end
Note, not quite sure what your end value applies to (ie, if a reservation finishes at 9:00, I am assuming that has nothing to do with the time slot that starts at 9:00)
EDIT - scraipt based on yours to output the table of details. This is just putting out xxx for any time slot that a room is occupied for.
<html>
</html>
<body>
<table>
<?php
$link = mysqli_connect('localhost', 'root', '');
$db_selected = mysqli_select_db($link, 'test');
$sql = "SELECT a.timeslot_start, b.roomid, b.roomname, TIME(c.start) AS start
FROM timeslots a
CROSS JOIN rooms b
LEFT OUTER JOIN reservations c
ON b.roomid = c.roomid
AND a.timeslot_start >= TIME(c.start)
AND a.timeslot_start < TIME(c.end)
ORDER BY b.roomid, a.timeslot_start";
$roomresult = mysqli_query($link, $sql) or die(mysql_error());
while($roomnames=mysqli_fetch_assoc($roomresult))
{
$room_bookings[$roomnames['roomid']][] = $roomnames;
}
$first_room = reset($room_bookings);
echo "<table>";
$FirstRoomDetails = reset($room_bookings);
$Header = array(0=>array("<td></td>"), 1=>array("<td></td>"));
foreach($FirstRoomDetails AS $aRoomTimeSlot)
{
$TimeSlotSplit = explode(':', $aRoomTimeSlot['timeslot_start']);
if ($TimeSlotSplit[1] == '00')
{
$Header[0][] = "<td colspan='4'>".$TimeSlotSplit[0]."</td>";
}
$Header[1][] = "<td>".$TimeSlotSplit[1]."</td>";
}
echo "<tr>".implode('', $Header[0])."</tr>\r\n";
echo "<tr>".implode('', $Header[1])."</tr>\r\n";
foreach($room_bookings AS $aRoomsBookings)
{
echo "<tr>";
$First = true;
foreach($aRoomsBookings AS $aRoomTimeSlot)
{
if ($First)
{
$First = false;
echo "<td>".$aRoomTimeSlot['roomname']."</td>";
}
echo "<td>".(($aRoomTimeSlot['start'] == '') ? '' : 'xxxx')."</td>";
}
echo "</tr>\r\n";
}
echo "<table>";
mysqli_close($link);
?>
</table>
</body>
</html>
I have a table containing the following data columns:
ord_number check
OR123 0
OR125 1
OR123 2
OR123 0
OR124 0
OR124 0
OR125 0
OR123 0
The check column indicates if we have fully supplied the order line with a value of zero or below meaning 'yes we have supplied complete' and a value of 1 or above meaning 'no we have not supplied complete' .
To calculate an order fill rate (how many orders have been filled complete) I need to know how many of the orders have only zero check results for each entry and how many have at least one positive check result.
My logic is that I need to GROUP the items and then carry out a COUNTIF within the group (this may be the wrong SQL methodology but logically it makes sense to me in terms of the outcome I'm looking for). From this query I need to return those two values into my PHP script.
The results from this data set would be:
Complete = 1 (orders with only zero checks)
Incomplete = 2 (orders where one or more lines have positive checks)
I've spent the morning trying to find a solution but can't find anything that I either understand enough or is similar enough that I can break it down and understand it.
If someone can help me by pointing me in the right direction or can provide a sample with an explanation I would be very grateful.
For 1 row with 2 counter fields use:
SELECT
SUM(CASE WHEN `check` = 1 THEN 1 ELSE 0 END) AS incomplete,
SUM(CASE WHEN `check` = 0 THEN 1 ELSE 0 END) AS complete
FROM orders
For 2 rows with 1 name use:
SELECT COUNT(`ord_number`) AS fulfillment
FROM orders WHERE (`check`=0)
UNION SELECT COUNT(ord_number)
FROM orders WHERE (`check`=1)
in which case you need to put row 1 into $complete (check=0)
and row 2 into $incomplete (check=1)
you may add:
UNION SELECT COUNT(ord_number) FROM orders
which will give you the total records on row 3.
output will be:
SELECT * FROM orders
ord_number check
---------------------
OR123 0
OR124 1
OR125 0
OR126 0
OR127 0
OR123 0
OR125 1
SELECT COUNT(`ord_number`) AS counts FROM orders or1 WHERE (`check`=0)
UNION SELECT COUNT(ord_number) FROM orders or2 WHERE (`check`=1)
UNION SELECT COUNT(ord_number) FROM orders
counts
-------
5
2
7
SELECT
SUM(CASE WHEN `check` = 1 THEN 1 ELSE 0 END) AS incomplete,
SUM(CASE WHEN `check` = 0 THEN 1 ELSE 0 END) AS complete FROM orders
incomplete complete
-------------------------
2 5
As for PHP:
for 1 row:
mysql_select_db($database_test, $test);
$query_countIn1Row = " SELECT SUM(CASE WHEN `check` = 1 THEN 1 ELSE 0 END) AS
incomplete,
SUM(CASE WHEN `check` = 0 THEN 1 ELSE 0 END) AS complete
FROM orders";
$countIn1Row = mysql_query($query_countIn1Row, $test) or die(mysql_error());
do {
$varIncomplete = $row_countIn1Row['incomplete'];
$varComplete = $row_countIn1Row['complete'];
} while ($row_countIn1Row = mysql_fetch_assoc($countIn1Row));
and for 1 column with counts:
mysql_select_db($database_test, $test);
$query_countOrders = "SELECT COUNT(`ord_number`) AS counts
FROM orders or1 WHERE (`check`=0)
UNION SELECT COUNT(ord_number) FROM orders or2 WHERE (`check`=1)
UNION SELECT COUNT(ord_number) FROM orders";
$countOrders = mysql_query($query_countOrders, $test) or die(mysql_error());
$myCounts = array();
do {
$myCounts[]= $row_countOrders['counts'];
} while ($row_countOrders = mysql_fetch_assoc($countOrders));
$complete = $myCounts[0];
$incomplete = $myCounts[1];
$total = $myCounts[2];
SELECT ord_number,IF(MAX( check) <=0 ,'COMPLETED','PENDING')
from TABLENAME
group by (ord_number )
Through this oneline query you will easily get which order is in pending status and which one is complete status
AS per your given details
The check column indicates if we have fully supplied the order line
with a value of zero or below meaning 'yes we have supplied complete'
and a value of 1 or above meaning 'no we have not supplied complete' .
it means check column can contain negative value as well as 0 for indicating the complete status and 1 or any postive integer number to indicate the pending status.
so the logic should be find the max(check) so if the max for a order is found 0 or any negative number then we will sure that order is complete and if it found a positive number it means there was a pending entry.
You can do this in two steps:
SELECT ord_number,
SUM(CASE WHEN `check` = 0 THEN 1 ELSE 0 END) as Comp,
COUNT(`check`) as total
FROM tab1
GROUP BY ord_number
This would give you the number of rows with 0 (complete) and the total number of rows for each ord_number.
Then you do a COUNT to validate when those two are equal:
SELECT CASE WHEN comp = total THEN 'COMPLETE' ELSE 'INCOMPLETE' END AS status,
COUNT(*) AS statusCount
FROM(
SELECT ord_number,
SUM(CASE WHEN `check` = 0 THEN 1 ELSE 0 END) as Comp,
COUNT(`check`) as total
FROM tab1
GROUP BY ord_number) a
GROUP BY 1;
This should get you what you want.
sqlfiddle demo
Note that i used ` around check since this is a mysql reserved word
This is a beginner php/mysql question, I've messed around for hours with various loops but I haven't been able to reach the goal. I have two tables in the db. One that contains books and one that contain the stock info for the books. Like this:
id title
1 A book
2 Another book
3 A third book
and for the stock (book_stock)
id book_id warehouse_id qty
1 1 1 12
2 1 2 45
3 2 3 22
4 3 1 78
5 1 3 15
I want to read the tables, match the id from book table with book_id from stock table and then output a summary in a html table, showing book titles and how many of each book exist in the different warehouses. What I've tried so far involves looping mysql requests, something that seems to crash since it outputs no results. I have a feeling the solutions is simple and involves arrays but my skills are lacking...
Here is my non-working code. The function works fine for 1, 2 and even 20 results entered manually, but only outputs blank table cells when looped.
//function to get stock based on book id number
function get_stock($book_row_number)
{
//get BOOK from db
$book_query="SELECT * FROM book";
$book_result=mysql_query($book_query);
//determine book info
$book_id=mysql_result($book_result,$book_row_number,"id");
$book_title=mysql_result($book_result,$book_row_number,"title");
//get LONDON stock for this book from db
$stock_query="SELECT qty FROM book_stock WHERE book_id='$book_id' AND warehouse_id='1'";
$stock_result=mysql_query($stock_query);
$stock_london=mysql_result($stock_result,0,"qty");
//get USA stock for this book from db
$stock_query="SELECT qty FROM book_stock WHERE book_id='$book_id' AND warehouse_id='2'";
$stock_result=mysql_query($stock_query);
$stock_usa=mysql_result($stock_result,0,"qty");
//get GERMANY stock for this book from db
$stock_query="SELECT qty FROM book_stock WHERE book_id='$book_id' AND warehouse_id='4'";
$stock_result=mysql_query($stock_query);
$stock_germany=mysql_result($stock_result,0,"qty");
echo "<tr><td>$book_title</td><td>$stock_london</td><td>$stock_usa</td><td>$stock_germany</td></tr>\n";
}
//find number of rows in book list
$all_query="SELECT * FROM book";
$all_result=mysql_query($all_query);
$all_rows=mysql_numrows($all_result);
// run the function on all the rows
$i=0;
while ($i < $all_rows) {
get_stock('$all_rows');
$i++;
}
EDIT: And the code as it is now
<?php
//set up connection
$user="username";
$password="paswd";
$database="database";
mysql_connect("localhost",$user,$password);
#mysql_select_db($database) or die( "Unable to select database");
//query
$book_query="SELECT
book_id,
title,
SUM(CASE WHEN warehouse_id = 1 THEN book_stock.qty ELSE 0 END) AS warehouse1,
SUM(CASE WHEN warehouse_id = 2 THEN book_stock.qty ELSE 0 END) AS warehouse2,
SUM(CASE WHEN warehouse_id = 3 THEN book_stock.qty ELSE 0 END) AS warehouse3,
SUM(CASE WHEN warehouse_id = 4 THEN book_stock.qty ELSE 0 END) AS warehouse4
FROM
book_stock
JOIN book ON book.id = book_stock.book_id
GROUP BY book_id, title";
//loop
$result = mysql_query($book_query);
if ($result) {
while ($row = mysql_fetch_assoc($row)) {
echo "<tr><td>" . htmlspecialchars($row['title']) . "</td><td>{$row['warehouse1']}</td><td>{$row['warehouse2']}</td><td>{$row['warehouse3']}</td><td>{$row['warehouse4']}</td></tr>";
}
}
else echo mysql_error();
//close database
mysql_close();
?>
You can do this in a single query, if you build it as a pivot table. The idea is that the SUM() aggregates add together the value of qty for the matching warehouse_id, or 0 when it doesn't match for each row, collapsing all the warehouses into a single row.
SELECT
SUM(CASE WHEN warehouse_id = 1 THEN qty ELSE 0 END) AS warehouse1,
SUM(CASE WHEN warehouse_id = 2 THEN qty ELSE 0 END) AS warehouse2,
SUM(CASE WHEN warehouse_id = 3 THEN qty ELSE 0 END) AS warehouse3,
SUM(CASE WHEN warehouse_id = 4 THEN qty ELSE 0 END) AS warehouse4
FROM
book_stock
WHERE book_id = $book_id
For book_id = 1, this produces a result like:
warehouse1 warehouse2 warehouse3 warehouse4
12 45 15 0
To get it for all books in rows, add a GROUP BY:
SELECT
book_id,
title,
SUM(CASE WHEN warehouse_id = 1 THEN qty ELSE 0 END) AS warehouse1,
SUM(CASE WHEN warehouse_id = 2 THEN qty ELSE 0 END) AS warehouse2,
SUM(CASE WHEN warehouse_id = 3 THEN qty ELSE 0 END) AS warehouse3,
SUM(CASE WHEN warehouse_id = 4 THEN qty ELSE 0 END) AS warehouse4
FROM
book_stock
JOIN book ON book.id = book_stock.book_id
GROUP BY book_id, title
Output from PHP is then a trivial while loop:
// Assuming you already opened your <table>
$result = mysql_query($the_big_query_above);
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>" . htmlspecialchars($row['title']) . "</td><td>{$row['warehouse1']}</td><td>{$row['warehouse2']}</td><td>{$row['warehouse3']}</td><td>{$row['warehouse4']}</td></tr>";
}
}
else echo mysql_error();
// Then don't forget to close your </table>