using php to fill in an existing table - php

I have a blank html table (column) on my page. I have a csv file with last years info for
that column available, but I don't want to initially write those values into the table
cells (because there might be new info which needs to be manually entered). I would like
to make a button which would populate this column. What would be the best way of going
about this? Since I want the info entered dynamically I would obviously need to use an
ajax call, and I would call a php file because that has a useful function fgetcsv(), but
can I use this function to enter info into a existing table? I was able to use php to
CREATE a table with this info, but as far as I understand, php has no knowledge of the
DOM... I would have to somehow package the entire column info and have javascript do the
job but I'm a little confused as to how...
Below is a snippet of how I used php to CREATE my table.
$file = fopen("SGS_Fall_Booklist.csv", "r");
$entry= fgetcsv($file);
echo $entry[0] . $_GET["program"] . $entry[1] . $GET["school"] .
$entry[2] . $GET["term"];
echo "<br>AutoFill (last years ISBN's)<br><input id='checkall' type='checkbox' </input>";
echo "<table><tr>
<th>Edit</th>
<th class='coursename'>" . $entry[6] . "</th>
<th class='startdate'>" . $entry[7] . "</th>
<th class='booktitle'>" . $entry[17]. "</th>
<th class='author'>" . $entry[18]. "</th>
<th class='isbn'>" . $entry[16]. "</th>
</tr>";
while(! feof($file))
{
$entry = fgetcsv($file);
echo "<tr>
<td><input type='checkbox'></input></td>
<td class='coursename'>" . $entry[6] . "</td>
<td class='startdate'>" . $entry[7] . "</td>
<td class='booktitle'>" . $entry[17]. "</td>
<td class='author'>" . $entry[18]. "</td>
<td class='isbn'></td>
</tr>";
}
echo "</table>";
fclose($file);

So here's a few things you can do:
(worst) Send the entire table back in the ajax call to PHP, and then let php add your column, and return the updated table (bad plan, lots of unchanged data transferring)
(better) Ajax call to return an entirely new table with your new column (better)
(best) Ajax call to fetch an array or object with your data and then use javascript to iterate over the table and add the data
Pseudo code:
//do your ajax request
foreach(newColumnValues AS key=>value) {
foreach(document.getElementByID("yourtable").elements) {
//If the ordering can change, check the key first, otherwise you could
//just go through every element
if(element[0] == key) {
element[1] = value;
}
}
}
Good luck!

If you have the code above print your ajax response you can then just do this on your javascript:
document.getElementById('container-id-here').innerHTML(your_ajax_response_text);

Related

How to display a button for each row in a table

I have a MySQL database of booking records and I am displaying this in an HTML table. I was wondering how to add a button in every row of the table that will allow me to delete that row from the database.
<!DOCTYPE html>
<html>
<head>
<h2> All bookings </h2>
</head>
<body>
<table class='striped white'>
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Surname</th>
<th>Date</th>
<th>Time</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
echo
"<tr>".
"<td>". $row['id'] . "</td>" .
"<td>". $row['firstName'] . "</td>" .
"<td>". $row['surName'] . "</td>" .
"<td>". $row['date'] . "</td>" .
"<td>". $row['timeSlot'] . "</td>" .
"</tr>";
}
} else{
echo 'no bookings';
}
?>
</tbody>
</table>
</body>
</html>
You'll need to add a cell with a URL that has code configured to run a DELETE command in your database. This is typically what atomic ID's are used for. Lets assume the above table is in a file called table.php. Given this, we can adjust your first table cell to the following:
...
"<td>". $row['id'] . "<br />Delete Row</td>" .
...
Now when you click this link you'll have a GET variable assigned in the $_GET superglobal array called "deleteId" that you can use to delete the row.
You'll want to place this above your table so that any deletions reflect in the table each time you reload the page.
if (isset($_GET['deleteId'])) {
// Sanitize input for SQL injection risk
$deleteId = $mysqli->real_escape_string($_GET['deleteId'])
if (!is_null($deleteId)) {
// Just an example, you will need to correct this query and optionally use parameters vs. directly putting the variable in the SQL string
$mysqli->query("DELETE FROM ... WHERE id = '$deleteId'");
}
}
Bedlams suggestions seems like a good solution.
However I would recommend to NOT delete anything from your database. I would add a column to my table 'Removed' with an integer 0 or 1.
1 = deleted
0 = not deleted (default)
When clicking the button in the table it updates the selected row's removed to 1.
I use bootstrap so this example uses that library.
If you want to add a confirmation modal, just simply replace bedlam's a href to something like:
Delete Row
Then add a button in that modal that will handle the deletion logic. You can use bedlam's a href in that modal.
<button type="button" id="delete">Delete</button>
You'll need to add some javascript to get the dynamic modal. Something like:
$("#whateveridyougiveyourmodal").on("shown.bs.modal", function(event){
var id = $(event.relatedTarget).data('id');
$(this).find("#id-hidden-input").val(id);
});
$("#delete").click(function(event){
var id = document.querySelector("input[name='id']").value;
// POST ID TO DELETE FOR EXAMPLE I'LL USE AJAX
$.ajax({
type: "POST",
data:{data: id},
url: "WHERE YOU WANT TO HANDLE DELETION LOGIC.php",
success:function(result){
console.log(result);
}
});
});
In your "WHERE YOU WANT TO HANDLE DELETION LOGIC.php" you'll want to accept the POST data with the super global "$_POST", or in this case "$_POST['data']".

Opening user profile in new tab

I am displaying proclamations in a table and I want to make each row clickable which I kinda did with js onclick function (i can only click on the name but i want to apply this to whole row). Now I want to see details about proclamations in new tab. My question starts here. I want to get proclamation ID when I click on a row but no idea how to do it. Plus i am doing onclick with js and rest of it is php so it's getting kinda messy there. I know it's not the best way to do it so i need your advice about how can I solve this issue.
P.S. I am not very familiar with js, those js parts been taken from web tutorials. And the code below is the section where I display the search results.
<section id="results">
<div class="container">
<table>
<tr>
<th>Name</th>
<th>Where</th>
<th>From</th>
<th>Date</th>
<th>Price</th>
<th>Type</th>
<th>PId</th>
</tr>
<?php
if(isset($_POST['search_btn'])){
include_once "db_connect.php";
$from = $_POST['from'];
$where = $_POST['where'];
$date = $_POST['date'];
$type = $_POST['type'];
$procid = $_POST['proc_id'];
if(empty($from) || empty($where) || empty($date) || empty($type)){
header("Location: index.php?search=empty");
exit();
}else{
$sql = "SELECT * FROM proc WHERE p_from = '".$from."' and p_where = '".$where."' and type= '".$type."' ";
$query = mysqli_query($conn, $sql);
$num_rows = mysqli_num_rows($query);
while ($rows = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
echo "<tr><td onclick='content(this)'>" . $rows['p_name'] . " " . $rows['p_surname']. " </td><td>" .$rows['p_from']. "</td><td>" .$rows['p_where']. "</td><td>" .$rows['p_date']. "</td><td>" .$rows['price']. "</td><td>" .$rows['type']. "</td></tr>" ;
}
echo "</table>";
}
}else{
echo "Error!";
}
?>
<?php
$fullUrl = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if(strpos($fullUrl, "search=empty") == true){
echo "<p class='error'>You did not fill in all fields!</p>";
}
?>
</table>
</div>
</section>
<script>
function content(elem){
<?php
?>
window.open('procdetail.php');
}
</script>
In your JavaScript function that calls window.open, you need to call the second parameter which will be the target to open the window, adding _blank will open it on a new tab instead of the same window:
window.open('procdetail.php', '_blank');
Give JavaScript the data needed to handle your information.
Also, if your idea is to open the tab with JavaScript with the content specially for the row, then you should try returning the necessary information to it, for example, if you want to open a new window with the content of a user, then you must let know JavaScript which user id should open.
This is as easy as returning in an attribute for your row element the value of the user id which data is being outputted by PHP.
Do something like this in your inline PHP script:
echo "
<tr class='table-item' data-userid='USER_ID_VARIABLE_HERE'>
<td>" . $rows['p_name'] . " " . $rows['p_surname']. " </td>
<td>" .$rows['p_from']. "</td>
<td>" .$rows['p_where']. "</td>
<td>" .$rows['p_date']. "</td>
<td>" .$rows['price']. "</td>
<td>" .$rows['type']. "</td>
</tr>
";
And then in your JavaScript code you could use an event listener for every element in your DOM with class="table-item":
window.onload = () => {
let tableItems = document.querySelectorAll(".table-item");
tableItems.forEach((element) => {
element.addEventListener("click", (event) => {
//Handle your click event here
let userId = event.target.dataset.userid; //Your user id
window.open('procdetail.php?id=' + userId, '_blank');
});
})
}
This will open in a new tab the contents of the url given which is procdetail.php?id=userId. So then, in your procdetail.php file you must handle the $_GET["id"] variable to show the respective data.
Additional resources:
You can read more of the window.open method here.
Try this
link name
If you want to continue to use inline JavaScript, you will first need to change the onClick attribute to be on the <tr> element instead of the <td> element. Once that is done, you can use the same function you have to pass the proc_id to the URL in the window.open(); method you have set in the function.
HTML/PHP
echo '<tr onclick="content(\''. $rows['proc_id'] .'\')">';
Javascript
function content(ID){
window.open('procdetail.php?proc_id=' + ID, '_blank');
}
This will make each of the table rows a clickable element that links to procdetail.php?proc_id=<YOUR_ID>
There is a way to perform this in HTML as well, but you want to modify the CSS of the table elements so that there are not non-clickable dead zones in the table row.
Using your current method of the single line echo, you could use something similar to the code below. This will append the proc_id data as a URL parameter for procdetail.php to parse.
Notice that the code only includes p_name and p_surname. You would have to add each definition with the same method.
PHP
echo "<tr><td><a href='procdetail.php?proc_id=". $rows['proc_id'] ."' target='_blank'>". $rows['p_name'] . "</a></td><td><a href='procdetail.php?proc_id=". $rows['proc_id'] ."' target='_blank'>". $rows['p_surname'] ."</a></td></tr>";
CSS
table tr td a {
display:block;
height:100%;
width:100%;
}
table tr td {
padding-left: 0;
padding-right: 0;
}
Check out this thread on the issue. It includes a usable demo that is hosted in JSFiddle.

How to submit parameters by hyperlink-url and retrieve them in php?

Carrying values in a while cycle, each value is extracted from a SQL table, and I need to carry em in a since I'm making a list of items purchased from a specific client. I'm using this line for the href url:
echo "<table width=1200 style align=left>";
while($row3 = mysqli_fetch_array($rs3)){
$space = array("");
$text=$row3['description'];
$dash="_";
$url = preg_replace("![^a-z0-9]+!i", "_", $text);
$url= "".$url.".php";
echo "<tr><td colspan=2 style align=center><span class=font>" . $row3['relid'] . "</span></td><td width=132 style align=center><span class=font>" . $row3['invoiceid'] . "</span></td><td width=400 style align=center <span class=font><a href=$url>" . $row3['description'] . "</span></A></td><td width=132 style align=right><span class=font>" . $row3['amount'] . "</span></td><td width=132 style align=center><span class=font>Pendiente</span></td><td width=132 style align=left><span class=font>" . $row3['duedate'] . "</span></td></tr>";
}
mysqli_close($con3);
echo "</table>";
echo"<table width=1200>";
echo " <tr class=font>
<td width=1200 height=22 colspan=7 background=border-green-horizontal.png> </td>
";
I'm generating the url from the Description I extract from the database but I need to carry the Order ID, Client ID, etc from the specific row.
Each variable is needs to be carried to a form where the user will fill some fields regarding the product the client bought (Medical Test Results), and I need those variables to mark as "Done" so It won't show up again on the list.
Fix these syntax errors, report back if still broken.
<td width=400 style align=center <span class=font><a href=$url>" . $row3['description'] . "</span></a></td>
-->
"<td width=400 style align='center'><span class='font'><a href='$url'>" . $row3['description'] . "</span></a></td>"
EDIT:
Do you mean how to append a var to an url, so it can be retrived on the called page?
You can append the var to the url by echo "<a href='{$url}?id={$var}'>.
On the called page, you can read it by $_GET['id']

Concept Help Needed: Tables and Displaying All Rows

I have an upload system in my site where users can upload files and write a brief description of them. Each upload has a corresponding SQL entry.
Another page on my site will then display every file uploaded along with some traits about that file
The question is:
How can create a table with a variable set of rows and how can I set a table to automatically populate the new rows?
I am capable with PHP but still a novice, weak with HTML (I use a wysiwyg) and completely inexperienced with Javascript.
Any nudge in the correct direction would be hugely appreciated...
In order to make the rows of your HTML table "dynamic" using PHP, you should use the foreach() control structure. For example, say you have some code to grab the data from the database and it returns it as an array or some sort of result statement that implements an Iterable interface (we'll call it $results), you can then:
<table>
<thead>
<tr>
<th>File Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php
foreach($results as $result)
{
// Start row
echo("<tr>");
echo("<td>" . $result->filename . "</td>");
echo("<td>" . $result->description . "</td>");
// End row
echo("</tr>");
}
?>
</tbody>
</table>
You can use a loop to populate the table based on results from a query of your database. Here's the code I use for one of my pages:
$result = $db->query_read("SELECT dice.RollID AS `Roll`, dice.Limit AS `Limit`,
dice.Value AS `Value`, dice.Dateline AS `Dateline`, dice.Comment AS `Comment`
FROM dice
ORDER BY Dateline DESC LIMIT 25");
// ###### MAIN CODE ######
$str = '<table>
<tr><th>ID</th><th>Roll</th><th>Time</th><th>Comment</th></tr>';
while ($resultLoop = $db->fetch_array($result)) {
$ID = $resultLoop["Roll"];
$roll = $resultLoop["Value"] . '/' . $resultLoop["Limit"];
$when = date('m-d-Y H:i:s', $resultLoop["Dateline"]);
$comment = $resultLoop["Comment"];
$str .= '<tr>
<td>' . $ID . '</td>
<td>' . $roll . '</td>
<td>' . $when . '</td>
<td>' . $comment . '</td></tr>';
}
$str .= '</table>';
echo $str;
One thing to note is that I use $db->* functions because it is integrated with a forum software. You should be using mysqli_* functions as found here: http://php.net/manual/en/book.mysqli.php

PHP/CSS can't get element to sit over a table?

I have a div relatedListings that contains a table of customer's orders.
I want to add a heading above it, I have tried h3, div, and span but it always puts the element below the table.
The code that generates the table:
echo '<div id="relatedListings">
<h3 id="relatedListingsHeader">Customer\'s Listings</h3>' .
$account->listAds() .
'</div>';
The actual source from the browser after executed:
<table id='customerAds'>
<!-- Generated table data -->
</table><div id="relatedListings">
<h3 id="relatedListingsHeader">Customer's Listings</h3></div>
Notice in the second snippet, the div is AFTER the table. Any ideas?
EDIT: here is the listAds method:
echo "<table id='customerAds'>
<tr><th>Ad</th><th>Title</th><th>Description</th><th>Ad Date</th><th>Actions</th></tr>";
while ($ad = $ads->fetch()) {
echo "<tr id='row_{$ad['idAds']}'>
<td>{$ad['idAds']}</td>
<td>{$ad['Title']}</td>
<td>" . substr(strip_tags($ad['Description']), 0, 100) . "...</td>
<td>" . format::dateConvert($ad['DatePosted'], 12) . "</td>
<td><a href='#'>Delete</a></td>
</tr>";
}
echo "</table>";
I would venture to guess that $account->listAds() is echo-ing as well and not returning instead. If you can change that function to return instead you should be better off.
Update:
Now having seen your updated code - I'd suggestion having that function return a string - instead of using echo like you are
$tableCode = "<table id='customerAds'>
<tr><th>Ad</th><th>Title</th><th>Description</th><th>Ad Date</th><th>Actions</th></tr>";
while ($ad = $ads->fetch()) {
$tableCode .= "<tr id='row_{$ad['idAds']}'>
<td>{$ad['idAds']}</td>
<td>{$ad['Title']}</td>
<td>" . substr(strip_tags($ad['Description']), 0, 100) . "...</td>
<td>" . format::dateConvert($ad['DatePosted'], 12) . "</td>
<td><a href='#'>Delete</a></td>
</tr>";
}
$tableCode .= "</table>";
return $tableCode;
Your generated table data may be malformed, causing the browser to try and fudge the markup into what it thinks you meant. Since you didn't include that markup, I couldn't tell for sure. It would also be helpful to see the code from $account->listAds().

Categories