HTML PHP database - edit/delete button - passing value - php

im rather amateur with php and even more so with js. I have created a database table with an edit & delete button, as shown in the screenshot. (if anyone is also able to see why there is a gap between my header and body of table that would be great, i have no clue why this is cropping up, doesnt seem to be css).
The idea is to just click the delete button, pass the 'AwbNo' over to the delete.php page in order to delete the entire row from the database, and then automatically return to the page to see the updated table, if redirection can be avoided, even better just to make the operation smoother. Any help would be greatly appreciated, hope my code below is enough for aid
so select a row to delete>click delete>confirmation>row deleted from db. That is the process i am aiming to achieve
example database screenshot
<table class="table">
<thead>
<tr>
<th>Awb Number</th>
<th>Vessel</th>
<th>Client</th>
<th>Pieces</th>
<th>Total Weight</th>
<th>Carrier</th>
<th>Sender</th>
<th>Status</th>
<th>Arrival Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php //BEGINNING OF PHP
include("login/dbinfo.inc.php");
$comm=#mysql_connect(localhost,$username,$password);
$rs=#mysql_select_db($database) or die( "Unable to select database");
$sql="SELECT AwbNo, VesselName, ClientCode, Pieces, Weight, Carrier, Sender, Status, DATE_FORMAT(ArrivalDate, '%d-%m-%yyyy') FROM tbl_import";
$result = mysql_query($sql) or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);
echo "<p>There are $num_rows records in the Customer table.</p>";
echo "<table class=\"table\">\n";
while ($get_info = mysql_fetch_array($result))
{
echo ("<tr>\n");
echo ("<td>".$get_info["AwbNo"]."</td>");
echo ("<td>".$get_info["VesselName"]."</td>");
echo ("<td>".$get_info["ClientCode"]."</td>");
echo ("<td>".$get_info["Pieces"]."</td>");
echo ("<td>".$get_info["Weight"]."</td>");
echo ("<td>".$get_info["Carrier"]."</td>");
echo ("<td>".$get_info["Sender"]."</td>");
echo ("<td>".$get_info["Status"]."</td>");
echo ("<td>".$get_info["ArrivalDate"]."</td>");
?>
<td>
<div id="outer">
<div class="inner"><button type="submit" class="msgBtn" onClick="goToURL()" > Edit </button></div>
<div class="inner"><button type="submit" class="msgBtn2" onClick="goToURL1()"> Delete </button></div>
</div>
</td>
<?php
echo ("</tr>\n");
}
echo "</table>\n";
mysql_close();
?> <!--END OF PHP-->
</tbody>
</table>
Below is the js script to redirect user page when clicking on the 'edit' or 'delete' button.
<script>
function goToURL() {
window.open('php/edit.php');
}
function goToURL1() {
window.open('php/delete.php');
}
</script>
And below is the supposing 'delete.php' page to delete the record from the db on a live server, this is only an example, im not exactly sure if it is correct.
<?php
include("dbinfo.inc.php");
$comm=#mysql_connect(localhost,$username,$password);
$rs=#mysql_select_db($database) or die( "Unable to select database");
$AwbNo=$_POST['AwbNo'];
$sql="DELETE FROM tbl_import where AwbNo=$AwbNo";
mysql_query($sql)or die("Delete Error: ".mysql_error());
mysql_close();
echo "Record was successfully deleted.\n";
?>

The issue your having is because you need to pass the primary key that AwbNo in you case, along with the Edit /Delete link, so that the correct record is selected from DB. This is not happening in your case.
The code for the table needs to look something like mentioned below for the edit & delete links.
echo '<td>&nbspEdit&nbsp</td>';
echo '<td>&nbspDelete&nbsp</td>'
Also add this script in same page.
<script>
function delete_user(uid)
{
if (confirm('Are You Sure to Delete this Record?'))
{
window.location.href = 'delete.php?id=' + uid;
}
}
</script>
delete.php can have just this code:
<?php
include("dbinfo.inc.php");
$comm=#mysql_connect(localhost,$username,$password);
$rs=#mysql_select_db($database) or die( "Unable to select database");
$id = $_GET['id']; // $id is now defined
mysqli_query($conn,"DELETE FROM tbl_import where AwbNo='".$id."'");
mysqli_close($conn);
header("Location: index.php"); //redirect to relevant page
?>

Related

Delete a line from a table in PHP

i'm currently working on an admin which permit to the user who has the rights to delete any account with a button, and all the accounts are displayed in a table and stored in a database (i'm using MySQL). For each row of the , there is a delete button, and i would like that, by pressing the button of the choosed row, it delete the account of the row selected. I dont really know how to do it clearly that's why I ask.
Can someone explain me the approach that i should take and give me an idea.
Have a good day.
[the admin pannel screen][1]
Here is where I am in my code :
<?php
require_once('testadmin.php');
if(!$isAdmin) {
header('Location: index.php');
}
include_once('./includes/head.php');
include_once('./includes/nav.php');
require_once('./lib/db.php');
// users
$stmt = $db->prepare('SELECT * FROM users');
$stmt->execute();
$users = $stmt->fetchAll();
?>
<main>
<table id="usersTable">
<h1 style="text-align: center;margin-top: 25px;">Users</h1>
<tr>
<th>ID</th>
<th>Username</th>
<th>Email</th>
<th>Role</th>
<th> </th>
</tr>
<?php
foreach ($users as $user)
{
echo
'<tr>
<td>'.$user['id'].'</td>
<td>'.$user['username'].'</td>
<td>'.$user['email'].'</td>
<td>'.$user['role'].'</td>
<td><button class="btn-danger" onclick=\'return confirm("Confirm account delete?");\'>
Delete account</button></td></tr>';
}
echo "</table>";
?>
delete.php :
NOTE : this is actually for delete the current connected account.
<?php
require('./lib/db.php');
session_start();
if(empty($_SESSION['user'])){
header('Location: login.php');
}
$user = $_SESSION['user'];
$req = $db->prepare('DELETE FROM users WHERE id=:id');
$req->bindValue(':id', $user["id"], PDO::PARAM_INT);
$req->execute();
unset($_SESSION['user']);
session_destroy();
header('Location: index.php');
Pass the identifier for the record to the delete.php page:
<a href="delete.php?id=' . $user['id'] . '" class="delete" style="color: #fff">
Then in delete.php you can reference $_GET['id'] and use that value in your SQL query to delete that specific record.
Note of course that within delete.php you'll probably want to make sure the current user is authorized to delete that record.

how to print a specific data that is stored in mysql database using php

Hi I have added a function to my website where the user can cancel a booked ticket using the code: cancel.php
<?php
session_start();
include('config.php');
mysqli_query($con,"delete from tbl_bookings where book_id='".$_GET['id']."'");
$_SESSION['success']="Booking Cancelled Successfully";
header('location:profile.php');
?>
and I tried to add a function to the same ticket that the user can cancel to print ticket, so the user can print this ticket, the code i used is: print.php
<?php
session_start();
include('config.php');
window.print(mysqli_query($con,"select from tbl_bookings where book_id='".$_GET['id']."'"));
header('location:profile.php');
?>
the link to these two classes in a class called profile.php, and this bit is in the line where it says:
Cancel /Print Ticket
I would be happy if you can tell me how to print this data.. thanks
the use of $bkg
$bk=mysqli_query($con,"select * from tbl_bookings where user_id='".$_SESSION['user']."'");
if(mysqli_num_rows($bk))
{
?>
<table class="table table-bordered">
<thead>
<th>Booking Id</th>
<th>Movie</th>
<th>Theatre</th>
<th>Screen</th>
<th>Show</th>
<th>Seats</th>
<th>Price</th>
<th></th>
</thead>
<tbody>
<?php
while($bkg=mysqli_fetch_array($bk))
{
$m=mysqli_query($con,"select * from tbl_movie where movie_id=(select movie_id from tbl_shows where s_id='".$bkg['show_id']."')");
$mov=mysqli_fetch_array($m);
$s=mysqli_query($con,"select * from tbl_screens where screen_id='".$bkg['screen_id']."'");
$srn=mysqli_fetch_array($s);
$tt=mysqli_query($con,"select * from tbl_theatre where id='".$bkg['t_id']."'");
$thr=mysqli_fetch_array($tt);
$st=mysqli_query($con,"select * from tbl_show_time where st_id=(select st_id from tbl_shows where s_id='".$bkg['show_id']."')");
$stm=mysqli_fetch_array($st);
?>
<tr>
<td>
<?php echo $bkg['ticket_id'];?>
</td>
<td>
<?php echo $mov['movie_name'];?>
</td>
<td>
<?php echo $thr['name'];?>
</td>
<td>
<?php echo $srn['screen_name'];?>
</td>
<td>
<?php echo $stm['start_time'];?>
<?php echo $stm['name'];?>
</td>
<td>
<?php echo $bkg['no_seats'];?>
</td>
<td>
£ <?php echo $bkg['amount'];?>
</td>
<td>
<?php if($bkg['ticket_date']<date('Y-m-d'))
{
?>
<i class="glyphicon glyphicon-ok"></i>
<?php
}
else
{?>
Cancel /Print Ticket
<?php
}
?>
</td>
</tr>
<?php
}
?></tbody>
enter image description here
You can't call window.print() within PHP code since it's a javascript function
header('location:profile.php'); will redirect the page before the javascript have the chance to execute the code. Replace that code with a javascript code which executes after you print the page.
Your print.php:
<?php
session_start();
include('config.php');
$result = mysqli_query($con, "select * from tbl_bookings where book_id='{$_GET['id']}'"); // You should replace this with prepare statement
$row = $result->fetch_array();
// assume that your booking table has columns: id, movie_name, time
echo "<table>
<tr><td>Booking ID</td><td>{$row['id']}</td></tr>
<tr><td>Movie Name</td><td>{$row['movie_name']}</td></tr>
<tr><td>Time</td><td>{$row['time']}</td></tr>
</table>";
?>
<script>
window.print();
window.location.href = "profile.php"
</script>
Stop coding now!
You need to learn the very basic of how PHP + MySQL + HTML + JS work together.
At the moment, you don't need to know what's wrong with your code. You need to learn some basic tutorials, then re-write your code from scratch. Many tutorials all over the intermet. Read this.
Extra Explanation
Server = where your code lives.
Client = the browser.
PHP & MySQL live in the server ONLY, work on the server, handled by the server.
HTML + CSS + JS prepared by the server, server then send it to client, then handled by client (the browser). So they start working when in the client (the browser). As long as they're on the server, they are just strings.
So it's always like:
Browser request file from server (http://www.mywebsite.com/something.php). This is known as the request.
Server runs the php file (something.php), which may generate output (HTML+CSS+JS), server then send the output to the client (browser). This is known as response.
Client (browser) then receives the output (as plain strings), then browser runs the code (JS).
Conclusion:
Don't tell server to run JS, don't tell client (browser) to run PHP or MYSQL.
I've modified your code to work and to much more secured way using prepare statement.
<table>
<tr><th> id </th> <th> time </th> </tr>
<?php
if (!$bk = $con->prepare("select * from tbl_bookings where user_id = ? ")) {
echo $con->error; // show error message when SQL query is wrong or goes kaboom!
} else{
$bk->bind_param("s",$_SESSION['user']); //bind the blind parameters, "s" stands for string
$bk->execute ();// execute the query
$bk_result = $bk->get_result(); // get results
}
while ($bk_row = $bk_result->fetch_assoc()){ ?>
<tr><td> <?php echo $bk_row['id']; ?> </td> <td> <?php echo $bk_row['id'] ?> </td> </tr>
<?php } //end while loop ?>
</table>

$_GET does not work and query the property

I have a problem with $_GET method. I have retrieved some data about admins of a webpage from database & I added a hyperlink for users to get the information about that them.
Here's the code in my 1st page:
<?php if(($adminlevel)==1){
echo '
<h4 class="widgettitle">List of admins</h4>
<table class="table responsive">
<thead>
<tr>
<th>Admin Level</th>
</tr>
</thead>
'; getAdmins(); echo '
</table>
';
}else{
echo '<h4 class="widgettitle">You dont have permission to see this table</h4>';
}
?>
<div class="divider15"></div>
The function getAdmins() goes like this:
<?php
function getAdmins(){
global $con;
$get_admin = "select * from admins order by id";
$run_admin = mysqli_query($con,$get_admin);
while($row_admin = mysqli_fetch_array($run_admin)){
$id_admin = $row_admin['id'];
echo "
<tbody>
<tr>
<td>Trident</td>
<td class='center'><a href='editlevel.php?id=$id_admin' title='Clik to change admin level' target='_blank'>$adminlevel_admin</a></td>
</tr>
</tbody>
";
}
}
?>
As you see I link the users from my first page to another page which is called editlevel.php by the function getAdmins().
Therefore I made my hyperlink like this:
<a href='editlevel.php?id=$id_admin'>$adminlevel_admin</a>
And Here's the editlevel.php page:
<body>
<?php
if (isset($_GET['id_admin'])){
$result_id = $_GET['id_admin'];
$get_result = "select * from admins where id='$result_id'";
$run_result = mysqli_query($con,$get_result);
while($row_result= mysqli_fetch_array($run_result)){
$id_target = $row_result['id'];
$username_target = $row_result['username'];
$adminlevel_target = $row_result['adminlevel'];
$email_target = $row_result['email'];
echo '
<div class="mainwrapper">
<div class="header">
'; include "php/php_includes/overall/header.inc.php"; echo'
</div>
<div class="leftpanel">
';include "php/php_includes/overall/leftpanel.inc.php"; echo '
</div><!-- leftpanel -->
<div class="rightpanel">
'; include "php/php_includes/gadgets/rightpanel.editlevel.php"; echo '
</div><!--rightpanel-->
</div><!--mainwrapper-->
';
}
}
?>
</body>
So basically I used if (isset($_GET['id_admin'])){ to get the results of the item which user clicked & try to retrieve the data of that item from database via that.. But the problem is nothing appears at my screen. No error message & no result. Please if you know how can I solve it please let me know!
It appears that your link is:
<a href='editlevel.php?id=$id_admin'>$adminlevel_admin</a>
When it should be:
<a href='editlevel.php?id_admin=$id_admin'>$adminlevel_admin</a>
In order for it to work with:
if (isset($_GET['id_admin'])){
$result_id = $_GET['id_admin'];
Edit: It goes without saying, you should never trust user input (such as $_GET). These values should be validated and sanitised before being used in SQL queries.

How to Set a MYSQL Variable Value to 1 when text is clicked in php?

First off I know very little about php and am still learning so please go easy on me with your answers. Basically I'm working on a project that functions like a social network site, users are able to send and receive private messages etc. I have got this all working great and the messages even go to the messages_deleted.php page when you set the variable value from '0' to '1' in the database.
Is there a way to let the user do this themselves, to delete their own messages by clicking a piece of text?
I'm working in php so would need a piece of php code which allows me to do this if anyone has any ideas?
Here is my current php script I'm using:
<?php
$page_title = "Messages";
include('includes/header.php');
confirm_logged_in();
include ('includes/mod_login/login_form.php');
?>
<div class="modtitle">
<div class="modtitle-text">Inbox</div>
</div>
<div class="modcontent">
<strong>Inbox</strong> | Sent Messages | Deleted
<br /><br />
<table width="100%" border="0" cellpadding="5" cellspacing="0">
<tr bgcolor="#CCCCCC">
<td width="30%"><strong>Recieved</strong></td>
<td width="20%"><strong>From</strong></td>
<td width="28%"><strong>Subject</strong></td>
<td width="0%"><strong>Read/Unread</strong></td>
<td width="0%"><strong>Delete</strong></td>
</tr>
<?php
$inbox_set = get_inbox();
while ($inbox = mysql_fetch_array($inbox_set)) {
?>
<?php
if ($inbox['read'] == 0) { ?>
<tr bgcolor="#6666B3">
<?php }
if ($inbox['read'] == 1) { ?>
<tr>
<?php } ?>
<td><?php
$datesent1 = $inbox['date_sent'];
echo "$datesent1"; ?></td>
<td><?php echo "<a href=\"profile.php?id={$inbox['from_user_id']}\">{$inbox['display_name']}"; ?></td>
<td><?php echo "<strong>{$inbox['subject']}</strong>"; ?></td>
<td><?php if ($inbox['read'] == 0) {
echo "Unread";
}
if ($inbox['read'] == 1) {
echo "Read";
}
?></td>
<td>
<?php
if ($inbox['delete'] == 0) {
echo "Delete";
}
if ($inbox['delete'] == 1) {
echo "$deleted_set;";
}
; ?></td>
</td>
<?php
}
?>
</tr>
</table>
</div>
<?php include('includes/footer.php'); ?>
What I really need is a way of making the 'delete' row clickable so that when a user clicks on it it sets the value to '1'. If it can be done that way it would be a lot easier for me I think.
Yes. It is quite simple. You can take a look at some basic jQuery and AJAX working on the page. Here's a link to documentation of the API.
if you dont want to use Ajax, you should create a link that redirects user to a page for example delete_message.php?mid=16 where mid is the message id users wants to delete,
then on server side first check that this message belongs to the user that wants to delete it, so a user cant delete other peoples messages,
then run a mysql code whish should look like this : UPDATEmessagesSETdeleted= '1' WHEREid= '16'
i hope it helps you, let me know if you had any other questions.
Assumptions
If you can include jQuery to your project, then you can use PHP + AJAX to work on this. Say, you have the PHP file which makes the message deleted as messages_deleted.php. And to delete a message, I assume that, you need to pass a parameter id to the script, which finally comes this way: messages_deleted.php?id=5.
Also assuming that the code in your PHP file is:
<?php
mysql_connect();
if (mysql_query("UPDATE `messages` SET `deleted` = 1 WHERE `id` = " . mysql_real_escape_string($_GET["id"])))
die ("deleted");
else
die ("error");
?>
Code
You can use jQuery's $.getScript() to do the work for you.
And if the message is valid and deleted, your PHP Script should die("deleted");. Adjust accordingly.
$(document).ready(function(){
$("table tr").click(function(){
$.getScript("messages_deleted.php", function(data){
if (data == "deleted")
alert("Message Deleted");
});
});
});

passing a php array item into a javascript popup window to be edited and updated in mysql db

I am creating a diabetes management system for a university project. One of the features of this system is for the patient to be able to send latest glucose readings and for the nurse to be able to login and comment on those readings.
I have been able to code the patient feature, however I wish to add a comment button in the comments column, which when clicked, brings up a popup window or a textbox for the nurse to be able to comment on that specific record. If a comment has not already been entered, an empty box should come up, however if there has been a previously entered comment, it should be displayed in the box to be updated and sent back to the mysql database. I would like to ask if someone could give me a way to include this comment box and code for the existing value to be displayed in the box and if there is no existing comment, then a new comment can be entered and stored in the database.
Below is my php code.
<?php//run query
$result = mysql_query($GetReadings);
?>
<table>
<tr>
<th>Date</th>
<th>Time</th>
<th>Glucose Level</th>
<th>SBP</th>
<th>DBP</th>
<th>Comments</th>
</tr>
<?php
//display results
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<tr>
<td><?php echo $row["Date"]; ?> </td>
<td><?php echo $row["Time"]; ?> </td>
<td><?php echo $row["GlucoseLevel"]; ?> </td>
<td><?php echo $row["SBP"]; ?> </td>
<td><?php echo $row["DBP"]; ?> </td>
<td><?php echo $row["Comments"];
<?php
//if statement to add comment link if user is a nurse
if ($_SESSION['User_level'] == 2)
{
//code for comments
}
?> </td>
</tr>
<?php
//end of while loop
}
?>
Hope I haven't missed out any crucial information.
Use the javascript function :
window.open(URL, windowName[, windowFeatures])
Where, URL - desired URL to display a page containing Textbox, use any window name you want.
Echo <a> or button with a onclick event eg:
Add Comment
Edit
The most basic way to achieve is, echo a <div></div> containing the past comments, the text box for new comments and Send/Cancel buttons. The trick is to set the display:none style property of that div. You the following code a guideline :
Echo the following code if the User has right user level.
Show Comments
<div id="comment-<?php echo $row['id']?>" style="display:none">
//display previous comments
<form method="post" action="addComment.php?id=<?php echo $row['id']?>">
<textarea name="comment"></textarea>
<input type="submit" value="Add Comment" /><input type="button" onclick="hideComment('<?php echo $row['id']?>')">
</form>
</div>
<script type="text/javascript">
function hideComment(id) {
document.getElementById('comment-' + id).style.display = 'none';
}
function showComment(id) {
document.getElementById('comment-' + id).style.display = 'block';
}
</script>

Categories