jquery tablesorter index column insert - php

I have a PHP generated table from a postgres query. How can I insert an index column with numbered rows at the beginning of the table using tablesorter plugin? The sorting works. Thank you.
klejgkekrj
qwef
<html>
<head>
<link href="/media/css/blue/style.css" rel="stylesheet">
<script src="/media/js/jquery.js" type="text/javascript"></script>
<script src="/media/js/jquery.tablesorter.js" type="text/javascript"></script>
<script src="/media/js/jquery.tablesorter.widgets.js" type="text/javascript"> </script>
<script src="/media/js/jquery.tablesorter.pager.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("#tabel").tablesorter({ widgets: [ 'zebra' , 'filter' ] })
});
</script>
</head>
<body>
<?php
$con = pg_connect("user=* password=* host=localhost port=5432 dbname=users ") or die (pg_last_error());
$query = "SELECT * from users";
$result = pg_query($con, $query);
echo "<table id=\"tabel\" class=\"tablesorter\">
<thead>
<tr>";
//next code get column names
for($i=0; $i < pg_num_fields($result); $i++){
$field_info = pg_field_name($result, $i);
echo "<th> $field_info </th>";
}
echo "
</tr>
</thead>";
//next code fetch cells content
echo "<tbody>";
while ($row=pg_fetch_row($result)){
echo "<tr>";
foreach($row as $_column){
echo "<td> $_column </td>";
}
echo "</tr>";
}
echo "</tbody>
</table>";
pg_close($con);
?>
</body>
</html>

I'm not that great with php, but couldn't you just do this?
echo "<table id=\"tabel\" class=\"tablesorter\">
<thead>
<tr>
<th>#</th>";
.
.
.
//next code fetch cells content
echo "<tbody>";
$i=1;
while ($row=pg_fetch_row($result)){
echo "<tr>";
echo "<td> $i </td>";
$i++;
foreach($row as $_column){
echo "<td> $_column </td>";
}
echo "</tr>";
}
If you want a that column to not sort and stay unchanged, you can use the following widget (demo) with header option to prevent sorting:
// target the number column using a zero-based index
var number_column = 0;
// add custom numbering widget
$.tablesorter.addWidget({
id: "numbering",
format: function(table) {
var c = table.config;
$("tr:visible", table.tBodies[0]).each(function(i) {
$(this).find('td').eq(number_column).text(i + 1);
});
}
});
$("table").tablesorter({
theme: 'blue',
// prevent first column from being sortable
headers: {
0: { sorter: false }
},
// apply custom widget
widgets: ['numbering']
});

Related

Query String PHP

I'm trying to get the Owner's details by clicking on their name from the table at the bottom.
<html>
<head>
<title>Home</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<h1>Welcome to Poppleton Dog Show! This year 50 owners entered 300 dogs in 10 events!</h1>
<?php
include './connection.php';
$sql = "SELECT owners.id AS id, owners.name AS Owner, owners.email AS Email, dogs.name AS Name, ROUND(avg(score), 1) AS avg_score, breeds.name AS breed_name, COUNT(entries.id) AS entries_count\n"
. "FROM entries\n"
. "JOIN dogs ON dogs.id = entries.dog_id\n"
. "JOIN breeds ON dogs.breed_id = breeds.id\n"
. "JOIN owners ON owners.id = dogs.owner_id\n"
. "GROUP BY dogs.id\n"
. "HAVING entries_count > 1\n"
. "ORDER BY `avg_score` DESC\n"
. "LIMIT 10";
$result = $conn->query($sql);
echo "<table '<td align='center'>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>". "" ."". $row['Owner']. "</td>";
echo "<td>". "" ."<a href= mailto:$row[Email]>$row[Email]</a></td>";
echo "<td>". "" . $row["Name"] . "</td>";
echo "<td>". "" . $row["breed_name"] . "</td>";
echo "<td>". "" . $row["avg_score"] . "</td>";
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
<!-- connection message will fade away-->
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
my $_GET method on the other page is now taking the number but it's still not displaying the owner's details and no errors or anything. I don't know what's wrong with the code. A would appreciate any advice regarding code, formatting, etc.
<html>
<head>
<title>OwnerDetail</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('co'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
<?php
require 'Navbar.php';
?>
<?php
include './connection.php';
?>
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "Data Error";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
echo " Success ";
$row = $count->fetch(PDO::FETCH_OBJ);
echo "<table>";
}
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>
";
echo "</table>";
?>
<script>
$( document ).ready( readyFn );
$(function() {
$('#echo').fadeOut(1000);
});
</script>
</body>
</html>
You really should consider doing this:
Replace the ancient jQuery
Simplify the PHP which is already producing invalid HTML
Ajax the data only
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function() {
$("#ownerTable a.owner").on("click", function(e) {
e.preventDefault(); // stop link
const ownerDetails = $.get(this.href, function(data) {
$("#output").html(data)
});
});
});
<script>
and have
<table>
<thead>
<tr>
<th>Owner</th>
<th>Email</th>
<th>Dog</th>
<th>Breed</th>
<th>Average Score</th>
</tr>
</thead>
<tbody id="ownerTable">
<? while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td>
<a class="owner" href="OwnerDetails.php?id=<?= $row['id'] ?>"><?= $row['Owner'] ?></a>
</td>
<td>
<?= $row[Email] ?>
</td>
<td>
<?= $row["Name"] ?>
</td>
<td>
<?= $row["breed_name"] ?>
</td>
<td>
<?= $row["avg_score"] ?>
</td>
</tr>
<? } ?>
</tbody>
<tbody id="output"></tbody>
</table>
where Ownerdetails.php now looks like
<?php
$id = $_GET['id']; // Collecting data from query string
if (!is_numeric($id)) { // Checking data it is a number or not
echo "<tr><td>Data Error</td></tr>";
exit;
}
$count=$dbo->prepare("SELECT * FROM owners WHERE id=:id");
$count->bindParam(":id",$id,PDO::PARAM_INT,3);
if($count->execute()){
$row = $count->fetch(PDO::FETCH_OBJ);
echo "
<tr bgcolor='#f1f1f1'><td><b>Name</b></td><td>$row->name</td></tr>
<tr><td><b>Class</b></td><td>$row->class</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Mark</b></td><td>$row->mark</td></tr>
<tr><td><b>Address</b></td><td>$row->address</td></tr>
<tr bgcolor='#f1f1f1'><td><b>Image</b></td><td>$row->img</td></tr>";
}
?>

jQuery load() not displaying echo table from php | wordpress

I'm using Wordpress and I want to display a table, which contains pictures and buttons. This table should get loaded with a jquery load() method and put the result into a div.
I get the result, which I want, but it doesn't display in the div. Just here:
here.
When I just put, for example, a H2 with text and without any php into the php file, then it gets displayed.
Script
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
jQuery(document).ready(function(){
var $id = GetURLParameter('id');
var urlGetItem = "getItems.php/?id=" + $id;
jQuery('#load_surveys').load(urlGetItem);
});
</script>
HTML
<div id="load_surveys"></div>
PHP
<?php
include_once 'db.php';
require ('../wp-blog-header.php');
global $wpdb;
global $current_user;
get_currentuserinfo();
$userId = $current_user->ID;
$id = $_GET['id'];
$result = mysqli_query($conn,"SELECT * FROM f5_users JOIN COMPARISONFOLDER ON COMPARISONFOLDER.USER_ID = f5_users.ID JOIN ITEM ON ITEM.COMPARISONFOLDER_ID LIKE COMPARISONFOLDER.COMPARISONFOLDER_ID WHERE COMPARISONFOLDER.COMPARISONFOLDER_ID LIKE $id AND f5_users.ID LIKE $userId");
echo "<table border='1'>
<tr>
<th>Item</th>
<th>Delete</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo '<td><img src="data:image/jpeg;base64,'.base64_encode($row['ITEM']).'" width="500" height="auto"/></td>';
echo "<td><button type='button' onclick='deleteItem(".$row['ITEM_ID'].", $id)'>Testing Script</button></td>";
echo "</tr>";
}
echo "</table>";
?>
What do you get if you make console.log('id',$id) and console.log('url,urlGetItem)
jQuery(document).ready(function(){
var $id = GetURLParameter('id');
console.log('id',$id);
var urlGetItem = "getItems.php/?id=" + $id;
console.log('url,urlGetItem);
jQuery('#load_surveys').load(urlGetItem);
});
PHP
$markup = "<table border='1'>
<tr>
<th>Item</th>
<th>Delete</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
$markup .= "<tr>";
$markup .='<td><img src="data:image/jpeg;base64,'.base64_encode($row['ITEM']).'" width="500" height="auto"/></td>';
e "<td><button type='button' onclick='deleteItem(".$row['ITEM_ID'].", $id)'>Testing Script</button></td>";
$markup .= "</tr>";
}
$markup .= "</table>";
echo $markup;

Get data of multiple columns from SQL Server using PHP

I am trying to select the data from SQL Server but only the columns stored in the variable SelectedColumns. This variable store the columns' names separated by comma from a drop Down list. For example : echo $SelectedColumns will display Country,Product,Date
I could create the header of the table by exploding the variable and use foreach. Now I want to get the data of these columns display it in the <tbody> </tbody>
Here is my php page :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$ser="********";
$db="********";
$user="********";
$pass="********";
$query = 'SELECT '.$_POST['selectedColumns'].' FROM ********';
$dbDB = new PDO("odbc:Driver=ODBC Driver 13 for SQL Server;Server=********,1456;Database=********;Port=1456", $user, $pass);
?>
<!DOCTYPE html>
<html>
<head>
<title>table</title>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<?php
$row = $_POST["selectedColumns"];
$rows = explode(",",$row);
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>";
echo $r;
echo "<td>";
}
echo "</tr>";
?>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
<script>
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
I was trying this solution to use foreach twice
<?php
$row = $_POST["selectedColumns"];
$rows = explode(",",$row);
foreach ($dbDB->query($query) as $dataRow) {
echo "<tr>";
foreach ($rows as $r ) {
echo "<td>" . $dataRow[$r] . "</td>"; }
echo "</tr>";
}
?>
But it's not working. Any suggestions please ? Thank you very much.

Asynchronously place data into a dynamically produced div

I have a link that sends a query string to a PHP file that returns data from a Mysql server as JSON. I want to put this JSON data into a DIV that has an ID which matches the query string sent to the PHP file.
Here is my PHP generated Link and DIV
<html>
<head>
<title>BadNoise</title>
</head>
<body>
<form action="Artisttest.php" method="post">
<fieldset>
<p> <input type="submit" value=" Search Our Artists" /> </p>
</fieldset>
</form>
<?php
$con=mysqli_connect("localhost","ee2800","secret","ee2800");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
$result = mysqli_query($con,"SELECT * FROM artist LIMIT 10");
if($_SERVER["REQUEST_METHOD"] == "POST")
echo " <h2>List of BadNoise Artists</h2>
<table border='0'>
<tr>
<th>Artist Number</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Search Songs</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['ArtistNumber'] . "</td>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo '<td> <a class="dynamic" href="test4.php?name='. urlencode($row['ArtistNumber']).'">Search Songs</a></td>';
echo "<td><div id=" . $row['ArtistNumber'] . "></div></td>";
echo "</tr>";
}
echo "</table>";
$results->close();
mysqli_close($con);
?>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="general.js"></script>
</body>
Here is the PHP file that returns the JSON data
<?php
$row = $_GET['name'];
echo $_GET['name'];
$dbs = new mysqli("localhost", "ee2800", "secret", "ee2800");
$results = $dbs->query("SELECT * FROM songs WHERE ArtistNumber = {$_GET['name']};");
$rows = array();
while ($r = mysqli_fetch_array($results))
{
$rows[] = $r;
}
echo json_encode($rows);
?>
And here is my attempt at doing this asynchronously with JS.
$(function() {
$("a.dynamic").click(function(e) {
e.preventDefault();
var destDiv = $(this).closest('tr').find('td').last().find('div[id]');
$.getJSON( this.href, function(obj){
$.each(obj, function(key, value) {
destDiv.append("<p>"+value.Title+"</p>");
});
});
});
});
I think I am on the right path but am having trouble targeting the DIV.
Is this what you meant?
</tr><tr><td>1</td><td>Steve</td><td>Perry</td><td> <a id="dynamic" href="test4.php?name=1">Search Songs</a></td></tr><td><div id=1></div></td>
Since you're adding the content on the same row where the click originated, you may not need the id of the div in order to add the content there. Using the link that was clicked determine the parent tr using .closest() the drill down to the div using .find() and .last().
And since you're likely to have multiple links I would recommend using a class .dynamic instead of an id. <td> <a class="dynamic" href="test4 ....
This should do it:
$(function() {
$("a.dynamic").click(function(e) {
e.preventDefault();
var destDiv = $(this).closest('tr').find('td').last().find('div[id]');
$.getJSON( this.href, function(obj){
$.each(obj, function(key, value) {
destDiv.append("<p>"+value.Title+"</p>");
});
});
});
});
UPDATE
The above code has been edited to include DOM ready.
Concept verification --> with DOM ready clicking a a.dynamic link does not navigate to the link.

Fixing a pagination error

I am having a problem with pagination within the tabs. In the second tab (candidate), when I press pagination 2 to navigate to the second page of the candidate table, I am returned to the first page of the contact table. If I go to the candidate tab after that I am on the right page. Where have I gone wrong?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/start/jquery-ui.css"/>
<link type ="text/css" rel ="stylesheet" href = "testData.cs"/>
<script>
$(function(){
$('#tabs1,#tabs2').tabs();
});
</script>
<head>
<title>Candidate DB</title>
</head>
<body>
<div id ="tabs1" class ="contactForm">
<ul>
<li>List of Contacts</li>
<li>List of Candidates</li>
<li>Advanced Search</li>
</ul>
<div id ="tab1" class="contact" >
<table border="1" id="contact_info">
<tr>
<th>Contact Name</th>
<th>County</th>
</tr>
<?php
$DB_NAME = "Candidate";
$DB_USER ="root";
$DB_PASSWORD ="";
$DB_HOST ="localhost";
$con=mysql_connect("$DB_HOST", "$DB_USER", "$DB_PASSWORD") or die("Could not connect to MySQL");
mysql_select_db("$DB_NAME") or die ("No Database");
echo "Connected to Candidate Database </br></hr>" ;
$per_page=5;
$pages_query= mysql_query("SELECT COUNT(contact_id) FROM contact");
$pages = ceil(mysql_result($pages_query,0)/$per_page);
$page=(isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$start=($page-1) * $per_page;
$sql=mysql_query("SELECT first_name, last_name, county from contact ORDER BY last_name ASC LIMIT $start, $per_page" );
$Fname = 'first_name';
$Lname = 'last_name';
$county = 'county';
while ( $row = mysql_fetch_object($sql)) {
echo "<tr>";
echo "<td>" . $row ->first_name . " " . $row->last_name. "</td>";
echo "<td>" . $row->county . "</td>";
echo "</tr>";
}
// close the loop
if ($pages>=1 && $page<= $pages ) {
for ($x=1; $x<=$pages; $x++)
{
echo ($x ==$page)? '<strong><a style="color:green" href="? page='.$x.'">'.$x. '</a></strong>_':''.$x. '_';
}
}
?>
</table>
</div>
<div id ="tab2" class="candidate" >
<table border="1" id="candidate_info">
<tr>
<th>Candidate Name</th>
<th>County</th>
</tr>
<?php
$per_pageR=5;
$pages_queryR= mysql_query("SELECT COUNT(candidate_id) FROM p_candidate");
$pagesR = ceil(mysql_result($pages_queryR,0)/$per_pageR);
$pageR=(isset($_GET['pageR'])) ? (int)$_GET['pageR'] : 1;
$startR=($pageR-1) * $per_pageR;
$sql2=mysql_query("SELECT R_first_name, R_last_name, R_county from p_candidate ORDER BY R_last_name ASC LIMIT $startR, $per_pageR" );
$R_name = 'R_first_name';
$R_name = 'R_last_name';
$R_county = 'R_county';
while ( $rowR = mysql_fetch_object($sql2)) {
echo "<tr>";
echo "<td>" . $rowR ->R_first_name . " " . $rowR->R_last_name. "</td>";
echo "<td>" . $rowR->R_county . "</td>";
echo "</tr>";
}
// close the loop
if ($pagesR>=1 && $pageR<= $pagesR ) {
for ($y=1; $y<=$pagesR; $y++)
{
echo ($y ==$pageR)? '<strong><a style="color:green" href="? pageR='.$y.'">'.$y. '</a></strong>_':''.$y. '_';
}
}
?>
</table>
</div>
</div>
</body>
If I understand correctly, try using the active option - http://api.jqueryui.com/tabs/#option-active - when you do .tabs() to make the candidate tab the active tab.
<script>
$(function(){
$('#tabs1,#tabs2').tabs(<?php if(isset($_GET['pageR'])) echo "{ active: 1 }"; ?>);
});
</script>
or
<script>
$(function(){
$('#tabs1,#tabs2').tabs(<?php if(isset($_GET['pageR'])) echo '"option", "active", -1'; ?>);
});
</script>
edit
You could bind the .tabs() first, and then set the active option. This should hopefully fix your formatting issue.
<script>
$(function(){
$('#tabs1,#tabs2').tabs();
<?php if(isset($_GET['pageR'])) { ?>
$('#tabs1').tabs("option", "active", -1)
<?php } ?>
});
</script>

Categories