Can each row in an HTML table be numbered? - php

What I would like to do is number each row in my table. I can't manually number the table myself, as all of the info in it is retrieved from a database. Is this possible with jQuery or PHP? Here's a screen shot of the table:
I tried searching for this, and did not find anything that helped me.
Here is the PHP / HTML that is displaying the table:
<tr>
<th>Name</th>
<th>Email</th>
<th>Subject</th>
<th>Created on</th>
<th style="width:65px;">Status</th>
<th>Actions</th>
</tr>
<?php
[...]
//Display the results
while($info = mysql_fetch_assoc($result)){
//data
$name = $info['name'];
$email = $info['email'];
$subject = $info['subject'];
$ticketid = $info['ticket'];
$isActive = $info['is_active'];
$created = $info['created'];
//status
if($isActive == "1") {
$status = "<span class=\"open\">Open</span>";
$status2 = "active";
}
else if($isActive == "0") {
$status = "<span class=\"closed\">Closed</span>";
$status2 = "closed";
}
else {
$status = "";
}
echo "
<tr>
<td style=\"min-width: 87px;\">$name</td>
<td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td>
<td title=\"$subject\">".addEllipsis($subject, 18)."</td>
<td style=\"width: 235px;\">$created</td>
<td title=\"This ticket is $status2\">$status</td>
<td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket »</a></td>
</tr>
";
}
As you can see, it's displayed with a while loop.
If anyone knows a way to number each line in my table with jQuery or PHP, please help me :)

$trCounter=0;
while($info = mysql_fetch_assoc($result)){
//data
$name = $info['name'];
$email = $info['email'];
$subject = $info['subject'];
$ticketid = $info['ticket'];
$isActive = $info['is_active'];
$created = $info['created'];
//status
if($isActive == "1") {
$status = "<span class=\"open\">Open</span>";
$status2 = "active";
}
else if($isActive == "0") {
$status = "<span class=\"closed\">Closed</span>";
$status2 = "closed";
}
else {
$status = "";
}
echo "
<tr>
<td>$trCounter++</td>
<td style=\"min-width: 87px;\">$name</td>
<td style=\"min-width:248px;\" title=\"$email\">".addEllipsis($email, 33)."</td>
<td title=\"$subject\">".addEllipsis($subject, 18)."</td>
<td style=\"width: 235px;\">$created</td>
<td title=\"This ticket is $status2\">$status</td>
<td><a href='/employee/employee.php?ticket=$ticketid'>View Ticket »</a></td>
</tr>
";
}
or you could always use the :eq api in your jquery selector or its equivalent to work with the index but like I asked it depends on what you want to do with the index.

I would go with PHP solution listed by Atul Gupta.
To add more - you also can to start iteration based on which page you are.
<?php
$i = ($page-1) * $itemsPerPage;
while(....)
{
echo $i;
$i++;
}
?>
if you are on the second page of your list would get something like 11,12,13,14,....

jQuery:
$(function () {
var i = 0;
$('table thead tr').prepend('<th>#</th>');
$('table tbody tr').each(function () {
i += 1;
$(this).prepend('<td>' + i + '</td>');
});
});

PHP
<tr>
<th>Sr. No</th> // Add header for counter
<th>Name</th>
...
</tr>
...
$i=1; // add counter -----------corrected-------------
while($info = mysql_fetch_assoc($result)){
//data
...
echo "
<tr>
<td>$i</td> // include counter to table
<td style=\"min-width: 87px;\">$name</td>
...
</tr>
";
$i++; // increment counter
}

Set an auto increment property in the SQL table, which can be used as an index, and will increase automatically when a new entry is added?

Related

find an element with jquery

i have this table wrote in html with php and bootstrap:
<table id="tabela-resultado" class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>Nome</th>
<th>Ativo</th>
<th class="text-center">Ação</th>
</tr>
</thead>
<tbody>
<?php if(count($records)) { ?>
<?php foreach($records as $record) { ?>
<tr data-id="<?php echo $record->id; ?>">
<td><?php echo $record->nome; ?></td>
<td>
<?php
if ($record->ativo == 1) {
echo "SIM";
} else if($record->ativo == 0){
echo "NÂO";
}
?>
</td>
<td>
<?php echo anchor("gurpoProduto/excluir", "<i class='glyphicon glyphicon-trash'></i> Exlcuir", ['class' => 'btn btn-danger btn-block', 'name' => 'delete']); ?>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
i'm trying to found an element in the first column using this function with jquery. Tihs is the function:
function verificar_existencia(nome) {
var table = $("#tabela-resultado tbody");
var nomeTabela = '';
table.find('tr').each(function (nome) {
var $tds = $(this).find('td'),
nomeTabela = $tds.eq(0).text()
});
if(trim(nome.toUpperCase()) === trim(nomeTabela.toUpperCase())) {
toastr.success("This element already exists!!!", "Aviso");
//return false;
}
}
but doesnt work.Whats is wrong? I need find an element in the table to prevent duplicate elements in the table.
You are looping through all the rows and overwriting nomeTabela every iteration.
Thus once loop completes it is the value found in last row only and that is what your comparison is done on
Do a check inside the loop for each value on each row something like:
function verificar_existencia(nome) {
nome = nome.trim().toUpperCase();
var table = $("#tabela-resultado tbody");
var isMatch = false;
table.find('tr').each(function(nome) {
var $tds = $(this).find('td');
var nomeTabela = $(this).find('td').eq(0).text();
// compare each value inside the loop
if (nome === nomeTabela.trim().toUpperCase()) {
isMatch = true;
return false; /// break the loop when match found
}
});
if (isMatch) {
toastr.success("This element already exists!!!", "Aviso");
//return false;
}
}
Also note your incorrect use of String#trim() which should show up as error in your browser console
Here's a way to identify a dupe strings in the first column of the table.
var $trs = $("table tr"), dupes = [];
function san(str) {
return str.text().trim().toUpperCase();
}
$trs.each(function() {
var origTd = $(this).find("td:first"), origTr = $(this);
$trs.each(function() {
var newTd = $(this).find("td:first"),
newTr = $(this),
origTrIdx = origTr.index(),
newTrIdx = newTr.index(),
origTdStr = san(origTd),
newTdStr = san(newTd);
if (
origTrIdx > newTrIdx &&
dupes.indexOf(origTdStr) < 0 &&
origTdStr === newTdStr
) {
dupes.push(origTdStr);
console.log(
'This element "' +
origTd.text() +
'" already exists!!!'
);
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
<tr>
<td>unique</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>unique2</td>
<td>bar</td>
</tr>
<tr>
<td>foo</td>
<td>bar</td>
</tr>
</table>

how to give style to the SQL table when checkbox selected?

SO i have form which consist of "Event Name" "Event Description" "Event Date" and checkbox "is important". When i check checkbox value "yes" its important, it sends to the sql value = "1" to table "is_important". Everything is all right, but i give the bootstrap style "bg-danger" for that "is_important" = 1 table and it doesnt show up. What's the problem?
You can see in the code:
<?php
if (isset($_POST['important'])) {
$error = array();
$success = array();
$eventTime = time();
$important = $_POST['important'];
$eventName = trim(mysql_real_escape_string($_POST['EventName']));
$eventDesc = htmlentities(trim(mysql_real_escape_string($_POST['EventDesc'])), ENT_QUOTES);
if (!isset($eventName) || empty($eventName)) {
$error['eventName'] = "Prasome ivesti ivykio varda";
} else if (strlen($eventName) > 32 || strlen($eventName) < 3) {
$error['eventName'] = "Ivykio pavadinimas turi buti tarp 3 ir 32 simboliu";
}
if (!isset($eventDesc) || empty($eventDesc)) {
$error['eventDesc'] = "Prasome ivesti ivykio aprasyma";
}
if (empty($error)) {
$sql = "INSERT INTO notes_list (title, description, timestamp,is_important) VALUES ('$eventName', '$eventDesc','$eventTime','$important')";
$result = mysqli_query($con, $sql);
$success[] = "SEKME !";
} else {
}
}
?>
<table class="table table-striped">
<thead>
<tr>
<th>Event name</th>
<th>Event description</th>
<th>Event date</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM notes_list ORDER BY id DESC LIMIT 10";
$result2 = mysqli_query($con, $query);
print_r($_POST);
if ($result2) {
while ($note = mysqli_fetch_assoc($result2)) {
?>
<tr<?php echo (($note['is_important'] == 1) ? "class='bg-danger'" : ""); ?>>
<td><?php echo $note['title']; ?></td>
<td><?php echo $note['description'] ?></td>
<td><?php echo date('l M jS', $note['timestamp']); ?></td>
</tr>
<?php
}
mysqli_free_result($result2);
}
/* close connection */
mysqli_close($con);
?>
</tbody>
</table>
Full Example in this picture:
https://www.dropbox.com/s/h650h2spy2487dm/chechbox.jpg?dl=0
This:
<tr<?php echo (($note['is_important'] == 1) ? "class='bg-danger'" : ""); ?>>
would render this:
<trclass='bg-danger'>
in case is_important is 1. You need a space there, before the class.

Unable to delete user from checkbox in PHP

i am trying to delete some rows but i dont know where i am mistaking please check this below code and suggest my error with solution:
if(isset($_GET['delete']) && $_GET['delete']=="true")
{
$checkbox = $_POST['checkbox'];
for($i=0;$i<count($checkbox);$i++)
{
echo $checkbox[$i]; // here i am going to write delete query
}
}
Now my HTML code for that. I have created a table for users.
it looks something like this in HTML
<table id="sample_2">
<thead>
<tr>
<th style="width:8px;"><input type="checkbox" class="group-checkable" data-set="#sample_2 .checkboxes" /></th>
<th>Username</th>
<th>Full Name</th>
<th class="hidden-480">Email</th>
<th>Mobile</th>
<th>Activation Key</th>
<th class="hidden-480">Status</th>
</tr>
</thead>
<tbody>
<?php $user_details->all_user_details(); ?>
</tbody>
</table>
Now here is the function i am using. to create table rows. So check this out:
while ($row = $database->fetch_array($result_set)) {
$single_row ="<tr class=\"odd gradeX\">
<td><input type=\"checkbox\" name=\"checkbox[]\" class=\"checkboxes\" value=\"".$row["userid"]."\" /></td>
<td>".$row['username']."</td>
<td>".$row['fullname']."</td>
<td class=\"hidden-480\">".$row['email']."</td>
<td>".$row['mobile']."</td>
<td>".$row['user_activation_key']."</td>";
if($row['status']==1){
$single_row .= "<td><span class=\"label label-success\">Approved</span></td>";
} else{
$single_row .= "<td><span class=\"label label-danger\">Pending</span></td>"; }
$single_row .="</tr>";
echo $single_row;
}
any solution for this problem? I know i am making mistake somewhere in $_POST['checkbox'] while getting the value, Please suggest.
Thank you!
this is your first problem:
if(isset($_GET['delete']) && $_GET['delete']=="true")
{
$checkbox = $_POST['checkbox'];
for($i=0;$i<count($checkbox);$i++)
{
echo $checkbox[$i]; // here i am going to write delete query
}
}
please change it to this:
if (isset($_GET['delete']))
{
if ($_GET['delete']=="true") {
$checkbox = $_POST['checkbox'];
for($i=0;$i<count($checkbox);$i++)
{
echo $checkbox[$i]; // here i am going to write delete query
}
}
}
and also you forgot to leave a space between if and (

How can I optimise and improve the speed of this MySQL query?

I am trying to get information from my database and display it. Here is a screenshot of what the page looks like:
The page loads really slow
Is there any way to make it load and display the data faster?
Here is the code.
<table align="center" class="pTable">
<tr class="main"> <th class="pTableHeader"> ID </th> <th class="pTableHeader"> Room </th> <th class="pTableHeader"> Status</th> </tr>
<?php
gc_enable();
gc_collect_cycles();
flush();
$this->mysql = new sqli('HIDDEN','HIDDEN','HIDDEN','HIDDEN');
$bots = $this->mysql->fetch_array("SELECT `pid`,`room`,`id` from `bots`;");
foreach ($bots as $b) {
if(is_numeric($b["room"])) {
$xat = file_get_contents('http://www.xat.com/xat'.trim($b["room"]));
$name = sp($xat, '<h1> ', '</h1>');
}
else $name = $b['room'];
//$b["pid"] = isset($b["pid"])?$b["pid"]:false;
//$online = \"start.php {$b['id']} {$b['id']}\"", $output) && count($output) > 1 ? true : false;
$online = file_exists("/proc/{$b['pid']}" )?true:false;
if($online === true) $status = "<font color='green'>Online</font> <div style='float:right'><img src='http://fexbots.com/Images/Pawns/online.png'> <a href='/botinfo?botid={$b["id"]}'>More info</a></div>";
else $status = "<font color='red'>Offline</font> <div style='float:right'><img src='http://fexbots.com/Images/Pawns/offline.png'> <a href='/botinfo?botid={$b["id"]}'>More info</a></div>";
if($b["room"] === '') {
$name = "No Room";
$status = "<font color='red'>Not Setup!</font> <div style='float:right'><img src='http://fexbots.com/Images/Pawns/hang.png'> <a href='/botinfo?botid={$b["id"]}'>More info</a></div>";
echo '<tr> <td> '.$b["id"].' </td> <td> No Room <td> '.$status.'</td> </tr>';
}
else echo "<tr> <td> ".$b['id']." </td> <td> <a href='http://www.xat.com/$name'>$name</a> <td> ".$status."</td> </tr>";
}
function sp($content, $start, $end, $lower=false) {
if($lower!=false) {
$content = strtolower($content);
$start = strtolower($start);
$end = strtolower($end);
}
$content = substr($content, strpos($content,$start)+strlen($start));
$content = substr($content, 0, strpos($content,$end));
return $content;
}
?>
</table>
You seem to download the content from an URL inside the loop. Maybe that is the cause to why it is slow and not the mysql query itself.
Try to write out some timestamps or comment some code out to see what is causing it to be slow.

PHP Search Code from HTML form

I had a previous question on here a few minutes ago about a syntax error that was sorted. I need help getting this script working or at least for someone to point me in the right direction.
This is a search script to search by multiple fields. The search() array works fine and is a series of tickboxes with the following code:
<td width="22"><input type="checkbox" name="search[olevel = 'Yes']" id="search[olevel = 'Yes']" value="1"/>
The postcode box is a text box with the following code:
<input name="postcode[]" type="text" id="postcode[]" size="12" maxlength="12" /></td>
When I tick the olevel box it returns all the records that have Yes in the olevel field. That works as I expect.
If I put in anything in the postcode box it returns no results.
Here is the php code for the search engine.
<?php
include ('c1.php');
if ($_COOKIE["auth"] == "1") {
$display_block = "<p>You are an authorized user.</p>";
} else {
header("Location: userlogin.html");
exit;
}
doDB();
$display_block = "<h1>Results</h1>";
if (isset($_POST['search']) && !empty($_POST['search'])) {
foreach ($_POST['search'] as $key => $value) {
if ($value == 1)
$search[] = "$key";
$searchstring = implode(' AND ', $search);
$post_map = array(
'postcode' => 'candididate_contact_details.postcode'
);
}
if (isset($_POST['postcode']) && !empty($_POST['postcode'])) {
foreach ($_POST['postcode'] as $key => $value) {
if (array_key_exists($key, $post_map))
$search[] = $post_map[$key] . '=' . mysql_real_escape_string($value);
echo $searchstring;
echo $search;
$query = "SELECT candidate_id.master_id, candidate_contact_details.first_name, candidate_contact_details.last_name, candidate_contact_details.home_phone, candidate_contact_details.work_phone, candidate_contact_details.mobile_phone, candidate_contact_details.email FROM candidate_id, candidate_contact_details, qualifications, security_experience, previous_career WHERE qualifications.active = 'finished' and candidate_id.master_id = candidate_contact_details.master_id and candidate_id.master_id = qualifications.master_id and candidate_id.master_id = security_experience.master_id and candidate_id.master_id = previous_career.master_id and $searchstring";
$query_res = mysqli_query($mysqli, $query)
or die(mysqli_error($mysqli));
// $search = mysqli_query($mysqli, $query)or die(mysqli_error($mysqli));
{
$display_block .= "
<table width=\"98%\" cellspacing=\"2\" border=\"1\">
<tr>
<th>Registration Number</th>
<th>First Name</th>
<th>Last Name</th>
<th>Home Number</th>
<th>Work Number</th>
<th>Mobile Number</th>
<th>E-Mail</th>
</tr>";
while ($result = mysqli_fetch_array($query_res)) {
$regnum = $result['master_id'];
$first_name = $result['first_name'];
$last_name = $result['last_name'];
$home_phone = $result['home_phone'];
$work_phone = $result['work_phone'];
$mobile_phone = $result['mobile_phone'];
$email = $result['email'];
$display_block .= "
<tr>
<td align=\"center\">$regnum <br></td>
<td align=\"center\">$first_name <br></td>
<td align=\"center\">$last_name <br></td>
<td align=\"center\">$home_phone <br></td>
<td align=\"center\">$work_phone <br></td>
<td align=\"center\">$mobile_phone <br></td>
<td align=\"center\">$email <br></td>
</tr>";
}
$display_block .= "</table>";
}
}
}
}
?>
<html>
<head>
<title> Display results</title>
</head>
<body>
<?php echo $display_block; ?>
</body>
</html>
I know I am doing something wrong but cannot quite figure it out. Thanks in advance.
if I understand correctly, you have several postcodes per form.
then id="postcode[]" is wrong as there will be several id named the same in dom.
just delete that from your code.

Categories