I want to make a table more readable by alternating row colours. I've been through the other answers but can't see how to apply them to my code. I tried various toggle methods in the last bit of the code but just broke everything.
I can't use jquery or CSS because I can only access this part of the code.
I want to toglle to bgcolor="#8BC6FD"
<table cellspacing=0 cellpadding=2 border="thin">
<col width=150>
<col width=100>
<tr bgcolor="#D4E9FC" style="outline: thin solid">
<td class="viewN"><b>TYPE:- </b></td>
<td class="viewN"><b>PACKING:- </b></td>
</tr>
<?php
$dbconn = pg_connect("host=127.0.0.1 XXXX password=YYYY)") or die('Could not connect: ' . pg_last_error());
$query = "SELECT * FROM stock
ORDER BY name" ;
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td></tr>", htmlspecialchars($myrow['type']),htmlspecialchars($myrow['packing']));
}
?>
</table>
I can't use jquery or CSS because I can only access this part of the code.
It's unclear as to which part of code you're referring. Assuming you can access all the code showed, you can place the <style> tag before or after the <table>.
It's as simple as defining n-th CSS like
<style>
/* tr:nth-child(odd) {background-color: #0000cc} */
tr:nth-child(even) {background-color: #D4E9FC}
</style>
Related
I try to make a dynamic table. The data comes from a database.
It works so far, but I want to make a table with seperate fields, not like my way.
My code so far:
<?php
$result = mysql_query("SELECT buyTime, untilTime FROM users WHERE userName='".$_SESSION["user"]."';");
$num_rows = mysql_num_rows($result);
echo("Buy Date"."|Expire Date");
echo "<br />";
echo "<br />";
while ($row = mysql_fetch_array($result)) {
echo '<th>'.$row['buyTime'].'</th>'."|".'<th>'.$row['untilTime'].'</th>';
echo "<br />";
}
?>
The result:
Click here
So how can I make a correct table, not a pseudo one?
Thank you :)
Regards
Use a table element on html and put your php loop code inside the tbody element. How to properly create a table;
<table>
<thead>
<tr>
<th>Buy Date</th>
<th>Expire Date</th>
</tr>
</thead>
<tbody>
<?php
$result = mysql_query("SELECT buyTime, untilTime FROM users WHERE userName='".$_SESSION["user"]."';");
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td>'.$row['buyTime'].'</td><td>'.$row['untilTime'].'</td>';
echo '</tr>'
}
?>
</tbody>
</table>
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<h2>Colored Table Header</h2>
<table>
<tr>
<th>Buy Date</th>
<th>Expire Date</th>
</tr>
<?php
$result = mysql_query("SELECT buyTime, untilTime FROM users WHERE userName='".$_SESSION["user"]."';");
$num_rows = mysql_num_rows($result);
while ($row = mysql_fetch_array($result)) { ?>
<tr>
<td><?php echo $row['buyTime']; ?></td>
<td><?php echo $row['untilTime']; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
NOTE: An HTML table is defined with the <table>tag.
Each table row is defined with the <tr> tag. A table header is defined with the <th> tag. By default, table headings are bold and centered. A table data/cell is defined with the <td> tag. Moreover Mysql is outmoded please try learn new approach. You can learn it on w3schools php
Good Luck!!!
this is my first question here.
I am trying to generate pdf from a particular row of my database using mpdf. I want the code to download a particular row's data when needed. A download link is beside every row. When the download button is pressed it will download that row's data.
The code is working but it is fetching all the values from the db and assigning the values side by side.
Here is my generate pdf php
<?php
//==============================================================
//==============================================================
//==============================================================
include("mpdf/mpdf.php");
include "config.php";
$res = mysql_query("select date1, date2 from test");
if (!$res)
die("query error : ".mysql_error());
$mpdf=new mPDF('c','A4','','',32,25,27,25,16,13);
$mpdf->SetDisplayMode('fullpage');
$mpdf->list_indent_first_level = 0; // 1 or 0 - whether to indent the first
level of a list
// LOAD a stylesheet
$stylesheet = file_get_contents('mpdfstyletables.css');
$mpdf->WriteHTML($stylesheet,1); // The parameter 1 tells that this is
css/style only and no body/html/text
$html = '
<center><h3>Test</h3></center>
<center>
<table border="1">
<tr>
<th>Date 1</th><th>Date 2</th>
</tr>
<tr>';
while($row = mysql_fetch_array($res)){
$html .=
'<td>'.$row['date1'].'</td>
<td>' . $row['date2']. '</td>';
}
$html .= '
</tr>
</table></center>
';
$mpdf->WriteHTML($html,2);
$mpdf->Output('mpdf.pdf','I');
exit;
//==============================================================
//==============================================================
//==============================================================
?>
And Here is the view.php part for viewing the database
<html>
<body>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
text-align: center;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
textarea
{
width:100%;
}
.textwrapper
{
border:1px solid #dddddd;
margin:5px 0;
padding:1px;
}
</style>
<?php
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('test') or die(mysql_error());
$query=mysql_query("select * from test limit 0,10") or die(mysql_error());
echo'<table border="1" ><th >Id</th><th>Date 1</th><th>Date 2</th>';
while($res=mysql_fetch_array($query))
{
echo'<tr><td>'.$res['id'].'</td><td>'.$res['date1'].'</td>
<td>'.$res['date2'].'</td>
<td><a href="gen.php?id=<?php echo $row["id"]; ?> Downlaod</a></td>
</tr>';
}
echo'</table>';
?>
</body>
</html>
Screenshot of my view.php
In your view page,
There is no array called $row. Rather $res holds your query's resultset.
Use this instead:
while($res=mysql_fetch_array($query)){
echo"<tr>";
echo "<td>$res['id']</td><td>$res['date1']</td>";
echo "<td>$res['date2']</td>";
echo "<td>Download</td>";
echo "</tr>";
}
In you pdf generating code, change:
$res = mysql_query("select date1, date2 from test");
To:
$res = mysql_query("SELECT date1,date2 FROM test WHERE id=".intval($_GET['id']));
Please, please, please upgrade your mysql functions to mysqli_ immediately.
I recommend using a prepared statement to protect your query from malicious injection. In the meantime, you can use intval() as a lazy/temporary fix.
I'm filling an HTML table with data from the following query:
$content_downloads = mysql_query( "SELECT
s.site, s.machine, d.projectid, d.directorySize, d.connectivityError,
d.blocked, d.blockedBy, d.blockedSince, d.errorString, d.dashboardTimeStamp
FROM rtcdb.site_machines s
LEFT JOIN rtcdb.downloadstatuses d
on (s.site = d.site and s.machine = d.machine)
where s.site in (select d2.site from rtcdb.downloadstatuses d2
where d2.dashboardTimeStamp > (SELECT DATE_ADD(max(dashboardTimeStamp),INTERVAL -1 DAY)
from rtcdb.downloadstatuses)) order by s.site, s.machine asc", $con) or die(mysql_error());
This query is going into an HTML table based on the following HTML/PHP:
<table>
<thead>
<tr>
<th>Site</th>
<th>Machine</th>
<th>Project ID</th>
<th>Folder Size</th>
<th>Error Description</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysql_fetch_assoc($content_downloads)) {
$error_string = "";
if ($row["connectivityError"] == true ) {
$error_string = "COULD NOT CONNECT: " . $row["errorString"];
}
elseif ($row["blocked"] == true ) {
$error_string = "BLOCKED BY LOCK OWNED BY: " . $row["blockedBy"] . " " . $row["blockedSince"];
}
echo '
<tr>
<td>'.$row["site"].'</td>
<td>'.$row["machine"].'</td>
<td>'.$row["projectid"].'</td>
<td>'.$row["directorySize"].'</td>
<td style = "text-align: left; color: red;">'.$error_string.'</td>
</tr> ';
}
?>
</tbody>
</table>
The error description column in this table rarely has contents. As you can see, when it does, a PHP conditional function (the if and ifelse functions) places a statement before the error description to make the description more understandable. One thing you may notice is that I am coloring the text of error descriptions red. The thing that I am struggling with that I need your help on is to selectively style an entire row with a background-color of yellow, when the error description cell in that row has a value. In other words, when the two conditionals I wrote are true, I would like to make the background-color of the row that includes that error description yellow.
It seems pretty simple, but I have tried various options and can't seem to figure it out. Any tips Stack Overflow?
Check if the error string is empty:
echo '
<tr' . (empty($error_string) ? '' : ' style="background-color:yellow;"') . '>
<td>'.$row["site"].'</td>
<td>'.$row["machine"].'</td>
<td>'.$row["projectid"].'</td>
<td>'.$row["directorySize"].'</td>
<td style = "text-align: left; color: red;">'.$error_string.'</td>
</tr> ';
What I would try is setting a class on the row of interest:
<tr class="highLight">
and then use CSS to set the background color of the cells in that row:
tr.highLight td {background-color: yellow; }
Set the class attribute is your error string has content.
Try this:
if($error_string != "")
{
echo '<tr class="error-row"';
}else{
echo '<tr>';
}
echo '<td>'.$row["site"].'</td>
<td>'.$row["machine"].'</td>
<td>'.$row["projectid"].'</td>
<td>'.$row["directorySize"].'</td>
<td style = "text-align: left; color: red;">'.$error_string.'</td>
</tr> ';
and add this to your stylesheet:
.error-row{background:yellow;}
if you want less code you can use the if shorthand too like this:
echo '<tr' . ($error_string == "" ? '' : 'class="error-row"') . '>
<td>'.$row["site"].'</td>
<td>'.$row["machine"].'</td>
<td>'.$row["projectid"].'</td>
<td>'.$row["directorySize"].'</td>
<td style = "text-align: left; color: red;">'.$error_string.'</td>
</tr> ';
Ok, I figured out what to do, and I apologize for not using jQuery or class attributes. I appreciate everyones help, and am being honest when I say that everyone's comments and answers helped me figure it out. Here's the solution:
if ($error_string != ""){
echo '
<tr style = "background-color: yellow;">
<td>'.$row["site"].'</td>
<td>'.$row["machine"].'</td>
<td>'.$row["projectid"].'</td>
<td>'.$row["directorySize"].'</td>
<td style = "text-align: left; color: red;">'.$error_string.'</td>
</tr> ';
}
else {
echo '
<tr>
<td>'.$row["site"].'</td>
<td>'.$row["machine"].'</td>
<td>'.$row["projectid"].'</td>
<td>'.$row["directorySize"].'</td>
<td style = "text-align: left; color: red;">'.$error_string.'</td>
</tr> ';
}
Thanks for everyone's help!
I have a results page and I would like there to be a bit at the top of the page where it says how many results were returned. How do I do this?
My code is
<?php
if(strlen(trim($_POST['search'])) > 0) {
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
mysql_connect ("3", "", "");
mysql_select_db ("");
if (!empty($_POST["search_string"]))
{
}
$query = "SELECT name,location,msg FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result) {
while ($row = mysql_fetch_array ($result)) { ?>
<center>
<table height="20" width="968" cellpadding="0" cellspacing="0">
<tr>
<td>
<table height="20" width="223" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="#045FB4"><?php echo $row[0]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
<td>
<table height="20" width="745" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="black"><?php echo $row[1]; ?>
<?php echo $row[2]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
<td align="right">
<font face="helvetica" size="2" color="red">See More...</font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
</tr>
</table>
<?php
}
}
}
?>
</center>
THANKS!
James
If you're going to keep it to one page then mysql_num_rows() will do the trick and you're good to go. If you use pagination on the other hand, then your SELECT query will have a LIMIT clause and a second query can be constructed using COUNT(*) on the same tables with the same WHERE clause.
$total_query = "SELECT COUNT(*) FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'"
I’m not trying to compete with the other fine answers. I’m posting this as an answer because it’s too big for a comment.
Since you asked in a comment what could be done to improve your HTML, I refactored your code a bit just to illustrate some things you could do. I also included mysql_num_rows($result) mentioned by the others for the sake of completion.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample</title>
<style type="text/css">
table {
font-family: helvetica;
font-size: small;
width: 968px;
}
td {
border-bottom: 1px solid #e6e6e6;
}
.name {
color:#045FB4;
}
.msg {
color:black;
}
.more {
color:red;
}
</style>
</head>
<body>
<?php
if(strlen(trim($_POST['search'])) > 0):
$search = mysql_real_escape_string($_POST["search"]);
$searchterm = mysql_real_escape_string($_POST["searchterm"]);
mysql_connect ("localhost", "root", "");
mysql_select_db ("sample");
if (!empty($_POST["search_string"]))
{
$search_string = mysql_real_escape_string($_POST["search_string"]);
// more code here
}
$query = "SELECT name,location,msg FROM contact
WHERE name LIKE '%$search%'
AND location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result):
$num_rows = mysql_num_rows($result);
?>
<p>Found <?php echo $num_rows; ?> results.</p>
<table>
<?php
while ($row = mysql_fetch_array ($result)):
?>
<tr>
<td class="name"><?php echo $row['name']; ?></td>
<td class="msg"><?php echo $row['location'], ' ', $row['msg']; ?></td>
<td class="more">See More...</td>
</tr>
<?php
endwhile;
endif;
endif;
?>
</table>
</body>
</html>
Normally, I would put the CSS in a separate file, but this is only an example.
Some things to notice:
There’s only one table
There’s no style information in the HTML
It uses mysql_real_escape_string. Ideally you'd also want to use prepared statements, but I’ll leave that as a personal exercise for you. :)
Even this can be improved quite a bit, but it's a start.
Try using mysql_num_rows($query). I am no PHP expert but, from memory, that should do the trick. Just echo this wherever you want it.
$num_rows = mysql_num_rows($result);
Check out the documentation: http://php.net/manual/en/function.mysql-num-rows.php
Also you can use SQL_CALC_FOUND_ROWS and FOUND_ROWS():
$query = "SELECT SQL_CALC_FOUND_ROWS name,location,msg FROM contact WHERE name LIKE '%$search%' AND location LIKE '%$searchterm%'";
$result = mysql_query($query);
if ($result)
{
$rs_count = mysql_query("SELECT FOUND_ROWS();");
$counted = (int)mysql_result($rs_count, 0);
}
I know it's such a basic thing, but a Google search hasn't shown me how to re-sort the rows after clicking the th links.
I've got this:
<table border="1">
<tr>
<th>Type:</th>
<th>Description:</th>
<th>Recorded Date:</th>
<th>Added Date:</th>
</tr>
<?php
while($row = mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $row['type'] ?></td>
<td><?php echo $row['description'] ?></td>
<td><?php echo $row['recorded_date'] ?></td>
<td><?php echo $row['added_date'] ?></td>
</tr>
<br />
<?php
}
mysql_close();
?>
</table>
I need to be able to click type and sort alphabetically, and click on either Recorded Date or Added Date and sort by date. I see that I need to have the MySQL queries do this, but do I set them up as conditionals with a href tags?
The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.
The HTML would look like this:
<th>Type:</th>
<th>Description:</th>
<th>Recorded Date:</th>
<th>Added Date:</th>
And in the php code, do something like this:
<?php
$sql = "SELECT * FROM MyTable";
if ($_GET['sort'] == 'type')
{
$sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
$sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
$sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
$sql .= " ORDER BY DateAdded";
}
$>
Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;
That's actually pretty easy, here's a possible approach:
<table>
<tr>
<th>
Type:
</th>
<th>
Description:
</th>
<th>
Recorded Date:
</th>
<th>
Added Date:
</th>
</tr>
</table>
<?php
$orderBy = array('type', 'description', 'recorded_date', 'added_date');
$order = 'type';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
$order = $_GET['orderBy'];
}
$query = 'SELECT * FROM aTable ORDER BY '.$order;
// retrieve and show the data :)
?>
That'll do the trick! :)
A SIMPLE TABLE SORT PHP CODE:
(the simple table for several values processing and sorting, using this sortable.js script )
<html><head>
<script src="sorttable.js"></script>
<style>
tbody tr td {color:green;border-right:1px solid;width:200px;}
</style>
</head><body>
<?php
$First = array('a', 'b', 'c', 'd');
$Second = array('1', '2', '3', '4');
if (!empty($_POST['myFirstvalues']))
{ $First = explode("\r\n",$_POST['myFirstvalues']); $Second = explode("\r\n",$_POST['mySecondvalues']);}
?>
</br>Hi User. PUT your values</br></br>
<form action="" method="POST">
projectX</br>
<textarea cols="20" rows="20" name="myFirstvalues" style="width:200px;background:url(untitled.PNG);position:relative;top:19px;Float:left;">
<?php foreach($First as $vv) {echo $vv."\r\n";}?>
</textarea>
The due amount</br>
<textarea cols="20" rows="20" name="mySecondvalues" style="width:200px;background:url(untitled.PNG);Float:left;">
<?php foreach($Second as $vv) {echo $vv."\r\n";}?>
</textarea>
<input type="submit">
</form>
<table class="sortable" style="padding:100px 0 0 300px;">
<thead style="background-color:#999999; color:red; font-weight: bold; cursor: default; position:relative;">
<tr><th>ProjectX</th><th>Due amount</th></tr>
</thead>
<tbody>
<?php
foreach($First as $indx => $value) {
echo '<tr><td>'.$First[$indx].'</td><td>'.$Second[$indx].'</td></tr>';
}
?>
</tbody>
<tfoot><tr><td>TOTAL = <b>111111111</b></td><td>Still to spend = <b>5555555</b></td></tr></tfoot></br></br>
</table>
</body>
</html>
source: php sortable table
//this is a php file
<html>
<head>
<style>
a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
table
{
width:50%;
height:50%;
}
table,th,td
{
border:1px solid black;
}
th,td
{
text-align:center;
background-color:yellow;
}
th
{
background-color:green;
color:white;
}
</style>
<script type="text/javascript">
function working(str)
{
if (str=="")
{
document.getElementById("tump").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("tump").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsort.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body bgcolor="pink">
<form method="post">
<select name="sortitems" onchange="working(this.value)">
<option value="">Select</option>
<option value="Id">Id</option>
<option value="Name">Name</option>
<option value="Email">Email</option>
<option value="Password">Password</option>
</select>
<?php
$connect=mysql_connect("localhost","root","");
$db=mysql_select_db("test1",$connect);
$sql=mysql_query("select * from mine");
echo "<center><br><br><br><br><table id='tump' border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>";
echo "<tr>";
while ($row=mysql_fetch_array($sql))
{?>
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
}
echo "</table></center>";?>
</form>
<br>
<div id="tump"></div>
</body>
</html>
------------------------------------------------------------------------
that is another php file
<html>
<body bgcolor="pink">
<head>
<style>
a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
table
{
width:50%;
height:50%;
}
table,th,td
{
border:1px solid black;
}
th,td
{
text-align:center;
background-color:yellow;
}
th
{
background-color:green;
color:white;
}
</style>
</head>
<?php
$q=$_GET['q'];
$connect=mysql_connect("localhost","root","");
$db=mysql_select_db("test1",$connect);
$sql=mysql_query("select * from mine order by $q");
echo "<table id='tump' border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>";
echo "<tr>";
while ($row=mysql_fetch_array($sql))
{?>
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
}
echo "</table>";?>
</body>
</html>
that will sort the table using ajax
This is the most simple solution that use:
// Use this as first line upon load of page
$sort = $_GET['s'];
// Then simply sort according to that variable
$sql="SELECT * FROM tracks ORDER BY $sort";
echo '<tr>';
echo '<td>Title<td>';
echo '<td>Album<td>';
echo '<td>Artist<td>';
echo '<td>Count<td>';
echo '</tr>';
It depends on nature of your data. The answer varies based on its size and data type. I saw a lot of SQL solutions based on ORDER BY. I would like to suggest javascript alternatives.
In all answers, I don't see anyone mentioning pagination problem for your future table. Let's make it easier for you. If your table doesn't have pagination, it's more likely that a javascript solution makes everything neat and clean for you on the client side. If you think this table will explode after you put data in it, you have to think about pagination as well. (you have to go to first page every time when you change the sorting column)
Another aspect is the data type. If you use SQL you have to be careful about the type of your data and what kind of sorting suites for it. For example, if in one of your VARCHAR columns you store integer numbers, the sorting will not take their integer value into account: instead of 1, 2, 11, 22 you will get 1, 11, 2, 22.
You can find jquery plugins or standalone javascript sortable tables on google. It worth mentioning that the <table> in HTML5 has sortable attribute, but apparently it's not implemented yet.