How can I format and style the rows of data in this table where it's displaying my data?
<table class="table">
<tr bgcolor=" #b366ff">
<th>Game</th>
<th>Date</th>
<th>Score</th>
<th>Venue</th>
</tr>
<?php
$sql = "SELECT * FROM game WHERE username = '{$users}' AND savename = '{$saves}';";
$result = mysqli_query($connection, $sql);
?>
<?php
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>".$row['team']."</td>";
echo "<td>".$row['date']."</td>";
echo "<td>".$row['score']."</td>";
echo "<td>".$row['venue']."</td>";
echo "</tr>";
}
?>
using a CSS class?
<style>
.tr1{background-color:#333;}
.td1{background-color:#999;}
</style>
echo "<tr class="tr1">";
echo "<td class="td1">".$row['team']."</td>";
You can do same as you do in normal HTML, you can use
.table tr{
background-color: grey;
}
Also you can use nth child selecter to style the elements.
I am working on an update database record form. The data is fetched from db table and populated into an html table on the webpage. I am stuck now how to add another column (5th) in the table that will contains 'edit' href link for updating database script.
Like:
|Col1|Col2|Col3|Col4|Edit|
| -- | -- | -- | -- |href|
I know this is very basic question, but so far I am not able to solve it.
It will be very helpful if someone can help me to work it.
Here is my code:
<div id="update" class="col mb-4">
<?php
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width:150px;border:1px solid grey;'>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
echo "<table class='table-bordered'>";
echo "<thead class='table-dark'>";
echo "<tr><th>Col1</th><th>Col2<th>Col3</th><th>xCol4</th></tr>";
echo "</thead>";
echo "<tbody>";
try {
$stmt = $conn->prepare("SELECT Col1, Col2, Col3, Col14 FROM table");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
// $conn = null;
echo "</tbody>";
echo "</table>";
?>
</div>
Your code is very overcomplicated, which is what's making it hard to modify.
It seems like you just want to do a simple table with data from a database. You could basically just do:
<div id="update" class="col mb-4">
<table class='table-bordered'>
<thead class='table-dark'>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<?php
try {
$stmt = $conn->prepare("SELECT Col1, Col2, Col3, Col14 FROM table");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $row) {
?>
<tr>
<td style='width:150px;border:1px solid grey;'><?= $row['Col1'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col2'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col3'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col4'] ?></td>
<td style='width:150px;border:1px solid grey;'>Edit</td>
</tr>
<?php
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</tbody>
</table>
</div>
I would also recommending moving the database query away from the view into a class or something. Then the view would be much cleaner (no try/catch etc). Then all the PHP in the view would be something like:
<?php foreach ($myClass->getTheData() as $row) : ?>
<tr>
<td style='width:150px;border:1px solid grey;'><?= $row['Col1'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col2'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col3'] ?></td>
<td style='width:150px;border:1px solid grey;'><?= $row['Col4'] ?></td>
<td style='width:150px;border:1px solid grey;'>Edit</td>
</tr>
<?php endforeach ?>
Now it would be much easier to change the HTML.
I've written a bit of CSS and PHP to query a MySQL table. I also have a filter in the form of a drop down box which allows the user to choose a 'family', whether it be "capacitor", "resistor", or "ferrite bead" (I've included pictures below of what this looks like).
My question is this: how can I create a sorting system for the elements once they have been filtered by family? That is, if I wanted to query the table from MySQL corresponding to ASC values of "voltage" for example, how would I go about this? I need to retain the filter when the sorting method is selected. I have included my code so far below the images. Thanks for the help!
(Below: 1, full table is loaded : 2, only family entries that match "capacitor" are loaded)
CODE: (File name, index.php)
<html>
<form action="index.php" method="post">
<select name="family">
<option value="" selected="selected">Any family</option>
<option value="capacitor">capacitor</option>
<option value="resistor">resistor</option>
<option value="ferrite bead">ferrite bead</option>
</select>
<input name="search" type="submit" value="Search"/>
</form>
<head>
<meta charset = "UTF-8">
<title>test.php</title>
<style>
table {
border-collapse: collapse;
width: 50%;
}
th, td {
input: "text";
text-align: left;
padding: 8px;
}
th {
background-color: SkyBlue;
}
tr:nth-child(odd) {background-color: #f2f2f2;}
tr:hover {background-color: AliceBlue;}
</style>
</head>
<body>
<p>
<?php
$family = "";
if(isset($_POST['family'])) {
$family = $_POST['family'];
}
try {
$con= new PDO('mysql:host=localhost;dbname=mysql', "root", "kelly188");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(!empty($family)) {
$query = 'SELECT * FROM testv2 WHERE family = "'.$family.'"';
}
else {
$query = "SELECT * FROM testv2";
}
//first pass just gets the column names
print "<table>";
$result = $con->query($query);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print " <tr>";
foreach ($row as $field => $value){
print " <th>$field</th>";
}
// end foreach
print " </tr>";
//second query gets the data
$data = $con->query($query);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr>";
foreach ($row as $name=>$value){
print " <td>$value</td>";
} //end field loop
print " </tr>";
} //end record loop
print "</table>";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
} // end try
?>
</p>
</body>
</html>
Datatables https://datatables.net/ is really cool too. The normal functioning is using JavaScript, but you can configure it to use server resources and process the date on server and just display the results. Once you get the hang of it it's pretty easy.
Each time you either order or filter the data, datatable sends an array with all the info necessary so you just scan the array and generate your queries accordingly.
You can add a sorting dropdown list in your form and use it in your query. This way you can let the user choose a sorting method and handle it server-side.
<form action="index.php" method="post">
<select name="family">
<option value="" selected="selected">Any family</option>
<option value="capacitor">capacitor</option>
<option value="resistor">resistor</option>
<option value="ferrite bead">ferrite bead</option>
</select>
<select name="sort">
<option value="" selected="selected">Any Order</option>
<option value="ASC">Ascending</option>
<option value="DESC">Descending</option>
</select>
<input name="search" type="submit" value="Search"/>
</form>
In PHP:
<?php
$family = "";
$sort = "";
if(isset($_POST['family'])) {
$family = $_POST['family'];
}
In your if Statement:
if(!empty($family)) {
$query = 'SELECT * FROM testv2 WHERE family = "'.$family.'" ORDER BY "'.$sort'"';
}
else {
$query = "SELECT * FROM testv2";
}
If you don't want to use a dedicated table sorting library, you should be able to do this yourself. Here is a solution that pulls all data from a provided array of data which you should be able to provide easily using PHP.
// Initially populate the table
populateTable(data);
// Listen for a click on a sort button
$('.sort').on('click', function() {
// Get the key based on the value of the button
var key = $(this).html();
// Sort the data and update our data
data = sortBy(data, key);
// Fill the table with our data
populateTable(data);
});
// Modified from: https://www.sitepoint.com/sort-array-index/
function sortBy(inputData, key) {
// Sort our data based on the given key
inputData.sort(function(a, b) {
var aVal = a[key],
bVal = b[key];
if (aVal == bVal) return 0;
return aVal > bVal ? 1 : -1;
});
return inputData;
}
// Modified from: https://stackoverflow.com/questions/5361810/fast-way-to-dynamically-fill-table-with-data-from-json-in-javascript
function populateTable(inputData) {
var keys = new Array(),
i = -1;
// Create an array of keys
$.each(inputData[0], function(key, value) {
keys[++i] = key;
});
var r = new Array(),
j = -1;
// Populate the table headers
r[++j] = '<tr>';
$.each(keys, function(key, value) {
r[++j] = '<th>' + keys[key] + '</th>';
});
r[++j] = '</tr>';
for (var index = 0, size = inputData.length; index < size; index++) {
// Populate the table values
r[++j] = '<tr>';
$.each(keys, function(key, value) {
r[++j] = '<td>' + inputData[index][value] + '</td>';
});
r[++j] = '</tr>';
}
// Join everything together
$('#data-table').html(r.join(''));
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
text-align: left;
padding: 8px;
}
th {
background-color: skyblue;
}
tr:nth-child(odd) {
background-color: #f2f2f2;
}
tr:hover {
background-color: aliceblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// Set our data
var data = [{
ID: 1,
Family: 'resistor',
Capacitance: 7,
Voltage: 6,
Price: 25.6
},
{
ID: 2,
Family: 'capacitor',
Capacitance: 10,
Voltage: 10,
Price: 100.2
},
{
ID: 3,
Family: 'ferrite bead',
Capacitance: 1,
Voltage: 5,
Price: 35.6
},
{
ID: 4,
Family: 'resistor',
Capacitance: 1,
Voltage: 4,
Price: 35.6
},
{
ID: 5,
Family: 'capacitor',
Capacitance: 9,
Voltage: 4,
Price: 25.6
}
];
</script>
<table id="data-table"></table>
<p>Sort by:</p>
<button class="sort">ID</button>
<button class="sort">Family</button>
<button class="sort">Capacitance</button>
<button class="sort">Voltage</button>
<button class="sort">Price</button>
You could keep the $_POST['family'] in a hidden field (maybe $_POST['hidden_family']). When you do your next level search you can check for it and append that to your search each time if it is not blank.
Here's how you numerically sort your table :
1) give the intended table an ID (in my code case it's main-table)
2) Call the sorting function everytime you click on the table headers (including the column number, first one is 0, everytime you add more columns increase the number inside the function name by one, in this case sortTable(0),sortTable(1),....
The final result will be something like this (test this example, it works):
<table id="main-table">
<tr>
<th style="cursor:pointer" onclick="sortTable(0)">colomn 0</th>
<th style="cursor:pointer" onclick="sortTable(1)">colomn 1</th>
<th style="cursor:pointer" onclick="sortTable(2)">colomn 2</th>
<th style="cursor:pointer" onclick="sortTable(3)">colomn 3</th>
<th style="cursor:pointer" onclick="sortTable(4)">colomn 4</th>
</tr>
<tr>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
</tr>
<tr>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
</tr>
<tr>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
</tr>
<tr>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
</tr>
<tr>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
<td><?php echo rand(0,999);?></td>
</tr>
</table>
<script>
function sortTable(column) {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("main-table");
switching = true;
while (switching) {
switching = false;
rows = table.getElementsByTagName("TR");
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[column];
y = rows[i + 1].getElementsByTagName("TD")[column];
if (Number(x.innerHTML) > Number(y.innerHTML)) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}
</script>
And here's what you need to do to generate the number of the column :
$counter = 0;
foreach ($row as $field => $value){
print " <th onclick='sortTable($counter)'>$field</th>";
$counter = $counter+1;
}
I have a problem in inserting table from my database to div.
html code:
<div class="content">
<?php
$query = "SELECT name, surname FROM players";
$response = #mysqli_query($dbc, $query);
if($response) {
echo' <table align="left"
cellspacing="5" cellpadding="8" >
<tr><td align="left"><b>First Name</b></td>
<td align="left"><b>Last Name</b></td></tr>';
while($row = mysqli_fetch_array($response)) {
echo '<tr><td align="left">' .
$row['imie'] . '</td><td align="left">' .
$row['nazwisko'] . '</td><td align="left">';
echo '</tr>';
}
echo '</table>';
} else {
echo "Couldn't issue database query";
echo mysqli_error($dbc);
}
mysqli_close($dbc);
?>
</div>
css code:
.content {
width: 1000px;
margin-left: auto;
margin-right: auto;
background-color: #ffffff;
color: #000000;
border-bottom: 14px solid #333333;}
Is there a way to insert this table to this div? Because when I'm loading this, the table is under my div'content'. The table should be in blank field 'a'.
Screenshot
Correctly indenting your code would have allowed you o spot the error relatively easily - there is an open td element. Either remove the last td from the echo statement in the loop or add additional td pair to first row in table so that they balance ( unless you use colspan attributes )
<style>
.content table tr td{ align:left;padding:5px;color:black;background:white; }
</style>
<div class='content'>
<?php
$sql = 'select `name`, `surname` from `players`';
$response = mysqli_query( $dbc, $sql );
if( $response ) {
echo "
<table align='left' cellspacing='5' cellpadding='8' >
<tr>
<td><b>First Name</b></td>
<td><b>Last Name</b></td>
</tr>";
while( $row = mysqli_fetch_array( $response ) ) {
echo "
<tr>
<td>{$row['imie']}</td>
<td>{$row['nazwisko']}</td>
</tr>";
}
echo "
</table>";
} else {
printf( 'Couldn\'t issue database query: %s', mysqli_error( $dbc ) );
}
mysqli_close( $dbc );
?>
</div>
There is an open <td> tag in your code you should close it before closing the <tr>
I want to display the data loaded from database after it is inserted using the function add_data() but it's not displaying the data on the table.
if(isset($_POST['btn_add_details'])) {
add_data();
include("db_PSIS.php");
$sql2="SELECT * FROM sample_barcode WHERE IDRec='".$row['IDRec']."'";
$result2=mysql_query($sql2);
if(!$result2) {
echo "<h1>Could not process query this time. Please try again later!</h1>";
}
else {
while($row2=mysql_fetch_array($result2)) {
echo "<form name='form2' method='POST'>";
echo "<table class='output' border=2 align=center>";
echo "<tr class='thcolor'>";
echo "<th>Parent</th>";
echo "<th>LOT Traveller No.</th>";
echo "<th>Datecode</th>";
echo "</tr>";
echo "<tr>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['Datecode']."</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
echo "<br><h1>Data successfully loaded!</h1>";
}
mysql_close($link);
}
?>
Here's the function for adding data on the database:
function add_data() {
include("db_PSIS.php");
$sql="INSERT INTO sample_barcode (LotTraveller, ShipmentLotNumber) VALUES ('".$_POST['traveller']."', '".$_POST['datecode']."')";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
mysql_close($link);
}
Here's the code for database connection:
<?php
$username="****";
$password="****";
$database="****";
$hostname="****";
$link=#mysql_connect($hostname,$username,$password)
or die ("...cannot connect database, using $username for $hostname");
mysql_query("set names 'utf8'"); //指定数据库字符集
mysql_select_db($database,$link);
?>
Here's the form input:
<table width="500" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<tr>
<th align="right">Parent Traveller: </th>
<td><input type="text" name="traveller" size="20" value="<?php if(empty($_POST['traveller'])) {echo ''; } else { echo $row2['LotTraveller']; } ?>"/></td>
</tr>
<tr>
<th align="right">Date Code: </th>
<td><input type="text" name="datecode" size="20" value="<?php if(empty($_POST['traveller'])) {echo ''; } else { echo $row2['ShipmentLotNumber']; } ?>" /></td>
</tr>
<tr>
<th align="right">Traveller 1: </th>
<td><input type="text" name="traveller1" size="20" /></td>
</tr>
<tr>
<th align="right">Date Code: </th>
<td><input type="text" name="datecode1" size="20" /></td>
</tr>
<tr>
<th align="right">Traveller 2: </th>
<td><input type="text" name="traveller2" size="20" /></td>
</tr>
<tr>
<th align="right">Date Code: </th>
<td><input type="text" name="datecode2" size="20" /></td>
</tr>
<tr>
<th align="right"> </th>
<td><input type="hidden" name="id" size="20" value="<?php if(empty($_POST['traveller'])) {echo ''; } else {echo $row2['IDRec'];} ?>"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="btn_add_details" id="btn_add_details" onClick="return check_submit();" value="Add the Detail(s)" onfocus="setStyle(this.id)"
style="color: #000000;
padding: 2px 5px;
border: 2px solid;
border-color: #7bf #07c #07c #4AA02C;
background-color: #09f;
font-family: Georgia, ..., serif;
font-size: 18px;
display: block;
height: 30px;
width: 200px;" /> </td>
</tr>
</table>
Since you stated that IDRec is your PK and is set to auto-increment, AND you are pulling records based on a single number... you will never get more than one result in your resultset.
Change this code block...
$sql2="SELECT * FROM sample_barcode WHERE IDRec='".$row['IDRec']."'";
$result2=mysql_query($sql2);
if(!$result2) {
echo "<h1>Could not process query this time. Please try again later!</h1>";
}
else {
while($row2=mysql_fetch_array($result2)) {
echo "<form name='form2' method='POST'>";
echo "<table class='output' border=2 align=center>";
echo "<tr class='thcolor'>";
echo "<th>Parent</th>";
echo "<th>LOT Traveller No.</th>";
echo "<th>Datecode</th>";
echo "</tr>";
echo "<tr>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['Datecode']."</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
echo "<br><h1>Data successfully loaded!</h1>";
}
mysql_close($link);
}
To this...
$sql2="SELECT * FROM sample_barcode WHERE IDRec=".$row['IDRec']."";
$result2=mysql_query($sql2);
$row2=mysql_fetch_assoc($result2); // added this line
if(!$result2) {
echo "<h1>Could not process query this time. Please try again later!</h1>";
}
else {
echo "<form name='form2' method='POST'>";
echo "<table class='output' border=2 align=center>";
echo "<tr class='thcolor'>";
echo "<th>Parent</th>";
echo "<th>LOT Traveller No.</th>";
echo "<th>Datecode</th>";
echo "</tr>";
echo "<tr>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['LotTraveller']."</td>";
echo "<td>".$row2['Datecode']."</td>";
echo "</tr>";
echo "</table>";
echo "</form>";
echo "<br><h1>Data successfully loaded!</h1>";
}
mysql_close($link);
}
In the first line I removed the single quotes around your IDRec - this is an integer so single quotes are not needed.
Removed your while loop - you will only ever get one result so a loop is not needed.
Also, this doesn't appear to actually be a form so you can also remove your <form> </form> tags.
Finally, start learning pdo_mysql. my_sql has been deprecated. Anyone still using this code will wake up one day to find out that their website has magically stopped functioning.
EDIT
In your add_data function, change it to this...
function add_data() {
include("db_PSIS.php");
$sql="INSERT INTO sample_barcode (LotTraveller, ShipmentLotNumber) VALUES ('".$_POST['traveller']."', '".$_POST['datecode']."')";
$result=mysql_query($sql);
$sql="SELECT * FROM sample_barcode ORDER BY IDRec DESC"; // added this line
$result=mysql_query($sql); // added this line
$row=mysql_fetch_assoc($result); // changed this line from array to assoc
mysql_close($link);
}
This will get the result of the data you just entered. I added a query to get the data you need to display.