Add onclick event on a php-generated table cell [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I would like to generate an HTML table with dynamic content in PHP, and add an onclick event on a cell of each row, to trigger an action depending on that row.
How to achieve that ?
Here is my example :
I have a table which prints data from a database. Table is made of 3 columns. Columns 1 and 2 hold name and surname and column 3 refers to a comment. Third column says "Comment exists" or "No comments", depending on whether a related comment exists or not.
The goal is to pop up a small window when user clicks on the third column, to show the given comment.
Here is an example of a table, and what I have tried so far :
<table border=1>
<tr>
<th>ID</th>
<th>Vardas</th>
<th></th>
</tr>
<?php while($row = mysql_fetch_array($res)) : ?>
<tr>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['vardas'] ?></td>
<td><?php echo $row['gedimas'] ?></td>
</tr>
<?php endwhile; ?>
</table>
How do I add on click event for the $row['gedimas'] line, to display a full comment from database ?

You can place an "onclick" event directly in PHP :
<td <?php echo "onclick='displayComment(".$id.")'" ?> >
About the general structure of opening a window, you can build the table pretty easily, and then have another page for displaying the comment if there is.
Code for the table :
<table>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Has comment ?</th>
</tr>
<?php
for( $i = 0; $i<count($database_data); $i++){
$item = $database_data[$i];
?><tr>
<td><?php echo $item[0] ?></td>
<td><?php echo $item[1] ?></td>
<td <?php
echo "onclick='displayComment("
echo $item[0].", ".$item[1]
echo ")'"?>
><?php echo $item[2] ? "Comment exists" : "No comments" ?></td>
</tr>
}
Then you would need to include a javascript file with the following code :
function displayComment(name, surname) {
window.open(
"display_comment.php?name="+encodeURI(name)+"&surname="+encodeURI(surname),
"_blank",
"height=200, width=300"
}
And lastly, you would need your display_comment.phppage, whose essence would be :
// get comment from database using data in $_GET["name"] and $_GET["surname"]
Comment from <?php echo $_GET["name"]." ".$_GET["surname"] ?> :
<br>
<?php echo $comment_retrieved_from_database ?>
Alternative
An alternative would be to only record the id of the comment in the HTML code, and then add the onclick events in javascript.
The php code for the cell would be as follows :
<td <?php echo "data-comment-id='$id'" ?> >
And you would add the onclick events in javascript that way :
var tableCells = document.querySelectorAll("td[data-comment-id]");
for(var i=0; i<tableCells.length; i++){
var cell = tableCells[i];
var commentId = cell.getAttribute("data-comment-id");
cell.addEventListener("click", function(){openPopup(commentId);});
}

Related

I have a record Id that needs to be selected to be updated

I have a simple issue I cannot figure out. I am trying to get the id of the record setup as a link to go to a second page that updates the record. I have the update working when I click on update it takes me to the record. I want the id to do the same.
<html>
<?php
require_once("../db_connect.php");
$stmt = $db->prepare("SELECT * FROM Users");
$stmt->execute();
?>
<?php while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { ?>
<table bgcolor=F2F2F2 width=1080 border='2'table-layout: fixed >
<br>
<tr>
<th>Id</th>
<th>Update</th>
<th>First Name</th>
<th>Last name</th>
<th>Address</th>
<th>Bio</th>
</tr>
<tr>
<?php echo "<td>
<a href='../update.php?id=" . $row['id'] . "'>ID</a></td>"?>
<?php echo "<td>
<a href='../update.php?id=" . $row['id'] . "'>Update</a></td>"?>
<td><?php echo $row['First Name']; ?></td>
<td><?php echo $row['Last Name']; ?></td>
<td><?php echo $row['Address']; ?></td>
<td><?php echo $row['Bio']; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
In general, it is a good practice to put duplicated content into a function or variable and then call it when needed, to improve code readability & to save time/space.
I have also noticed many people struggling with new syntax so I have split the "one-liners" and left comments explaining how does new syntax works.
function col_gen($slug,$id=''){
return (!empty($id))? // If ID parameter exist and not empty generate column with a link
'<td>'.$slug.'</td>': //else
'<td>'.$slug.'</td>';
}
And then, in your case, you can run this function inside a loop:
....
foreach($row as $k=>$slug){
echo ($k==='id')? //if key equals "id"
col_gen($slug,$slug) // Output column for ID
.col_gen('Update',$slug) // Output column for keyword Update
:col_gen($slug); //else output just column with the slug
/**
* Learn one-line PHP, you will love it, once you understand it...
* Full Example Above:
* echo ($k==='id') ? col_gen($slug,$slug).col_gen('Update',$slug):col_gen($slug);
**/
}

Getting contenteditable div's current value and update database

I'm new to web development and I'm trying to create editable database interface. I have got checkboxes in every row and an edit button. I need to update table(in database) when button clicked(rows that are checked). However I can't get current values in cells. I tried contentedittable div to display attiributes.
<?php while ( $rows = mysql_fetch_array($result)): ?>
<td align="center" bgcolor="#FFFFFF"><input name="need_delete[<?php echo $rows['UniqueID']; ?>]" type="checkbox" id="checkbox[<?php echo $rows['UniqueID']; ?>]" value="<?php echo $rows['UniqueID']; ?>"></td>
<td bgcolor="#FFFFFF"><div contenteditable><?php echo $rows['Timestamp']; ?></div></td>
<td bgcolor="#FFFFFF"><div contenteditable><?php echo $rows['Name']; ?></div></td>
<td bgcolor="#FFFFFF"><div contenteditable><?php echo $rows['Email']; ?></div></td>
<?php endwhile; ?>
I also tried to give unique names to divs, but it didn't work. I want to get current values from there if possible.
<?php
if( ! empty($_POST['edit']) ){
$query = 'UPDATE `asd` SET `Timestamp` = '????' WHERE `UniqueID`='.(int)$id;
mysql_query($query);
}
?>
Checkboxes work fine when I delete rows from table. Any suggestions ?
Thanks.
There are several javascript libraries that help with this problem:
x-editable http://vitalets.github.io/x-editable/ (bootstrap)
datatables https://datatables.net/ (jquery)
I had a similar issue that I solved here:
http://www.abrandao.com/2019/12/saving-contenteditable-html-using-php/
basically, it involves reading the HTML and using PHP parser to exctract the tag and the update the data

jquery how to get value in a table

I have the following code that generates a table:
<table class="table table-bordered table-striped" id="assignedvs">
<thead>
<tr>
<th>VlId</th>
<th>Name</th>
<th>Status</th>
<th>Voice</th>
<th>Jumbo</th>
<th>Mode</th>
</tr>
</thead>
<tbody>
<?php foreach ($vln as $vlndetail): ?>
<tr>
<td id='vlid'><?php echo $vlndetail['VlId'] ?></td>
<td><?php echo $vlndetail['Name'] ?></td>
<td><?php echo $vlndetail['Status'] ?></td>
<td><?php echo $vlndetail['Voice'] ?></td>
<td><?php echo $vlndetail['Jumbo'] ?></td>
<td><?php echo $vlandetail['Mode'] ?></td>
</tr>
<?php endforeach ?>
I need to find the row where the VlId matches what the user has specified in a text box. Once I've found this record, I want to grab value in the mode column for the particular row.
here's what i've written so far:
$('#delete').live('click', function() {
//get a count of all records. only allowed to delete if you have more than one + the header.
var reccount = $('#assignedvs tr').length;
if (reccount > 2)
{
//loop through the table
$('#assignedvs tr').each(function() {
var temp = $(this).find(".vlid").html();
console.log(temp);
if (temp == $('#uservalue').val){
//grab mode column
}
});
}
else
{
alert("error: must have at least 1 record.");
}
});
problem - the code i have to reference the vlid column is incorrect. it always prints a null to the console.
Can you tell me what I've done wrong?
thanks.
EDIT 1
I changed my id to a class and changed my jquery back to the original code I had. it's working - except for the fact that I think it's including the header . I have 4 rows + header. When i check the console results, the first print out is always NULL and then the correct value for the 4 records. how do it get it to ignore the header?
That's because you are finding by className, not by id. To find by id, use the following instead:
$(this).find("#vlid").html();
However, since ids should be unique across the entire document, a better solution would be to maintain your current code, and instead of using <td id='vlid'>, use <td class='vlid'>.
Also note that val() is a function. Thus, to get the value of a given input, you should use $('#uservalue').val().
EDIT: To exclude the header, use the $('#assignedvs tbody tr') selector. This way, you only get rows that are descendants of tbody, thus ignoring the header rows, which descend from thead.
couple of changes:
<?php echo $vlndetail['VlId']; //missing semi-colon ?>
var temp = $(this).find("#vlid").html(); vlid is an id
You can easily do this via datatables at http://datatables.net
var temp = $(this).find("#vlid").html(); // .vlid (by class) changed to #vlid (by id)
An even easier solution.
Assign an ID to each row with the vlId (possibly prepend tr_ to the ID to avoid duplication).
Assign a class with the column name to each datacell.
Like so:
<?php foreach ($vln as $vlndetail): ?>
<tr id='tr_<?php echo $vlndetail['VlId'] // set the ID ?>'>
<td class='vlid'><?php echo $vlndetail['VlId'] ?></td>
<td class='Name'><?php echo $vlndetail['Name'] ?></td>
<td class='Status'><?php echo $vlndetail['Status'] ?></td>
<td class='Voice'><?php echo $vlndetail['Voice'] ?></td>
<td class='Jumbo'><?php echo $vlndetail['Jumbo'] ?></td>
<td class='Mode'><?php echo $vlandetail['Mode'] ?></td>
</tr>
<?php endforeach ?>
Then to get the Name of the selected vlID just do this JQUERY:
var rowID = "#tr_" + $('#uservalue').val(); // this is optional. I prefer to cache values for increased code readability.
$(rowID + " td.Mode").dostuffhere(); // this selector returns the Mode cell for the row indicated by the user
This will grab the Mode column of that specific row.

Odd and Even Rows for a table

I have a table that get its rows from a MYSQL database
<table id="table1">
<?php
// Connect to database server
mysql_connect("localhost", "root", "asnaeb") or die (mysql_error ());
// Select database
mysql_query("SET NAMES `utf8`"); // UTF 8 support!!
mysql_select_db("scores") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM latest";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
?>
<?php echo $row['Header'].""; ?>
<tr>
<td id='date'><?php echo $row['Date'].""; ?></td>
<td id='time'><?php echo $row['Time'].""; ?></td>
<td id='hometeam'><?php echo $row['HomeTeam'].""; ?></td>
<td id='score'><?php echo $row['Score'].""; ?></td>
<td id='awayteam'><?php echo $row['AwayTeam'].""; ?></td>
<td id='other'><?php echo $row['Other'].""; ?></td>
</tr>
<?php } mysql_close(); ?>
</table>
i have 2 css class called "A" and "B" for Odd Rows and Even Rows
i currently getting this done by replacing <tr> with <tr class='<?php echo $row['Row'].""; ?>'> and i have in my Database table a column "Row" which i add in A or B for even or odd row... the problem is if i wanna delete or add a new row between one of these i will have to change all the A and B in the other.
I have seen in another questions many way to do that in javascript or jquery but for a normal table with TR's which is not my case...(tried some of these scripts but couldn't get it fixed)
So what i want an easier way to do that Even and Odd rows, Thanks!
do it in CSS way (no inline class) once and for all:
in CSS:
#table1 tr:nth-child(odd) td { background-color:#ebebeb }
#table1 tr:nth-child(even) td { background-color:#0000ff }
in your HTML:
<table id="table1">
thats it, no matter if your table rows are removed/or not.
You can add those classes using jQuery easily like this
$(function(){
$('#table1 tr:odd').addClass('A');
// for even
$('#table1 tr:even').addClass('B');
});
Why didn't you use modulo in your while loop ? It's a better way than store your class in your database... :
$i = 0;
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
?>
<?php echo $row['Header'].""; ?>
<tr class="<?php echo $i%2 == 0 ? "class_A" : "class_B" ; $i++;?>" >
<td id='date'><?php echo $row['Date'].""; ?></td>
<td id='time'><?php echo $row['Time'].""; ?></td>
<td id='hometeam'><?php echo $row['HomeTeam'].""; ?></td>
<td id='score'><?php echo $row['Score'].""; ?></td>
<td id='awayteam'><?php echo $row['AwayTeam'].""; ?></td>
<td id='other'><?php echo $row['Other'].""; ?></td>
</tr>
<?php } mysql_close(); ?>
<?php
$class="odd"
while($row = mysql_fetch_array($rs)) {
$class = ($class=='even' ? 'odd' : 'even');
?>
<tr class="<?php echo $class">
...
</tr>
<?php } ?>
There are many ways to do this, PHP, Javascript and even pure CSS. Here's the PHP way to add a class to every other row:
while($row = mysql_fetch_blahblah()) {
$i = 0; ?>
<tr class="<?php echo $i % 2 == 0 ? 'class1' : 'class2';?>">
<td>....</td>
</tr>
<?php
$i++; // increment our counter
}
Basically the modulus operator returns the remainder of dividing the nubmers either side of it, so for example 3 % 2 == 1, 4 % 2 == 0, 5 % 2 == 1, so we can tell if $i is odd or even and alternate the classes added to the <tr>.
IMHO you want to either do it this way for 100% guarantee it will work (no browser dependencies) or if you design your app for modern browsers go for the CSS route.

Use output from MySQL to extract additional info

How can I use the output of a MySQL query as to extract extra info from the database about that output?
For example, if my query generates a list of names and there is extra info about each name existing in the database, when I click on the name on the output page, the system will extract the relevant info from the database and show it on another page.
EDIT: Here's the code:
<?php
// you can delete mysql-assoc
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
?>
<tr align="center">
<td width="5%">
<a href="// I don't know what do put here " >
<?php print("{$row["pid"]}");?>
</a>
</td>
<td><?php print("{$row["place"]}");?></td>
<td><?php print("{$row["date"]}");?></td>
<td><?php print("{$row["ppp"]}");?></td>
<td><input type="button" value="Book"></td>
</tr> <?php } ?>
Set each row of the first output results equal to a variable, and then have an if statement in php that looks for strings in those variables, and then (upon some sort of a page refresh button since php is server-side code) displays the additional content.
Great; here's what you're missing:
<a href="<?php // I don't know what to put here ?>" >
Should be:
<a href="<?php echo 'database.php?action=viewrecord({$row["pid"]})'?>" >
From there, you should be able to extract the relevant info using the pid of the user.
On a side note, unless you're really worried about spacing, you should just dump out the relevant HTML; doing so will save you the task of repeatedly typing <?php ?> every time you want to dump out a variable.
<?php
// you can delete mysql-assoc
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
echo "<tr align='center'>";
echo "<td width='5%'>";
echo "<a href='database.php?action=viewrecord({$row['pid']})'>";
echo "{$row['pid']}";
echo "</a>";
echo "</td>";
echo "<td>{$row['place']}</td>";
echo "<td>{$row['date']}</td>";
echo "<td>{$row['ppp']}</td>";
echo "<td><input type='button' value='Book'></td>";
echo "</tr>";
}
?>
Thanks for the help but this doesn't work :( I'm beginner in php when I press the record the url looks like localhost/ass/database.php?action=viewrecord%28{$row[
This isnt a direct answer to your question perse but since youre new to php im goign to through it out there. The syntax you uisng makes unicorns cry. It give me a headache jsut tryign to decipher it. Heres the same code in an alternative way:
<?php while($row = mysql_fetch_array($rs, MYSQL_ASSOC)): ?>
<tr align="center">
<td><?php printf('%s', url_encode('viewrecord('.$row['pid'].')'), $row['pid']); ?></td>
<td><?php echo $row['place']; ?></td>
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['ppp']; ?></td>
<td><input type="button" value="Book"></td>
</tr>
<?php endwhile; ?>
However this database.php?action=viewrecord() worries me. I hope youre not using eval to execute a function passed by URL. Typically this would look something more like: database.php?action=viewrecord&id=2. You would verify that the action parameter is valid, and then invoke a function tied to that parameter which may or may not be the actual function name, and you would pass in the id parameter.
Eaxample database.php:
$action = isset($_POST['action']) ? $_POST['action'] : 'index';
switch($action) {
case 'viewrecord':
if(isset($_POST['id']) {
viewrecord((integer) $_POST['id']);
}
break;
// a whole bunch of other cases here for other actions
default:
// the default thing to do if an action is in valid
}
// the rest of your processing

Categories