MySQL : Create table comparison product - javascript

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.

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

how to implement bootstrap when printing <div> Containing another hidden <div> with javascript

like i mention in the title i have a problem when i want to print a div> Containing another hidden div with javaScript the bootstrap styling gone
before pushing the print botton
after pushing the print botton
<script type="text/JavaScript">
function myPrint() {
var myPrintContent = document.getElementById('table');
var myPrintWindow = window.open('','','');
myPrintWindow.document.write(myPrintContent.innerHTML);
myPrintWindow.document.getElementById('hidden_div').style.display='block';
myPrintWindow.document.close();
myPrintWindow.focus();
myPrintWindow.print();
return false;
}
</script>
<div id=table>
<table class="table table-hover">
<div style="display: none;" id="hidden_div">
<h1>hi</h1>
</div>
<thead class="table-primary">
<tr>
<th scope="col">#</th>
<th scope="col">Nom Article</th>
<th scope="col">CIN du responsable</th>
<th scope="col">Date</th>
<th scope="col">Quantite</th>
<th class="text-center" scope="col" colspan="2" width="1%">Options</th>
</tr>
</thead>
<tbody class="table-light">
<?php while($donnees = mysqli_fetch_array($reponse3)){
$donnees1=mysqli_fetch_array(mysqli_query($con,"select NOM_ARTICLE from article where ID_ARTICLE = $donnees[1]"));
$login_cin=mysqli_fetch_array(mysqli_query($con,"select CIN from utilisateurs where ID_LOGIN = $donnees[2]"));
?>
<tr>
<th scope="row"><?php echo $donnees[0];?></th>
<td><?php echo $donnees1[0]; ?></td>
<td><?php echo $login_cin[0]; ?></td>
<td><?php echo $donnees[3]; ?></td>
<td><?php echo $donnees[4]; ?></td>
<td><img src="res\images\edit-icon.svg" height="30x" title="modifier"></td>
<td><a onclick="supprimer(<?php echo $donnees[0]; ?>)" href="#"><img src="res\images\delete-icon.svg" height="30x" title="supprimer"></a></td>
</tr>
<?php
}?>
</tbody>
</table></div>
Please move the hidden_div out from the table.
<div id="table">
<div style="display: none;" id="hidden_div">
<h1>hi</h1>
</div>
<table class="table table-hover">
<thead class="table-primary">
......
You can at least write the correct markup into the window you're opening, then provide the link to your CSS file (note that you'll need to put in the full URL):
<script>
function myPrint() {
var myPrintContent = document.getElementById('table');
var myPrintWindow = window.open('','','');
myPrintWindow.document.write('<html><head>');
myPrintWindow.document.write('<link rel="stylesheet" href="http://www.yourdomain.com/your/bootstrap/css/path/your-bootstrap-theme.css">');
myPrintWindow.document.write('</head><body>');
myPrintWindow.document.write(myPrintContent.innerHTML);
myPrintWindow.document.write('</body></html>');
myPrintWindow.document.getElementById('hidden_div').style.display = 'block';
myPrintWindow.document.close();
myPrintWindow.focus();
myPrintWindow.print();
return false;
}
</script>
Admittedly this is not the best way to print a webpage. As mentioned by #BenRondeau using #media print (learn more about media query here) to define a style specifically for printing is the appropriate method. Your current method might work, yes, but learn to do things the right way is always more beneficial in the long run.
With Bootstrap data tables, you need to use table-row instead of 'block'
This has been an issue I have experienced in the past, and that fixed it.
myPrintWindow.document.getElementById('hidden_div').style.display='table-row';

Not able to expand and collapse child row

I am using basic datatable to print dynamic values that are received from the back end. I also have a hidden child row for each row with some additional values of that parent row. There is a button in each parent row and I want that on click of that link the child of that parent row should expand and be visible to the user. This should happen for every row.Here is the fiddle
However, when I am clicking on that button, the child row is not opening. Can anyone please help me with the solution
$('table').on('click', 'tr.parent .det', function() {
$(this).closest('tr.cchild').toggleClass('open');
});
.cchild {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Location</th>
<th>Experience</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($per_job as $job): ?>
<tr class="parent">
<td>
<?php echo $job->name; ?>
</td>
<td>
<?php echo $job->location; ?>
</td>
<td>
<?php echo $job->experience; ?>
</td>
<td>
<button class="show-btn rd-details det">
DETAILS
</button>
</td>
</tr>
<tr class="cchild">
<td>
<?php echo $job->age; ?>
</td>
<td>
<?php echo $job->class; ?>
</td>
<td>
<?php echo $job->address; ?>
</td>
<td>
<?php echo $job->number; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
As far I see you have not defined the class open anywhere, so just define the class in existing CSS.
.open{
display:block !important;
}
The display property specifies if/how an element is displayed.
Every HTML element has a default display value depending on what type of element it is. The default display value for most elements is block or inline. When you declare an object to have display none as you have done using your CSS for cchild the code hides the object.
Now to show your object you can either remove your existing class or override the existing class by using another class or style. To do so you are using toggling the class open which should have display 'block'. In simple language, you are showing and hiding the object. More info can be found here.

table pagination without reload the page -Bootstrap-

I have a table fetching its data from database
I want to make pagination for table but without refreshing the page
my table code:
<?php
<table id="table2" class="table table-hover table-mc-light-blue ">
<thead>
<tr>
<th>#</th>
<th>اسم المطرب</th>
<th>عدد الاغاني</th>
<th>تعديل</th>
</tr>
</thead>
<tbody class="searchable" >
<?php
$artistquery= mysqli_query($conn,"SELECT * FROM `artist` ORDER BY `artistID` DESC ");
$num=1;
$x=0;
while($listartist = mysqli_fetch_assoc($artistquery)){
$songquery= mysqli_query($conn,"SELECT * FROM `songs` WHERE `artist` = '$listartist[artistname]' ");
$songsnumber = mysqli_num_rows($songquery);
$x+=0.1;
echo'
<tr class="animated bounceIn " style=" animation-delay:'.$x.'s;">
<td data-title="#"></td>
<td data-title="اسم المطرب"></td>
<td data-title="عدد الاغاني"></td>
<td data-title=""></td>
</tr> ';}
?>
NOTE: I tried DataTables.js but i did know how to remove the filter and show labels.
is there any different way to do it ?
I dont fully comprehend your query so I'll stick to the pagination. Lets Say you want to show 10 items at a time and you are using next and prev as pagination buttons, you can render the first view using LIMIT 10 in your query or using array_slice($mysql_result,0,10). I have this downloaded json files containing zips (countries and code), that is what I used to test it. the next and prev totally perfect but it works.
<?php
$mysql_result = (array) json_decode(file_get_contents('zips'));
if(isset($_GET['ajax'])){
header('content-type: application/json');
$_GET['offset'] = isset($_GET['offset'])?$_GET['offset']:0;
echo json_encode(array_slice($mysql_result,$_GET['offset'],10));
exit;
}
$ar = array_slice($mysql_result,0,10);//or add LIMIT 10 in sql query
?>
<table border="on" width="100%">
<tbody id="songartiststuff">
<?php foreach($ar as $k => $r)://initial render?>
<tr>
<td data-replace="code"><?=$r->code?></td>
<td data-replace="country"><?=$r->country?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<center>
<button data-next="10">Next</button>
<button data-prev="0">Prev</button>
</center>
<script src="jquery.js"></script>
<?php
$mysql_result = (array) json_decode(file_get_contents('zips'));
if(isset($_GET['ajax'])){
header('content-type: application/json');
$_GET['offset'] = isset($_GET['offset'])?$_GET['offset']:0;
echo json_encode(array_slice($mysql_result,$_GET['offset'],10));
exit;
}
$ar = array_slice($mysql_result,0,10);//or add LIMIT 10 in sql query
?>
<table border="on" width="100%">
<tbody id="songartiststuff">
<?php foreach($ar as $k => $r)://initial render?>
<tr>
<td data-replace="code"><?=$r->code?></td>
<td data-replace="country"><?=$r->country?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<center>
<button data-next="10">Next</button>
<button data-prev="0">Prev</button>
</center>
<script src="jquery.js"></script>
<script>
$(()=>{
document.querySelector('[data-next]').addEventListener('click',function(){
move(this.dataset.next);
console.log(this.dataset.next);
this.setAttribute('data-next',parseInt(this.dataset.next) + 10);//add to next
var prv = document.querySelector('[data-prev]');
prv.setAttribute('data-prev',parseInt(prv.dataset.prev) + 10);//add to prev
})
document.querySelector('[data-prev]').addEventListener('click',function(){
move(this.dataset.prev);
console.log(this.dataset.prev);
this.setAttribute('data-prev',parseInt(this.dataset.prev) - 10);// remove form next
var nxt = document.querySelector('[data-next]');
nxt.setAttribute('data-next',parseInt(nxt.dataset.next) - 10);//remove from prev
})
function move(int){
var template = document.querySelector('tbody tr').cloneNode(true);//get a sample from tbody
$.get('table.php?ajax=true&offset='+int).success(function(data){
$(document.querySelector('tbody')).empty();
$.each(data,function(i,v){
let tp = tmp.cloneNode(true);//clone the template
tp.querySelector("[data-replace='code']").innerHTML = v.code;//replace code
tp.querySelector("[data-replace='country']").innerHTML = v.country;//replace country
document.querySelector('tbody').appendChild(tp);//append to tbody
})
});
}
});
</script>

Cannot add DataTables.net javascript to Joomla 1.5

I'm having a problem here where I could not run DataTables.net javascripts on Joomla 1.5. The script is as what it is on DataTables
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready( function () {
var table = $('#example').DataTable();
} );
</script>
To say that it is Joomla stripping off my code, I managed to run Google Chart API javascript without any problems. Any experts here mind sharing why this is happening?
UPDATED:
Below is my code :
<?php
$doc = JFactory::getDocument();
$doc->addScript('http://code.jquery.com/jquery-1.11.0.min.js');
$doc->addScript('http://datatables.net/download/build/nightly/jquery.dataTables.js');
$doc->addScriptDeclaration('
$(document).ready( function () {
$("#example").DataTable();
});
');
function listProcess($process,$date_sort)
{
$asas= new class_asas;
$sql = "
Select proses_pendaftaran.*, secretary.*,
kpps_agih.name as kpps_agih_name,
kpps_sokong.name as kpps_sokong_name,
ppps.name as ppps_name,
tps.name as tps_name,
pjs.name as pjs_name,
pt.name as pt_name
From proses_pendaftaran
Left join jos_users secretary On secretary.id=proses_pendaftaran.user_id
Left join jos_users kpps_agih On kpps_agih.id=proses_pendaftaran.kpps_agih_id
Left join jos_users kpps_sokong On kpps_sokong.id=proses_pendaftaran.kpps_sokong_id
Left join jos_users ppps On ppps.id=proses_pendaftaran.ppps_semak_id
Left join jos_users tps On tps.id=proses_pendaftaran.tps_perakui_id
Left join jos_users pjs On pjs.id=proses_pendaftaran.pjs_lulus_id
Left join jos_users pt On ppps.id=proses_pendaftaran.pt_rekod_id
Where current_process='$process'
Order By $date_sort DESC";
//echo $sql;
return $asas->readAll($sql);
}
$userm = $asas->getUser();
$userid = $user->get('id');
$userm=$asas->getOtherUser($userid);
$usergroup = $userm['user_group_id'];
//---------------------------------------------------------------------------------------------------------------
//PJS, TPS, KPPS
if($usergroup ==7 or $usergroup ==2 or $usergroup ==3 or $usergroup ==4 or $usergroup ==5)
{
$datas=listProcess('ppps_semak','kpps_agih_date');
?>
<h1 class="contentheading">Senarai Permohonan Yang Telah Diagihkan (Menunggu Tindakan PPPS/PPPS(P))</h1>
<table id ="example" width="100%" class="systemTable">
<thead>
<tr>
<th width="20%">NAMA BADAN SUKAN</th>
<th width="10%">NAMA PEMOHON</th>
<th width="10%">TARIKH PERMOHONAN</th>
<th width="10%">PEGAWAI KPPS</th>
<th width="15%">TARIKH DIAGIHKAN</th>
<th width="10%">PEGAWAI PPPS</th>
<th width="10%">STATUS</th>
</tr>
</thead>
<?php
foreach($datas as $data)
{
?>
<tr>
<td><?php echo strtoupper($data['NamaBadan']) ?></td>
<td><?php echo strtoupper($data['name']) ?><br/>[<?php echo $data['TelPejabat'] ?>]</td>
<td><?php echo date('d/m/Y',strtotime($data['tarikh_mohon'])) ?></td>
<td><?php echo strtoupper($data['kpps_agih_name']) ?></t>
<td><?php echo date('d/m/Y (h:ia)',strtotime($data['kpps_agih_date'])) ?></td>
<td><?php echo strtoupper($data['ppps_name']) ?></t>
<td><?php echo strtoupper($data['current_process']) ?></t>
</tr>
<?php
}
?>
</table>
<br/>
<?php
}
?>
Try using the following to import the scripts and add your custom code:
$doc = JFactory::getDocument();
$doc->addScript('http://code.jquery.com/jquery-1.11.0.min.js');
$doc->addScript('http://datatables.net/download/build/nightly/jquery.dataTables.js');
$doc->addScriptDeclaration('
$(document).ready( function () {
$("#example").DataTable();
});
');
HTML:
<table id="example">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>etc</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
<td>etc</td>
</tr>
<tr>
<td>Row 2 Data 1</td>
<td>Row 2 Data 2</td>
<td>etc</td>
</tr>
</tbody>
</table>
I have tested this myself a couple of minutes ago and it works perfectly for me. Please copy and paste the script (a few changes made) and HTML I have provided.
First of all, since you are in a Joomla environment there will a conflict between mootools and jquery, so you cannot use
$(document).ready( function () { $("#example").DataTable(); });
but instead
jQuery.noConflict();
jQuery(document).ready( function () { jQuery("#example").DataTable(); });
in other words, you cannot use $ when mootools library is present.
You may also consider using Tabulizer for Joomla (http://www.tabulizer.com) that has all the datatables functionality without the hassle.

Categories

Resources