Print out certain rows from a table - mysql

The names im using can be changed or removed in the database at times, as it is now i have to change every name in the script when that happends. Can i print it out w/o a IF for example?
<?php
$sql = "SELECT detail,
SUM(IF(depot = 'Huvuddepån', quantity, 0)) AS Huvuddepån,
SUM(IF(depot = 'Uddevalla', quantity, 0)) AS Uddevalla,
SUM(IF(depot = 'Jönköping', quantity, 0)) AS Jönköping,
SUM(IF(depot = 'Polyeten', quantity, 0)) AS Polyeten,
SUM(IF(depot = 'Krackern', quantity, 0)) AS Krackern
FROM quantities
GROUP BY detail";
$result = $conn->query($sql);
echo "<table border='0' cellspacing='3' cellpadding='3'>";
echo "<tr>";
echo "<td width='300'>"."<b>Detalj</b>"."</td>";
echo "<td align='center' width='100'>"."<b>Huvuddepån</b>"."</td>";
echo "<td align='center' width='100'>"."<b>Uddevalla</b>"."</td>";
echo "<td align='center' width='100'>"."<b>Jönköping</b>"."</td>";
echo "<td align='center' width='100'>"."<b>Polyeten</b>"."</td>";
echo "<td align='center' width='100'>"."<b>Krackern</b>"."</td>";
echo "</tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>".$row["detail"]."</td>";
echo "<td align='center'>".$row["Huvuddepån"]."</td>";
echo "<td align='center'>".$row["Uddevalla"]."</td>";
echo "<td align='center'>".$row["Jönköping"]."</td>";
echo "<td align='center'>".$row["Polyeten"]."</td>";
echo "<td align='center'>".$row["Krackern"]."</td>";
echo "</tr>";
}
} else {
echo "0 results";
}
echo "</table>";
?>

What about this ? See sqlfiddle
SET #COLUMNS = NULL;
SELECT GROUP_CONCAT(
DISTINCT CONCAT(
'SUM(CASE WHEN depot = "',
depot,
'" THEN quantity ELSE 0 END) AS "',
depot,
'"'
)
) INTO #COLUMNS
FROM quantities;
SET #SQL = CONCAT(
'SELECT
detail,
',#COLUMNS,'
FROM
quantities
GROUP BY
detail'
);
PREPARE stmt FROM #SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
It works with the following table :
CREATE TABLE quantities(
detail INT,
depot VARCHAR(20),
quantity INT
);
INSERT INTO quantities VALUES (1,"Huvuddepån",10);
INSERT INTO quantities VALUES (2,'Uddevalla',15);
INSERT INTO quantities VALUES (2,'Jönköping',20);
INSERT INTO quantities VALUES (3,'Polyeten',10);
INSERT INTO quantities VALUES (1,'Krackern',10);
INSERT INTO quantities VALUES (4,"fo'o6",10);
NOTE : Nevertheless, it will most likely break if one of your depot contains quotes ". If your data might contain such quotes, you should consider using REPLACE to replace those by \" in order to escape them.
The php code you should be using is the following one, I escaped the " in the sql because they weren't and I believe the problem came from here :
<?php
$sql = "SET #COLUMNS = NULL;
SELECT GROUP_CONCAT(
DISTINCT CONCAT(
'SUM(CASE WHEN depot = \"',
depot,
'\" THEN quantity ELSE 0 END) AS \"',
depot,
'\"'
)
) INTO #COLUMNS
FROM quantities;
SET #SQL = CONCAT(
'SELECT
detail,
',#COLUMNS,'
FROM
quantities
GROUP BY
detail'
);
PREPARE stmt FROM #SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;";
$result = $conn->query($sql);
echo "<table border='0' cellspacing='3' cellpadding='3'>";
echo "<tr>";
echo "<td width='300'>"."<b>Detalj</b>"."</td>";
echo "<td align='center' width='100'>"."<b>Huvuddepån</b>"."</td>";
echo "<td align='center' width='100'>"."<b>Uddevalla</b>"."</td>";
echo "<td align='center' width='100'>"."<b>Jönköping</b>"."</td>";
echo "<td align='center' width='100'>"."<b>Polyeten</b>"."</td>";
echo "<td align='center' width='100'>"."<b>Krackern</b>"."</td>";
echo "</tr>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>".$row["detail"]."</td>";
echo "<td align='center'>".$row["Huvuddepån"]."</td>";
echo "<td align='center'>".$row["Uddevalla"]."</td>";
echo "<td align='center'>".$row["Jönköping"]."</td>";
echo "<td align='center'>".$row["Polyeten"]."</td>";
echo "<td align='center'>".$row["Krackern"]."</td>";
echo "</tr>";
}
} else {
echo "0 results";
}
echo "</table>";
?>

Related

2 or 3 Checkboxes in MySQL query

I created the following SQL Query, which works fine. However, I want to add 2 other checkbox $Post's from another label. Now I'm a little bit without any idea how I can add it. Do I have to add an "AND" between the tbs queries?
Here is the code
include "db_connect.inc.php";
$sql = "SELECT * FROM profiles";
$sql .= " WHERE profilename = '". $_POST["profilename"] ."' ";
$sql .= " AND ort = '". $_POST["ort"] ."' ";
$sql .= "AND jahren = '" . $_POST["alter"] . "' ";
$tbs = array();
foreach( array( 'tb1', 'tb2', 'tb3' ) as $tb_key )
{
if ( empty( $_POST[$tb_key] ) ) continue;
$tbs[] = "`grosse` LIKE '" . $_POST[$tb_key] . "'";
}
if ( !empty( $tbs ) )
{
$sql .= ' AND ( ' . implode( ' OR ', $tbs ) . ' )';
}
$tbs = array();
foreach( array( 'tb4', 'tb5', 'tb6', 'tb7' ) as $tb_key )
{
if ( empty( $_POST[$tb_key] ) ) continue;
$tbs[] = "`haare` LIKE '" . $_POST[$tb_key] . "'";
}
if ( !empty( $tbs ) )
{
$sql .= ' AND ( ' . implode( ' OR ', $tbs ) . ' )';
}
$res = mysqli_query($con, $sql);
$num = mysqli_num_rows($res);
if ($num==0) echo "Kein Profil gefunden";
echo "<table border='1'>";
echo "<tr><td>Profile</td><td>Alter</td>";
echo "<td>Ort</td><td>Brustgrösse</td>";
echo "<td>Haarfarbe</td></tr>";
while ($dsatz = mysqli_fetch_assoc($res))
{
echo "<tr>";
echo "<td>" . $dsatz["profilename"] . "</td>";
echo "<td>" .$dsatz["jahren"] . "</td>";
echo "<td>" .$dsatz["ort"] . "</td>";
echo "<td>" .$dsatz["grosse"] . "</td>";
echo "<td>" .$dsatz["haare"] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
i could it resolve it. I had a wrong entry in the DB. The query works fine!

Display data from mysql database using a table

I have table of items and I want to display all the item in a table form. Each row must contain a maximum of 3 cells. How can I do that?
$query = "SELECT * FROM newrequest";
$result = mysql_query($query);
echo "<table>
<tr>";
While($row = mysql_fetch_array($result))
{
$query_two = "SELECT * FROM tblmember WHERE customer_id = '${row['customer_id']}'";
$result_two = mysql_query($query_two);
$username = mysql_fetch_array($result_two)['username'];
echo "
<td> <p><b>Advertised by:</b> " .$username . " </p>
<img src= ".$row['location']." style= width:300px; >
<p><b>Product name:</b>" .$row['product_name'] . "</p>
<p><b>Product price:</b>" . $row['price'] . "</p>
</td>";
}
echo "</tr>
</table>";
mysql_close();
?>
<?php
echo '<table>';
$i = 1;
while($row = mysql_fetch_array($result)) {
$query_two = "SELECT * FROM tblmember WHERE customer_id = '${row['customer_id']}'";
$result_two = mysql_query($query_two);
$username = mysql_fetch_array($result_two)['username'];
$flag = false;
if($i%3 == 1) echo '<tr>';
echo '<td>
<td><img src="'.$row['location'].'" style="width:300px;"/>
<p><b>Product name:</b>' .$row['product_name'] . '</p>
<p><b>Product price:</b>' . $row['price'] . '</p></td>
</td>';
if($i%3 == 0) {
$flag = true;
echo '</tr>';
}
$i++;
}
if(!$flag) echo '</tr>';
echo '</table>';
mysql_close();
?>

Changing date format from database

I am trying to change the date format before it is displayed with SQL query however the date format is being completely ignored.
my code is
$query = "SELECT * , DATE_FORMAT(formatted, '%d/%m/%Y') from movies;";
then further down this is my table
echo "<table>"
echo "<table border='2'>"
echo "<tr>
<th>id</th>
<th>title</th>
<th>date</th>
</tr>";
while($row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['formatted'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
this query is working, however the date format is being ignored and just displaying the date in yyyy-mm-dd I want it in DD-MM-YY.
thanks
Use an alias to name your calculated column
SELECT * , DATE_FORMAT(datetime, '%d/%m/%Y') AS formatted_date
from movies
Use a different name than the existing column to differ between the two. Then use
echo "<td>" . $row['formatted_date'] . "</td>";
to get the formatted one.
You need to mention the alias for the formatted datetime column other wise formatted value will not be called in your code
SELECT * ,
DATE_FORMAT(`datetime`, '%d/%m/%Y') `datetime`
from movies

combine two pdo queries showing all results from the 2nd.

I had one table listing events and attendies. To try Database normalization i split this into two tables.
I have made a database listing all the planned games for a team.
Table 1
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+name + organiser + date + location + cost + notes + id+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
i then have a second database that has everyone how has marked they will be comming
Table 2
++++++++++++++++++++++++++
+id + event + player +
++++++++++++++++++++++++++
The id is unique to each, The id from table 1 is used as the event in table 2.
i have a simple PDO query that pulls the data from table 1 into a HTMl table
if($db->connect_error) {
die("Connection error: ".$db->connect_error);
}
$sql = $db->query('SELECT * FROM event ORDER BY `date` ASC'
) or die($db->error);
echo"";
while($row = mysqli_fetch_assoc($sql))
{
$a = $row['attendees'];//will look up attendies to tick a check box if already aknowledged
$b = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
if (strpos($a,$b) !== false) {
$c = "checked='checked'";
}else{
$c = "";
}
$r=$row['id'];
echo "<div id='results'>";
echo "<CENTER>";
echo "<table BORDER=6 class='fixed'>";
echo "<TR> ";
echo "<TD COLSPAN=3 ALIGN=CENTER><form action='going.php' method='post' name='form".$r."'>Event ".$row['name']." i'm going
<input type='checkbox' name='going'".$c." onclick='document.form".$r.".submit ();'>
<input type='text' name='Organise' value='".$r."'>
<input type='text' name='name' value='".$b."'>
</form></TD>";
echo "</TR> ";
echo "<TR>";
echo "<td>";
echo "<B><u><font color='#0080FF'>Title </font></b></u>".$row['name']."<br></font>";
echo "<B><u><font color='#0080FF'>Orginiser </font></b></u>".$row['organiser']."<br></font>";
echo "<B><u><font color='#0080FF'>When </font></b></u>".date("D j-M-Y GA",$row['dt'])."<br></font>";
echo "<B><u><font color='#0080FF'>Location </font></b></u>".$row['location']."<br></font>";
echo "<B><u><font color='#0080FF'>Cost </font></b></u>£".$row['cost']."<br></font></TD>";
echo "<TD ROWSPAN=3 valign='top'><B><u><font color='#0080FF'>Attendies </font></b></u>".$row['attendees']."<br></font></TD>";//will change to table 2
echo "<TD ROWSPAN=3 valign='top'><B><u><font color='#0080FF'>notes </font></b></u>".$row['notes']."<br></font></TD>";
echo "</tr>";
echo "</table>";
echo "</CENTER>";
echo "</div>";
}
i have tried and joind these using
$sql = $db->query('SELECT t1.*, t2.event as t2event, t2.player as player
FROM `event` as t1
LEFT JOIN `going` as t2 on t1.id = t2.event
ORDER BY t1.`dt` ASC'
but all i got was a HTML table per event and per player. I'm sure its possible but can't work it out, can i create a html table from quering table 1 and add to attendies all those going from table 2 not just one or creating a result each one. ?

Simple code for exceeding time [duplicate]

This question already has an answer here:
SQL Time exceeds
(1 answer)
Closed 9 years ago.
I've written a piece of code to calculate the waiting time for a patient as follows;
$query = "SELECT PatientID, Forename, Surname, Gender, Illness, Priority, Arrival_time, TIME_FORMAT(ABS(TIMEDIFF(CURTIME(), Arrival_time)),'%H hours') as Waiting_Time FROM Patient";
Which displays the following data:
PatientID Forename Surname Gender Illness Priority Waiting Time
625 Max Courts M non-urgent moderate 4 hours
As the example shows; the waiting time is 4 hours;
I need a piece of code to detect and alert when a time is MORE THAN 4 hours; to echo an alert.
Example code I've tried;
if $waitingtime == >4 hours
then echo "patient must be seen!"
EDIT FULL CODE
<?php
$conn = mysqli_connect("localhost","root","") or die ("No connection");
mysqli_select_db($conn, "a&e") or die('Could not select database.');
$query = "SELECT PatientID, Forename, Surname, Gender, Illness, Priority, Arrival_time, TIME_FORMAT(ABS(TIMEDIFF(CURTIME(), Arrival_time)),'%H hours') as Waiting_Time FROM Patient";
$result = mysqli_query($conn, $query) or die("Invalid query");
echo "<table border='1'>
<tr>
<th>PatientID</th>
<th>Forename</th>
<th>Surname</th>
<th>Gender</th>
<th>Illness</th>
<th>Priority</th>
<th>Waiting Time</th>
</tr>";
while ($row = $result->fetch_object()){
echo "<tr>
<td>" . $row->PatientID . "</td>
<td>" . $row->Forename . "</td>
<td>" . $row->Surname . "</td>
<td>" . $row->Gender . "</td>
<td>" . $row->Illness . "</td>
<td>" . $row->Priority . "</td>
<td>" . $row->Waiting_Time . "</td>
</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
I'm using mysql_* for demonstation purposes. You should be using mysqli_* or PDO.
$query = "SELECT PatientID, Forename, Surname, Gender, Illness, Priority, Arrival_time, TIME_FORMAT(ABS(TIMEDIFF(CURTIME(), Arrival_time)),'%H') as Waiting_Time FROM Patient";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['Waiting_Time '] > 4)
{
echo "patient must be seen!"
}