PHP: Get value of id from a table - php

I have a table which I load with values from the database. The table has an update button which I want to pull specific data values from the database based on the id.
<tr>
<td><?php echo $result['id'];?></td>
<td><?php echo $rowcount ?></td>
<td><?php echo $result['Level Date'];?></td>
<td><?php echo $result['Recieve Date'];?></td>
<td><button type="button" name ="updateid" id="updateid" class="btn btn-primary" data-toggle="modal" data-target="#previous-detail-modal"> Update</button></td>
Can you advice on how I can get the value of $result['id'] of that particular row so I can use it in a function. Currently it keeps taking the last row count value
I tried many solutions reading the posts from others but I am not able to get the value. Would appreciate some help on this

Based on your comment:
I need the id on the client side
You can emit the ID from your PHP code onto the button itself as a data attribute, the same way you emit it anywhere else:
<button type="button" name="updateid" id="updateid" class="btn btn-primary" data-id="<?php echo $result['id'];?>" data-toggle="modal" data-target="#previous-detail-modal">Update</button>
Then in your client-side code, wherever you're handling the button click or otherwise identifying the button, you can pull the data attribute from that button. For example, if you have a reference to the element in a variable called myButton:
let id = myButton.dataset.id;
Edit: In a comment on the question you show the use of jQuery. In that case you might pull the data value with that:
let id = $('#updateid').data('id');

Related

Can I eliminate use of hidden form fields in html to pass data between pages where the data is row id of all table rows

I am developing an web app in which user should click on a link dislayed next to an order to generate an order details pdf
The page showing the orders by a particular user as a table with two columns:- time of order and pdf link for each order is having this snippet
echo '<table class="table"><tr>
<th>Order Submitted on</th>
<th>Get Details</th>
</tr>';
while ($row = $ordersByUser->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>'.$row['timestamp'].'</td>';
echo '<td><form method="POST" action="generateorderpdf.php">
<input type ="hidden" name="orderid" value='.$row['id'].'>
<input type="submit" value="CLICK" class="btn btn-dark">
</form></td></tr>';
}
echo '</table>';
I am storing the primary key of each order $row['id'] in a hidden field which is then sent to the generateOrderPdf.php page to generate the order pdf through a form using post method. My problem is that users can change the hidden input field using some browser developer tools and generate pdfs for other users which i definity don't want users to do (and its the reason why i am sending post request to the generate pdf page since anyone can edit the get url and see other people's orders). So is there any way in which I can eliminate the dependency on hidden input fields to send order id to the generateOrderPdf.php page?
I've read that i can use sessions to store sensitive data which then eliminates the need to use hidden form fields but I don't know is it even possible to use session variables to solve this problem and if possible how since this is a table of data?
Actually, you can do this with a session variable.
Put all the order IDs in an array in the session. Instead of putting the order ID in the hidden input, put the array index.
$myorders = [];
$order_index = 0;
echo '<table class="table"><tr>
<th>Order Submitted on</th>
<th>Get Details</th>
</tr>';
while ($row = $ordersByUser->fetch(PDO::FETCH_ASSOC)) {
$myorders[$order_index] = $row['id'];
echo '<tr><td>'.$row['timestamp'].'</td>';
echo '<td><form method="POST" action="generateorderpdf.php">
<input type ="hidden" name="orderid" value="'.$order_index.'">
<input type="submit" value="CLICK" class="btn btn-dark">
</form></td></tr>';
$order_index++;
}
echo '</table>';
$_SESSION['myorders'] = $myorders;
Then in generatorderpdf.php, you use $_SESSION['myorders'][$_POST['orderid']] to get the order ID.

PHP pass record id to another page without showing it in the URL

I'd like to know if there is a way to pass a record id to another page without showing in the URL (using $_GET).
This is my code:
<table class="table table-bordered">
<thead>
<tr>
<td>#</td>
<td>Sigla</td>
<td>Nome</td>
<td>Bilancio</td>
<td>Responsabile</td>
<td>Azione</td>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row): ?>
<tr>
<td><?=$row['id']?></td>
<td><?=$row['sigla']?></td>
<td><?=$row['nome']?></td>
<td><?=$row['bilancio']?></td>
<td><?=$row['responsabile']?></td>
<td class="actions">
<a href="update.php?id=<?php echo $row['id']; ?>" class="edit">
<i class="fas fa-pen fa-xs"></i>
</a>
<a href="delete.php?id=<?php echo $row['id']; ?>" class="trash">
<i class="fas fa-trash fa-xs"></i>
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
As you can see for each record i create an <href> with the redirect to the "delete" or "update", so i will pass the id via $_GET.
Is there a way to not show the id in the URL?
You need AJAX or a form
Using a link to delete is VERY dangerous since once viist from a crawler and your database is corrupt
I suggest something like this
delegate the click to the container table
use data-attributes for the ID
Ajax using POST - I use fetch to do that here
let fetchData = {
method: 'POST'
}
const url = "delete.php";
document.querySelector("form").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("trash") && confirm("Delete "+this.id+"?")) {
e.preventDefault();
fetchData["body"] = {
"id": this.getAttribute("data-id")
};
fetch(url, fetchData)
.then(function() {
console.log("deleted");
});
}
})
<a href="#" data-id="<?php echo $row['id']; ?>" class="trash">
<i class="fas fa-trash fa-xs"></i>
</a>
The id being shown in the URL is an absolute non-issue. That doesn't make the delete operation any more secure or insecure. What you have are one, perhaps two, other issues:
Any destructive operation must use POST requests. Normal links are free to be crawled by search engines, or preloaded by browsers. Which means, as soon as Google has crawled all your links, your database will be empty. That's why using POST is important, because every properly behaved HTTP client understands that POST is destructive.
If you're asking this question because you're afraid users can simply manipulate the id shown in the URL and delete other records they're not supposed to delete, then your real issue isn't in where you pass the id, but that you have no permission checking on your server.
For starters, use a form to create POST requests:
<form action="delete.php?id=<?php echo htmlspecialchars(urlencode($row['id'])); ?>"
method="post">
<input type="submit" value="Delete">
</form>
(Also note the proper way to URL-encode and HTML-encode the value, since you're embedding it in a URL in the context of HTML.)
On the PHP side, you'd process this something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_GET['id'];
// permission checking here
// delete record here
}
Instead of transporting the ID as a query parameter, you could also make it a form field:
<form action="delete.php" method="post">
<input type="hidden" name="id" value="<?php echo htmlspecialchars($row['id']); ?>">
<input type="submit" value="Delete">
</form>
On the server you'd then take the value from $_POST['id'] instead of $_GET['id'].
Note that this does not fundamentally change anything and is mostly a matter of taste.
You can customise that drab submit button in various ways, or perhaps switch to more interactive Javascript; but those are all just ways to pretty up this basic operation.
You can do it by something like this https://laravel.com/docs/5.8/encryption
At back-end you have to encrypt all your parameters like the following code:
$encryptedParameters = encrypt([
'id' => 132,
'something' => 'value',
'another_key' => 'another_value',
]);
and then send this value to your html template.
At front-end if you want to do it by GET do something like this and your users can't see what are you sending to your back-end because it is encrypted:
and if you want to do it by POST you can do it by Ajax or by generating a form and putting this value as a hidden input inside it. and then when user clicked on this link at back-end you have to decrypt it and use it's values like the following code:
$decryptedParameters = decrypt($_GET['s']);
$id = $decryptedParameters['id'];
$something = $decryptedParameters['something'];
$another_key = $decryptedParameters['another_key'];
Convert the GET request to a Post using a hidden form submission, a preferred method is to encrypt the record id when submitting the data.

Can't get data attribute value

Am trying to fetch the data attribute from a dynamically created table using foreach.Currently am getting the value od data attribute serviceid of first row only.
This is my php code :
<?php foreach ($service_arr as $service) {?>
<tr class="odd gradeX">
<td><button id="delete_btn" type="button"
data-serviceid="<?=$service->service_id?>" class="btn btn-default" data-toggle="modal"
data-target="#ServicesDeleteModal">Delete</button></td>
</tr>
<?php }?>
I want to fetch the value serviced from the table. Currently if I have three rows generated in foreach loop, am getting only the serviceid of first row only (<tr>).Why is that?
Jquery Code:
$('#delete_btn').click(function(){
var service_id = $(this).attr("data-serviceid");
console.log(service_id);
});
Please help
Thanks
You have duplicate ids. id selector is only binding the click to first element in matched DOM. Also you should use .data() to get set data attribute. and make sure that click event is binded when DOM is ready. something like this:
$(function(){$('.btn.btn-default').click(function(){
var service_id = $(this).data("serviceid");
console.log(service_id);
});});
The problem with the buttons you are generating is that they all have the same id attribute.
An "id" should be unique !
However, several tags can have the same "class" attribute;
You can replace
<td><button id="delete_btn" type="button" [...]
by
<td><button class="delete_btn" type="button" [....]
and change your jQuery selector by that :
$('.delete_btn').click(function(){ [...]

How to connect dynamic db value from one html element to another?

I had a hard time to formulate this question so it would be understandable, but here goes.
I have a page called apartments.php. On this page I list a number of rows from my database on apartments that you can show interest to rent.
The apartments are printed out like this:
<?php
foreach ($apartments as $apartment) { ?>
<tr>
<td><?php echo $apartment['apartments_room'] ?></td>
<td><?php echo $apartment['apartments_area'] ?></td>
<td><?php echo $apartment['apartments_rent'] ?></td>
<td><?php echo $apartment['apartments_address'] ?></td>
<td><?php echo $apartment['apartments_floor'] ?></td>
<td><?php echo $apartment['apartments_city'] ?></td>
<td><?php echo $apartment['apartments_freeFromDate'] ?></td>
<td>Apply!</td>
</tr>
<?php } ?>
Each apartment that gets printed out has its own button. When you press this button, a modal / popup will show.
And here's my problem.
When the modal pops up I want it to show the information of the apartment from witch I pressed the button.
So the data-reveal-id value from the button (that represent the specific apartment's db-id) is what I need to get into the modal divs id-value. Additionally I need to write out the address of that apartment (the db column 'apartments_address').
So this is how I need it to be:
<div id="HERE I NEED TO GET THAT ID" class="reveal-modal">
<h2>AND HERE I NEED TO PRINT OUT THE NAME OF THE ADDRESS</h2>
// Here i make room for an application form, but that's irrelevant...
</div>
This shouldn't be a hard thing, right? I hope you can help me out. Thanks!
(For more details if it matters, I'm using the modal of Foundation Zurb 4.)
First, your html isn't linking to a new page:
<a href="#" id="<?php echo $apartment['apartments_id'] ?>">
This should probably look something like this:
<a href="streetEdit.php?id=<?php echo $apartment['apartments_id'] ?>">
Then you can create a new php page named streetEdit.php
in that page, you can select the appropriate row from the database
$sql = "select * from myApartmentsTable where id = {$_GET['id']}";
See how the ID passed in the URL above shows up in $_GET?
next, do your query using the sql and output it on the page.
inside that you need an html form. Use a hidden input to keep track of the ID you are editing:
<form method="POST" action="updateStreet.php">
<input type="hidden" name="id" value="<?php echo $apartment['apartments_id'] ?>">
<input type="text" name="streetName" value="<?php echo $apartment['streetName'] ?>"
<input type="submit">
</form>
Then you need to write updateStreet.php. Since the form was POSTed you will use $_POST instead of $_GET
$id = $_POST['id'];
$streetName = $_POST['streetName'];
Note, you should use PDO for doing your sql queries
$sql = "update apartments set streetName = :name where id = :id";
$pdo = new PDO();
$stmt = $pdo->prepareStatement($sql);
$stmt->bindParam(':name', $streetName );
$stmt->bindParam(':id', $id);
http://php.net/manual/en/pdo.prepared-statements.php
This will prevent SQL injection attacks.. Ask further if you have more questions

how to save a javascript rendered countdown timer to mysql using PHP?

can someone please tell me how to save a javascript rendered countdown timer to mysql db using PHP ?
e.g
I have this button, that when someone clicks it, the countdown appears and starts counting.
so yeah, that's my problem, what's the best way to do in order to ensure that
- the exact date/time(in unix format) the button got clicked will be saved in db?
is this possible with PHP ?
// this is the PHP and HTML
<?php foreach($task->result() as $row): ?>
<tr>
<td><a title="<?php echo $row->descr; ?>"
href="#"><?php echo $row->title; ?></a>
</td>
<td><input type = "button"
id =<?php echo $row->title; ?>
value = "Unlocked"
onmouseover = "asktolock(this.id)"
onclick = "lockme(this.id)">
</td>
<td><?php echo $row->assign_to; ?></td>
<td><a id="txt"></a></td>
</tr>
Have your button populate a hidden formfield with a timestamp when it is clicked. Set the form to POST to a PHP script which processes the formfields and stores them where you like.
ETA: So on your form you'll need a field like this (with a unique name) for every timestamp you wish to store:
<input type='hidden' name='mytimestamp_unique' id='mytimestamp_unique' value=''/>
And then you'll add some code to your javascript function to set the value of the corresponding "mytimestamp" field. Something like:
function lockme(id){
//parse the id to get the unique part of the id which is also the unique part of mytimestamp_unique
var $hiddenfield=getElementById('mytimestamp_' + $uniquepart);
$hiddenfield.value=new Date().getTime();
//do other lockme stuff
}

Categories