Generate multiple tables with multiple links in each table (webpage) - javascript

I have a webpage which needs to show multiple tables in the same format, but with different numbers inside + generate appropriate links inside many of the table cells.
Design: The webpage will show 1 table for each School subject, and then the cells inside will show how different homeroom classes have been doing under their teachers guidance, using SAT scores, final exams, and attendance rates. The teacher's names and the subject names must link to another page which displays more info about that specific teacher/subject.
I used to use php to generate tables, but seeing as there needs to be links as well inside these table, and very "customized" ones at that, I'm not sure where to start. Each link is totally unique, no complete duplicates. And with say 6 subjects, and 5 teachers, there will be 36 unique links which must be generated.
Currently I have an sql table with: subject, homeroom_teacher, subject_SAT_rslt_change, sat_retake_count, Final_vs_mid, improved_students_count, attendance_rate, missing_student_count
Below, I have put an html example of the type of table I want to generate for a given subject.
<!--subjects: math, science, literature, art, history, physical education-->
<table>
<tr>
<th colspan="7"<a href="allsubjects.php?subject=math" style="color: #ffffff; text-align: center;">Math</b></th> </tr>
<tr id="tr01">
<td><b> Homeroom Teacher </b> </td>
<td><b> Subject SAT result change </b> </td>
<td><b> Retake count</b> </td>
<td><b> Finals vs midterm difference </b></td>
<td><b> Improved students count </b></td>
<td><b> Attendance rates </b></td>
<td><b> Students missing class </b></td>
</tr>
<tr>
<td><a href="xyz.php?subject=math">Mrs. Xyz </td>
<td>-1% </td>
<td>3 </td>
<td>+22% </td>
<td>2 </td>
<td>-2% </td>
<td>5 </td>
</tr>
<tr>
<td><a href="abc.php?subject=math">Mr. Abc </td>
<td>-22% </td>
<td>2 </td>
<td>+1% </td>
<td>3 </td>
<td>-6% </td>
<td>1 </td>
</tr>
<tr>
<td><a href="msa.php?subject=math">Ms. A </td>
<td>-2% </td>
<td>1 </td>
<td>+10% </td>
<td>32 </td>
<td>-2% </td>
<td>0 </td>
</tr>
</table>
php
<?php
$mysqli = new mysqli("localhost","username","password","database");
if($mysqli->connect_errno)
die("Connection failed".$mysqli->connect_error);
$query = "SELECT * FROM `table1` where subject='math';";
$query .= "SELECT * FROM `table1` where subject='literature';";
$query .= "SELECT * FROM `table1` where subject='science';";
if($mysqli->multi_query($query))
{
$i=0;
do{
$result = $mysqli->store_result();
$finfo = $result->fetch_fields();
$title = '';
$table = '';
$i=0;
foreach($finfo as $f)
{
if($i!=0)
$table = $table. "<th>".$f->name."</th>";
$i++;
}
$table = $table. "</tr>";
while($row = $result->fetch_assoc())
{
$table = $table. "<tr>";
$j=0;
foreach($row as $v)
{
if($j==0) {
$title=$v;
} else {
$table = $table. "<td>".$v."</td>";
}
$j++;
}
$table = $table. "</tr>";
}
echo "<table>";
echo "<tr><th><b>".$title."</b></th></tr>";
echo $table;
echo "</table>";
}while($mysqli->more_results() && $mysqli->next_result());
}
?>
SQL:
insert into table1('math','mrs.xyz','-1%',3,'+22%',2,'-2%',5);
I have tagged javascript and php as I need to use them, but if you know of solutions in other languages you are also welcome to post them.

use " double quote and single quote properly that's all,
$finfo = $result->fetch_fields(); *///example variable*
echo "<a hrea='".$finfo.".php'>Link text </a> ";
another way :
Link text

Related

Making The Table Count Rows

I have a table which automatically adds rows or removes them. I want to make the table to count these rows and give them number. For example;
| # | Name | Surname|
| 1 | Jake | Murray |
| 2 | Maria| Brown |
Here is my code;
Don't worry about the php code. I only need to fix the javascript. It may not work because i didn't put the php code inside the table.
var number = document.getElementById ( "nmr" ).innerText;
if (number = 1){
number = number + 1;
}
<table class="table">
<tr>
<th>#</th>
<th><b>Name</b></th>
<th><b>Email</b></th>
<th><b>The Lowest Money</b></th>
<th><b>The Most Money</b></th>
<th><b>Currency</b></th>
<th><b>Age</b></th>
<th><b>Gender</b></th>
<th><b>Hobby 1</b></th>
<th><b>Hobby 2</b></th>
<th><b>Reason</b></th>
<th><b>Favorite Color</b></th>
<th></th>
<th></th>
</tr>
<?php
require 'inc/session.ic.php';
$sql = "SELECT * FROM people WHERE username='" . $_SESSION[ "uid" ] . "'";
$res = mysqli_query( $conn, $sql );
?>
<?php
while ( $row = mysqli_fetch_assoc( $res ) ) {
$sql = "SELECT * FROM supportus WHERE emailUsers=\"" . $row["emailPerson"] ."\"";
$res2 = mysqli_query($conn, $sql);
$giftExists = mysqli_num_rows($res2) > 0;
// eger varsa, asagidaki butonu degistir.
?>
<tr>
<th id="nmr">1</th>
<td id="name"><?=$row["name"]?></td>
<td id="email"><?=$row["emailPerson"]?></td>
<td id="moneyLow"><?=$row["least"]?></td>
<td id="moneyMuch"><?=$row["much"]?></td>
<td id="currency"><?=$row["currency"]?></td>
<td id="age"><?=$row["age"]?></td>
<td id="gender"><?=$row["gender"]?></td>
<td id="hobby 1"><?=$row["likes_main"]?></td>
<td id="hobby 2"><?=$row["likes_sub"]?></td>
<td id="reason"><?=$row["reason"]?></td>
<td id="fovColor"><?=$row["color"]?></td>
<?php if ($giftExists) {?>
<td><a style="margin-top: 40px;" href="giftIdeas.php" class="btn btn-primary btn-sm active" role="button" aria-pressed="true">See Gifts??</a></td>
<?php } else {?>
<td><a style="margin-top: 40px;" href="giftIdeas.php" class="btn btn-primary btn-sm active" role="button" aria-pressed="true">See Gift Ideas</a></td>
<?php } ?>
<td><a style="margin-top: 40px;" href="2-kisi.php?deleteid=<?=$row["id"]?>" class="btn btn-primary btn-sm active" role="button" aria-pressed="true">Delete Person</a></td>
</tr>
<?php } ?>
</table>
what about something to the effect of const rows = document.querySelectorAll on the TRs and then .length will be the next number (because the tr from the head is basically the +1 you would normally do to inc the number)
It is a little unclear really what the problem actually is here - if it is to simply add a number for each row that can easily be accomplished in the PHP loop (set a variable and increment on each loop iteration.)
Further confusion because, according to the question, rows can be automatically added or removed but it is not clear how or why this happens. The javascript is incorrect and the HTML is also incorrect because of the duplicated ID attributes set on each TD ~ a better option if it is really required would be to use a dataset attribute perhaps but targeting specific elements within the DOM can be accomplished using querySelector &/or querySelectorAll
The below code uses a simple piece of Javascript ( & querySelectorAll ) to find all the relevant table cells within the table and assign an integer to each. Because of the "table which automatically adds rows or removes them" if a row were added or removed the integers would no longer be accurate - hence using the MutationObserver to monitor the DOM for changes to the table.
I hope this offers some help.
document.addEventListener('DOMContentLoaded',(e)=>{
// specifically target ALL first cells within the table and assign some content - an integer.
const callback = function() {
Array.from( document.querySelectorAll( 'tr > td:first-of-type' ) ).forEach( ( td, i )=>{
td.textContent=i + 1;
})
};
// determine what the observer will react to
const config = {
attributes:false,
childList:true,
characterData:false,
subtree:true
};
// monitor the table for changes
( new MutationObserver( callback ) ).observe( document.querySelector('table'), config );
// number the table rows at page load
callback();
// utility function to find table row
const getrow=function(e){
let n=e.target;
while(n.tagName!='TR')n=n.parentNode;
return n;
};
// a simple event listener bound to the `delete` links which will remove entire table row
// the `MutationObserver` will be triggered by a row deletion and the rows will be re-indexed
Array.from( document.querySelectorAll('td > a') ).forEach( a=>{
a.onclick=function(e){
e.preventDefault()
let tr=getrow(e);
tr.parentNode.removeChild( tr );
}
})
})
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Surname</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>fred</td>
<td>bloggs</td>
<td>Delete</td>
</tr>
<tr>
<td></td>
<td>jim</td>
<td>smith</td>
<td>Delete</td>
</tr>
<tr>
<td></td>
<td>john</td>
<td>doe</td>
<td>Delete</td>
</tr>
<tr>
<td></td>
<td>mike</td>
<td>hunt</td>
<td>Delete</td>
</tr>
</tbody>
</table>
If that has over complicated things and you simply need to display a number on each row and the table does not change after page load then either add using PHP as mentioned or you could even just use CSS

MySQL : Create table comparison product

I am confused when will display product comparison table. I have 2 tables t_product_item and t_product_specification. Here's a picture of the table structure:
I want to display a product comparison like this picture :
Script:
<table border="1">
<tr style="background-color: #C3C3C3">
<td>Product</td>
<td>Spec Name</td>
<td>Spec Value</td>
</tr>
<?php
$sql = mysqli_query($conn, "SELECT item, spec_name, spec_value FROM t_product_item JOIN t_product_specification USING (item_id)");
if (mysqli_num_rows($sql)>0){
while ($row=mysqli_fetch_array($sql)){
?>
<tr>
<td><?php echo $row['item']?>
<td><?php echo $row['spec_name']?>
<td><?php echo $row['spec_value']?>
</tr>
<?php
}}
?>
</table>
Instead it appears like this
Result:
How do I structure logically or query for the table to display like the example pic?
Change your SQL Query to:
SELECT spec_name,MAX(CASE WHEN ItemId=1 THEN spec_value END)`Samsung Galaxy S8+`
,MAX(CASE WHEN ItemId=2 THEN spec_value END)`Samsung Galaxy S8`
FROM t_product_item JOIN t_product_specification USING (item_id)
GROUP BY spec_name
ORDER BY MIN(spec_Id)
Hope this helps you.
You are looping through item_id for each of your <tr> rows. Instead you should be looping through spec_name for <tr>, and for each cell <td> loop through the product.
In pseudo code:
<table>
<thead>
<tr>
<th> </th> <!-- Empty cell for spacer -->
for (item in item_list) {
<th>item.name</th>
}
</tr>
</thead>
<tbody>
<tr>
for (spec in spec_list) {
<td>spec.name</td>
}
for (item in item_list) {
<td>item.spec[spec.name]</td> <!-- display spec detail of each item -->
}
</tr>
</tbody>
</table>
You might have to restructure your data before looping it through the table.

How To Get Hidden TD Value when i click on a TR

im trying to make a task manger based on web system that can monitor tasks at work , im using html and php .
im trying to show all the tasks in table and when i click on a task (row) i want to get a hidden td value (id of task) and send it as arg to another page for more information about the task .
i searched the web how can i do that , but i didnt realy understand how to do it with my table .
here is my table code
<table id="thickets_show">
<tr id="show_ticket_table_header">
<td>Work Week</td>
<td>Task Submited Date</td>
<td>Task Submited Time</td>
<td>Task</td>
<td>Project</td>
<td>Task Owner</td>
<td>Task Assigend to</td>
<td>Priority</td>
<td>Status</td>
<td>Task Total Work Time</td>
<td>Task Due Date</td>
<td>Task Finish Date</td>
<td>Team</td>
</tr>';
foreach ($tasks as $key => $value) {
if ($value['ticket_status']=="done")
echo '<tr id="done_ticket" >';
elseif ($value['ticket_priority']=="high")
echo '<tr id="high_ticket" class="ticket_raw">';
else
echo '<tr class="ticket_raw">';
echo '
<td>
'.$value['work_week'].'
</td>
<td>
'.$value['ticket_date'].'
</td>
<td>
'.$value['ticket_time_submit'].'
</td>
<td>
'.$value['ticket_request'].'
</td>
<td>
'.$value['ticket_project'].'
</td>
<td>
'.$value['ticket_onwer'].'
</td>
<td>
'.$value['ticket_assigned_user'].'
</td>
<td>
'.$value['ticket_priority'].'
</td>
<td>
'.$value['ticket_status'].'
</td>
<td>
'.$value['ticket_worktime'].'
</td>
<td>
'.$value['ticket_due_date'].'
</td>
<td>
'.$value['ticket_finish_date'].'
</td>
<td>
'.$value['team'].'
</td>
<td style="display:none;" id="ticket_id class="divOne">
'.$value['id'].'
</td>
</tr>
this is the function that im using
$(function(){
$(".ticket_raw" ).on(\'click\',function(e){
e.preventDefault();
var id = $(this).attr("#ticket_id");
alert(id);
});
});
There is a small issue to correct, then you can make this work nice and easily:
echo '<tr id="done_ticket" >'; is invalid - if you're creating multiple elements in a loop like this, you can't give them all the same "id", that's illegal in the HTML specification. You have to use classes instead.
Rewrite it slightly like this:
foreach ($tasks as $key => $value) {
echo '<tr data-id="'.$value['id'].'" class="ticket ';
if ($value['ticket_status']=="done")
echo 'done_ticket';
elseif ($value['ticket_priority']=="high")
echo 'high_ticket ticket_raw';
else
echo 'ticket_raw';
echo '">';
echo '
<td>
//etc...
Note the extra class "ticket" on the tr element, regardless of the status, and the "data-id" attribute containing the ID (instead of a hidden field).
Now, you can write some jQuery to get the ticket ID:
$(".ticket").click(function(event) {
var id = $(this).data("id"); //gets the data-id value from the clicked tr
window.location.href = "ticket.php?id=" + id; //example URL to redirect to, passing the ID from the tr
});
Lastly you can delete this code:
<td style="display:none;" id="ticket_id class="divOne">
'.$value['id'].'
</td>
The td has the id ticket_id, so you can use document.getElementById():
var td = document.getElementById('ticket_id');
var value = td.textContent;
Or, using jQuery:
var td = $('#ticket_id');
var value = td.text();
$('tr').on('click',function(){
var hidden_items = $(this).find('.td_hidden');
$.each(hidden_items,function(k,v){
console.log($(v).text());
})
})
html,body{
height: 100%;
margin: 0 auto;
padding: 0px;
}
td{
border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<body>
<table>
<tr>
<td>COLUMN1</td>
<td>COLUMN2</td>
<td>COLUMN3</td>
<td>COLUMN4</td>
</tr>
<tr>
<td>VALUE01</td>
<td>VALUE02</td>
<td>VALUE03</td>
<td>VALUE04</td>
<td style="display:none;" class="td_hidden">VALUE_HIDDEN_01</td>
<td style="display:none;" class="td_hidden">VALUE_HIDDEN_02</td>
</tr>
<tr>
<td>VALUE11</td>
<td>VALUE12</td>
<td>VALUE13</td>
<td>VALUE14</td>
<td style="display:none;" class="td_hidden">VALUE_HIDDEN_11</td>
<td style="display:none;" class="td_hidden">VALUE_HIDDEN_12</td>
</tr>
</table>
</body>

Get clicked href variable from one page to another

Greeting everyone,
Currently i'm making a webpage that has the following functions:
When the administrator opens the page, admin will be seeing a form filled with these information from a database:
What this page does is that it shows how many video's each user has in the database and when the admin clicks on the desired user ID, a new page should open with the video's of that specific user ID. The " DONE" button is to return to the main page when the admin is done deleting video's.
Now, what I have done is that I've assigned an href link to the userID values that is being fetched from Database. The problem is that, I have no clue how to pass the selected value/string to the next page with href. I've tried with Session, but ended up getting the last variable processed in the WHILE loop instead of getting the clicked UserID. Below follows my php code of what I've done. Can anyone give me some tips on how to pass the clicked userID from one page to another with href, or is there another way to do this?
code= click here
ps: As everyone can see, my php coding needs some serious improvement. But i'm still trying to improve by doing these types of exercises.
<?php
include_once ("includes/db_connection.php");
$sql = "SELECT Users_UserID, count(Users_UserID) AS total FROM video GROUP BY Users_UserID";
$sql2="SELECT UserID, FirstName, LastName FROM users";
$result = $connection->query($sql);
$result2 = $connection->query($sql2);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="deleteSingleVideo" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete user video</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>First Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Last Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>User ID</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Amount of videos</strong></td>
</tr>
<?php
session_start();
if ($result->num_rows > 0) {
while (($row=$result->fetch_assoc())&& ($row2=$result2->fetch_assoc()) ) {
?>
<tr>
<td align="center" bgcolor="#FFFFFF"></td>
<td bgcolor="#FFFFFF"><center><?php echo $row2['FirstName']; ?></center></td>
<td bgcolor="#FFFFFF"><?php echo $row2['LastName']; ?></td>
<td bgcolor="#FFFFFF"><center><a href="DeleteVideo.php" target="_blank"><?php echo $row['Users_UserID'];
$_SESSION['id']=$row['id'] ?></center></td>
<td bgcolor="#FFFFFF"><center><?php echo $row['total'];?></a></center></td>
</tr>
<?php
}
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="Done" type="submit" id="Done" value="Done" </td>
</tr>
<?php
$connection->close();
if(isset($_POST['Done'])){
header( "Location: Home.php" );
}
?>
</table>
</form>
</td>
</tr>
</table>
<?php
?>
this is not a good use of session
use get method to send such data :
append the id to href url --->href="<?php echo "DeleteVideo.php?id="$row['id'] ?>";
get data in the next page by accessing global variable ---> $_GET['id']
..
In the DeleteVideo.php your variable is $_GET['id']
use this code
and that id value get in xyz.php
$value=$_request['id'];
or
$value=$_Get['id'];

How to iterate changing values onkeyup using jquery?

I have a problem in my jquery/code where the id's capturing with my jquery code is an array.
Here's the snippet code.
Here's my jquery.
<script type="text/JavaScript">
$(document).ready(function()
{
$('input').keyup(function()
{
$('.total_fabi').each(function() {
var answer = parseFloat($('.req').val()) * parseInt($('.was_perc').val());
$('.total_fabi').html(answer);
});
});
});
Here's the html generated code.
<table align='center' width='100%' border='1'>
<thead style='background-color: #900; color: #FFF;'>
<th>Description</th>
<th>Estimated Cost</th>
<th>Req'd Qty</th>
<th>Wastage %</th>
<th>Total</th>
</thead>
<tbody>
<!-- This values are SQL generated inside While.. -->
<!-- Values generated by sql are under Description, Estimated Cost, Wastage-->
<!-- i Need to calculate the total using keyup by multiplying req'd qty * wastage% -->
<tr bgcolor='#FFF'>
<td>FABRICATION PER LM</td>
<td align='center'>200</td>
<td align='center'><input type='text' size='3' name='req[]' class='req'></td>
<td align='center'><input type='hidden' name='was_perc[]' value='7' class='was_perc'>7</td>
<td align='right'>
<font color='#900'>
<span id='total_fabi'>0</span>
<input type='hidden' name='total_fabi' id='total_fabi' style='border: none;' size='6' readonly='readonly'>
</font>
</td>
</tr>
<tr bgcolor='#E3E4FA'>
<td>INSTALLATION PER LM</td>
<td align='center'>200</td>
<td align='center'><input type='text' size='3' name='req[]' class='req'></td>
<td align='center'><input type='hidden' name='was_perc[]' value='15' class='was_perc'>15</td>
<td align='right'>
<font color='#900'>
<span class='total_fabi'>0</span>
<input type='hidden' name='total_fabi' id='total_fabi' style='border: none;' size='6' readonly='readonly'>
</font>
</td>
</tr>
<!-- Here's the while Ends..--->
<tr>
<td colspan='4' align='right'>Total Fabrication & Installation</td>
<td align='right'>
<!-- This part where $total+=$total_fabi -->
</td>
</tr>
</tbody>
</table>
Here's the actual PHP code.
<table align='center' width='100%' border='1'>
<thead style='background-color: #900; color: #FFF;'>
<th>Description</th>
<th>Estimated Cost</th>
<th>Req'd Qty</th>
<th>Wastage %</th>
<th>Total</th>
</thead>
<tbody>
<?php
$total_non = 0;
$sel_fabi = mysql_query("SELECT * FROM tbllabor") or die (mysql_error());
while($non = mysql_fetch_array($sel_fabi)){
$desc_fabi = $non['desc'];
$est_cost = $non['est_cost'];
$was_perc = $non['wastage_perc'];
$was_perc = $was_perc * 100;
//$total_fabi = $req * $was_perc;
echo "<tr bgcolor='".$colors[$c++ % 2]."'>";
echo " <td>$desc_fabi</td>
<td align='center'>$est_cost</td>
<td align='center'><input type='text' size='3' name='req[]' class='req'></td>
<td align='center'><input type='hidden' name='was_perc[]' value='$was_perc' class='was_perc'>$was_perc</td>
<td align='right'>
<font color='#900'>
<span class='total_fabi'>0</span>
<input type='hidden' name='total_fabi' id='total_fabi' style='border: none;' size='6' readonly='readonly'>
</font>
</td>";
echo "</tr>";
}
?>
<tr>
<td colspan='4' align='right'>Total Fabrication & Installation</td>
<td align='right'>
<input type='hidden' value='<?php echo $total_non;?>'>
<?php echo $total_non;?>
</td>
</tr>
</tbody>
</table>
.each() function is not working with me. with this kind of code i stated. do you have any other option where i should use keyup or keydown to calculate the total i needed.. Thanks in advance..
id values must be unique on the page, you can't have more than one element with the same id. That's the fundamental problem.
You can change your id values to class values instead.
It's hard to tell exactly what you're trying to do, but if the goal is to update the total_fabi element within the same row each time a req or was_perc element changes:
$(document).ready(function()
{
$('input').keyup(function()
{
// Find the row (if any) containing this input
var $tr = $(this).closest("tr");
// Find the .req, .was_perc, and .total_fabi elements *within* this row
var $req = $tr.find(".req");
var $was_perc = $tr.find(".was_perc");
var $total_fabi = $tr.find(".total_fabi");
// Do the update (probably better to use `text` than `html`)
$total_fabi.text(parseFloat($req.val()) * parseInt($was_perc.val()));
});
});
Re your comment below:
sir how would i get the total computed generated by $total_fabi for my overall total? in php its just like $total += $total_fabi.. How can i do this in jquery?
You can do that with each:
var total = 0;
$(".total_fabi").each(function() {
total += parseFloat($(this).text());
});
First of all you need to know that ID attribute must be unique and you defined same ID many time.
You can use class instead of ID attribute.

Categories

Resources