I want to update the table after after the option from drop down list is selected. However, when I click approve button, the car plate is not updated in the database. Can someone help me? Thanks.
<?php
mysql_connect("l","t","")or die(mysql_error()); // connect to server
mysql_select_db("car")or die("Cannot connect to database") ;
$query=mysql_query("Select * from list "); //SQL Query
echo "<table><tr>
<th>Name</th>
<th>Destination</th>
<th>Time</th>
<th>Date</th>
<th>Car Requested</th>
<th>Purpose</th>
<th>Car Approve</th>
<th>Approve</th>
<th>Reject</th>
</tr>";
while($row=mysql_fetch_array($query))
{
if($row['status'] =='Pending'){
echo"<tr>";
echo'<td align="center">'.$row['employee']."</td>";
echo'<td align="center">'.$row['destination']."</td>";
echo'<td align="center">'.$row['time']."</td>";
echo'<td align="center">'.$row['date']."</td>";
echo'<td align="center">'.$row['car']."</td>";
echo'<td align="center">'.$row['message']."</td>";
echo'
<form action="approve.php" method="GET">
<td align="center">
<select name="car_plate">
<option>--Select Car--</option>
<option>WBN 3041</option>
<option>WWW 4545</option>
<option>BBB 1111</option>
<option>CCC 2222</option>
<option>DDD 3333</option>
</select>
</td>
</form>
';
echo'<td align="center">Approve </td>';
echo'<td align="center">Reject </td>';
echo"<tr>";
}
}
echo"</table>";
?>
<script>
function fapprove(id)
{
var r=confirm("Are you sure you want to APPROVE this record?");
if(r==true)
{
window.location.assign("approve.php?id=" + id);
alert('APRROVED! =)');
}
}
</script>
approve.php
if($_SERVER['REQUEST_METHOD'] == "GET")
{
mysql_connect("l", "r","") or die(mysql_error()); //Connect to server
mysql_select_db("car") or die("Cannot connect to database"); //Connect to database
$id = $_GET['id'];
$car_plate = $_GET['car_plate'];
mysql_query("UPDATE list SET status='Approved' WHERE id='$id'");
mysql_query("UPDATE list SET car_plate='$car_plate' WHERE id='$id'");
You didnt pass the carplate number in your javascript function. Use below code
function fapprove(id)
{
var r=confirm("Are you sure you want to APPROVE this record?");
if(r==true)
{
var carPlate = $("#car_plate").val();
window.location.assign("approve.php?id="+id+"&car_plate="+carPlate);
alert('APRROVED! =)');
}
}
add id to the select dropdown as <select id="car_plate" name="">
Hope it will work for you. If you need any help I'm ready to guide you...
Related
I am a student with a couple of weeks into PHP. What I am trying to do is Generate A table containing all users messages. Then I need a check box in each row. When the user hits the delete button rows with checkboxes marked will be deleted from table. The issue is that I can not figure out how to assign an individual value to each row of the HTML table to target with PHP. So I will only delete the rows that have been selected. I've only been able to delete all rows.
Here is what I got so far
<?php
//connect to database
include("../partials/.connect.php");
// select rows from contacts
$query = "SELECT * FROM contacts";
// display table headers
echo '<form>
<table width="100%" border="0" cellspacing="4" cellpadding="6">
<tr>
<th class="center">ID</th>
<th class="center">Name</th>
<th class="center">Phone</th>
<th class="center">Email</tdclass=center>
<th class="center">Message</th>
<th class="center"> <button type="submit" name="button1">Delete Selected</button</th>
</tr>';
// create loop to fetch all rows from DataBase
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["id"];
$field2name = $row["name"];
$field3name = $row["phone"];
$field4name = $row["email"];
$field5name = $row["message"];
// If delete button is clicked delete user
if(isset($_POST['button1'])) {
$sql = "DELETE FROM contacts WHERE id=$field1name";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
// display table data
echo '<tr>
<td class="center">'.$field1name.'</td>
<td class="center">'.$field2name.'</td>
<td class="center">'.$field3name.'</td>
<td class="center">'.$field4name.'</td>
<td class="center">'.$field5name.'</td>
<td class="center"> <input type="checkbox" id="if_checked" name="if_checked"></td>
</tr>
</form>';
}
$result->free();
}
?>
</body>
</html>
Your code is wrong, you just delete all your data along with your foreach run, so I just want to say keep learn more about programming logic since you're student
ok, for your question you have to put delete query before
$query = "SELECT * FROM contacts";
and your delete query should be based from foreach of checkbox value, and the most important thing is your checkbox name should be an array name since you will post multiple checkbox with the same name
<input type="checkbox" class="if_checked" name="if_checked[]">
and then you can use code like this
..................
include("../partials/.connect.php");
if(isset($_POST['button1'])) {
foreach($_POST['if_checked'] as $id) {
......your delete query
}
}
// select rows from contacts
$query = "SELECT * FROM contacts";
...................
You can use the checkbox as an array where you will store the ids when you select checkboxes for delete, you will loop through checkboxes and will be able to delete all selected rows.
I Was Able to solve this by storing the $row['id'] variable in the checkbox value instead of $Field1name. allowing me to specify which row to delete.
<?php
//connect to database
include("../partials/.connect.php");
// select rows from contacts
$query = "SELECT * FROM contacts";
//if delete button is set
if(isset($_POST['delete'])) {
$selected = $_POST['if_checked'];
//confirm record target
$confirm = mysqli_query($conn, "SELECT * FROM contacts WHERE id = '$selected'") or die("Not Found");
if(mysqli_num_rows($confirm)>0){
//record found delete
$delete_query = mysqli_query($conn, "DELETE from contacts where id = '$selected'")
or die("Not Deleted");
echo "<div><p>Record Deleted</p></div>";
} else {
//record not DataBase
die("Not deleted".mysqli_error());
}
}
// display table headers
echo '<form method="post" action="" role="form">
<table width="100%" border="0" cellspacing="4" cellpadding="6">
<tr>
<th class="center">ID</th>
<th class="center">Name</th>
<th class="center">Phone</th>
<th class="center">Email</th>
<th class="center">Message</th>
<th class="center"><input class="center" type="submit" name="delete" value="Delete"></th>
</tr>';
// create loop to fetch all rows from DataBase
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$field1name = $row["id"];
$field2name = $row["name"];
$field3name = $row["phone"];
$field4name = $row["email"];
$field5name = $row["message"];
// If delete button is clicked delete user
// display table data
echo '<tr>
<td class="center">'.$field1name.'</td>
<td class="center">'.$field2name.'</td>
<td class="center">'.$field3name.'</td>
<td class="center">'.$field4name.'</td>
<td class="center">'.$field5name.'</td>
<td class="center">
<input type="checkbox" id="if_checked" name="if_checked" value="'.$row['id'].'"></td>
</tr>
</form>';
}
$result->free();
}
?>
</body>
</html>
I have added a button at the end of the row of my datatable intended to update the information in the database for the specific row chosen.
When I click the update button, a form pops us with the relevant fields to update.
Ideally, I would like the form to be autopopulated with the information from the table row which I have chosen to update
Code...
Table:
<div class="viewalljob tab-pane show active" id="profile" role="tabpanel" aria-labelledby="profile-tab">
<h2>Edit Job Table</h2>
<table id="edit-job-table" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th class="job_id">ID</th>
<th class="job_date">Date</th>
<th class="job_company">Company Name</th>
<th class="job_contact">Contact</th>
<th class="job_from">From</th>
<th class="job_to">To</th>
<th class="job_driver nowrap">Driver</th>
<th class="job_income">Income (£)</th>
<th class="job_payment">Payment (£)</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<!--Fetch from Database-->
<!--Connect To Database-->
<?php
$host_name = 'xxx';
$database = 'xxx';
$user_name = 'xxx';
$password = 'xxx';
$conn = mysqli_connect($host_name, $user_name, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT *,AS markup
FROM `table`
GROUP BY id";
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
// output data of each row
while($result = mysqli_fetch_assoc($query)) {
echo "<tr>
<td class='job_id'>".$result['id']."</td>
<td class='job_date'>".$result['adddate']."</td>
<td class='job_company'>".$result['customer']."</td>
<td class='job_contact'>".$result['addcontact']."</td>
<td class='nowrap job_from'>".$result['addfrom']."</td>
<td class='nowrap job_to'>".$result['addto']."</td>
<td class='nowrap job_driver'>".$result['adddriver']."</td>
<td class='currency job_income'>".$result['addincome']."</td>
<td class='currency job_payment'>".$result['addpayment']."</td>
<td><button type='button' name='update' id=".$result['id']." class='btn btn-warning btn-xs update updatebtn'>Update</button></td>
<td><button type='button' name='delete' id=".$result['id']." class='btn btn-danger btn-xs delete deletebtn'>Delete</button></td>
</tr>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</tbody>
</table>
</div>
<div id="contactForm3">
<h1>Edit Job</h1>
<form id="dataForm" name="dataform" method="POST" action="/">
/**** FORM DATA ****/
</form>
</div>
JS to open form:
$(function() {
// contact form animations
$('.update').click(function() {
$('#contactForm3').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm3");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
I have added the update button using <td><button type='button' name='update' id=".$result['id']." class='btn btn-warning btn-xs update updatebtn'>Update</button></td> I have given the id=".$result['id']." hoping that I can use this to populate the form from the ID
I am assuming that I will need to connect to the database table, something like:
<form>
<?php
//Connect to Database ... //
$sql = SELECT * FROM `table`
WHERE ID = ???
$query = mysqli_query($conn, $sql);
if (mysqli_num_rows($query) > 0) {
// output data of each row
while($result = mysqli_fetch_assoc($query)) {
echo "<span>
<label> label1 </label>
<input value = ".$result['column'].">
</span>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Im hoping that this is correct and someone can help me do this?
Actually you can acheive this using javascript/jquery, get row element from table displayed, from which you can get every columns/inputs value like as below:
$('.updatebtn').on('click', function(e) {
e.preventDefault();
var row = $(this).closest('tr'); //get table row from displayed table.
var form = $('#contactForm3').fimd('form'); //form to be populate.
//make sure your form input field with same name as the column name.
//now create form_data object with key as same name as column/input name .
var form_data = { 'id' : row.find('.job_id').value(),
'adddate' : row.find('.job_date').value(),
.....
'addpayment' : row.find('.job_payment').value()
}
//Apply loop to populate values in form.
$.each(form_data, function(key, value){
form.find('input[name="'+ key +'"]').val(value);
});
});
Then on form submit update database record/row using PHP (hope you know that well, if not let me know I will update my code).
I want to disable the two buttons in a single row if the button will be clicked and won't affect the buttons of another row.
I dont know how to disable an echo button of the table. I want to disable the "Accept" and "Reject" button if one of those was been clicked.I provide a screenshot so that you can easily understand what I mean. Thank you in advance.
Here's my php code. It names as app.php
<?php
//connect to database
$con = mysqli_connect('127.0.0.1','root','');
//select database
mysqli_select_db($con, 'appointment');
//select query
$sql = "SELECT * FROM service";
//Execute the query
$records = mysqli_query($con,$sql)
?>
<html>
<head>
<title>Appointment Schedule</title>
</head>
<body>
<table width = "100%" border = "5px" height = "20%">
<tr align = "left">
<th>First Name</th>
<th>Middle Name</th>
<th>Last Name</th>
<th>Address</th>
<th>Date</th>
<th>Time</th>
<th>Office</th>
<th>Service</th>
<th>Contact No.</th>
<th>Remarks</th>
</tr>
<?php
while($row = mysqli_fetch_array($records))
{
echo "<tr><form action = 'display.php' method = post>";
echo "<input type=hidden name=id value='".$row['ID']."'>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$row['mname']."</td>";
echo "<td>".$row['lname']."</td>";
echo "<td>".$row['address']."</td>";
echo "<td>".$row['date']."</td>";
echo "<td>".$row['time']."</td>";
echo "<td>".$row['office']."</td>";
echo "<td>".$row['services']."</td>";
echo "<td><name = number>".$row['contactno']."</td>";
echo "<td>".$row['remarks']."</td>";
echo "<td><input type =submit value='Accepted' name=accept>";
echo "<td><input type =submit value='Rejected' name=reject>";
echo "</form></tr>";
}
?>
</table>
</body>
</html>
here's my another one php code. It names display.php
<?php
//connect to database
$con = mysqli_connect('127.0.0.1','root','');
//select database
mysqli_select_db($con, 'appointment');
if($_POST['accept'])
{
$sql = "UPDATE service SET remarks = 'Accepted' WHERE ID=$_POST[id]";
}
else if($_POST['reject'])
{
$sql = "UPDATE service SET remarks = 'Rejected' WHERE ID=$_POST[id]";
}
//Execute Query
if(mysqli_query($con,$sql))
header("refresh:1; url=app.php");
else
echo "Unsuccessful";
?>
here's the screenshot of my work
Sample of my database table using php
Kindly try the below code:
Provide the condition to display the buttuon
echo "<td><input type =submit value='Accepted' name=accept>";
echo "<td><input type =submit value='Rejected' name=reject>";
if($row['remarks'] == 'Accepted' || $row['remarks'] == 'Rejected')
{
echo "<td><input type =submit disabled value='Accepted' name=accept>";
echo "<td><input type =submit disabled value='Rejected' name=reject>";
}
simply I have two tables: Course_table and Major_table, and they both have relationship entity. I have created a drop down list and linked it to the Major_table, and an html table linked it to the Course_table. What I want to do is display data on the Course_table based on the selection from the drop down list, but when I select something and press 'Filter' it shows an empty table.
Here is my first code:
<form method="post" action="staff-page.php">
<label for="majorFilter">Select Major: <select id="majorFilter" name="majorFilter">
<option value="0">Select a major</option>
<?php
include ('partials/connectDb.php');
$sql = "SELECT * FROM major_table;";
$run_query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($run_query)) {
$m_id = $row['major_id'];
$m_name = $row['major_name'];
echo "<option value='{$m_id}'>{$m_name}</option>";
}
?>
</select></label>
<Button type="button" name="filter" id="filter">Filter</Button>
</form>
And this is my second code:
<table style="height: 400px; width: 600px; overflow: auto; display: none;" id="courseTable">
<caption>Course Table</caption>
<thead>
<tr>
<th>Name</th>
<th>Code</th>
<th style="padding-right: 10px;">Cr</th>
<th>Major</th>
<th>Students Enrolled</th>
</tr>
</thead>
<?php
error_reporting(0);
$conn = mysqli_connect('localhost', 'root', '', 'srs-db') or die('ERROR: Cannot Connect='.mysql_error($conn));
$query = "SELECT course_table.course_name, course_table.course_code, course_table.cr, major_table.major_name, course_table.students_enrolled FROM course_table
INNER JOIN major_table ON course_table.major = major_table.major_id
WHERE course_table.major = '$m_id';";
$sql = mysqli_query($conn, $query);
while ($course = mysqli_fetch_array($sql)) {
# code...
echo "<tr>";
echo "<td>.$course[course_name].</td>";
echo "<td>.$course[course_code].</td>";
echo "<td>.$course[cr].</td>";
echo "<td>.$course[major_name].</td>";
echo "<td>.$course[students_enrolled].</td>";
echo "</tr>";
}
?>
</table>
Your help is much appreciated :)
In your second code, you need to make your <tr> id based and apply a class for all of them. like this:
while ($course = mysqli_fetch_array($sql)) {
# code...
echo "<tr class='all_trs' id='display_".$m_id."' style='display:none;'>";
echo "<td>.$course[course_name].</td>";
echo "<td>.$course[course_code].</td>";
echo "<td>.$course[cr].</td>";
echo "<td>.$course[major_name].</td>";
echo "<td>.$course[students_enrolled].</td>";
echo "</tr>";
}
And then you need to place a JQuery Onchange method in Document ready:
<script type="text/javascript">
$(function() {
// will be triggered on Change of your Select box
$( "#majorFilter" ).change(function() {
alert("Select Box changed");
// Hiding all Trs by default.
$( ".all_trs" ).hide();
// Showing just the specific TR which is selected in select box
$( "#display_" + $(this).val() ).show();
});
});
</script>
You might notice, that I have used display:none for echoing the <tr> html, it is because, I'm hiding all the TRs by default and will display only the selected one on Select Box change.
Hope some one can help me out here, i guess am not calling my functions right.
Am trying to retrieve some data from my database and have a delete link attached to each items being retrieved, so that when ever i click on delete, it will delete that particular item which have the delete function.
My Code to retrieve items from database are as follows.
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$count = 1;
$y = mysql_query("SELECT * FROM transaction");
if(mysql_num_rows($y) != 0){
echo "<table bgcolor=\"white\" width=\"1000\" bordercolor=\"grey\" border=\"5\" >";
echo "<tr>
<td align=\"center\">No</td>
<td align=\"center\">Date</td>
<td align=\"center\">Current Balance</td>
<td align=\"center\">Avaliable Balance</td>
<td align=\"center\">Account Status</td>
<td align=\"center\">Delete Account</td>
</tr>";
while ($z = mysql_fetch_array($y, MYSQL_BOTH)){
echo "<tr>
<td align=\"center\">".$count++."</td>
<td align=\"center\">".$z[1]."</td>
<td align=\"center\">".$z[2]."</td>
<td align=\"center\">".$z[3]."</td>
<td align=\"left\" width=\"300\">".$z[4]."</td>
<td>delete</td>
</tr>";
}
echo "</table>";
}
?>
And my code to delete
<?php
session_start();
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$id = $_GET['id'];
$sql = mysql_query("DELETE FROM transaction WHERE id='$id' LIMIT 1") or die (mysql_error());
header("Location: vacct.php");
?>
I know am missing out the logic here and hope somebody can direct me or show me the easy way out. at the moment i can successfully retrieve my items from the data base my only problem is to be able to apply the delete function each time the delete button is tapped.
You have to pass the id when you click on the delete link:
<a href=\"delete.php?id=$z[theIdKey]\">
Use the below code.I have added validation and encryption
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$count = 1;
$y = mysql_query("SELECT * FROM transaction");
if(mysql_num_rows($y) != 0){
echo "<table bgcolor=\"white\" width=\"1000\" bordercolor=\"grey\" border=\"5\" >";
echo "<tr>
<td align=\"center\">No</td>
<td align=\"center\">Date</td>
<td align=\"center\">Current Balance</td>
<td align=\"center\">Avaliable Balance</td>
<td align=\"center\">Account Status</td>
<td align=\"center\">Delete Account</td>
</tr>";
while ($z = mysql_fetch_array($y, MYSQL_BOTH)){
echo "<tr>
<td align=\"center\">".$count++."</td>
<td align=\"center\">".$z[1]."</td>
<td align=\"center\">".$z[2]."</td>
<td align=\"center\">".$z[3]."</td>
<td align=\"left\" width=\"300\">".$z[4]."</td>
<td>delete</td>
</tr>";
}
echo "</table>";
}
?>
code to delete
<?php
session_start();
$con = mysql_connect("localhost","root","");
mysql_select_db("uloaku", $con);
$id = base64_decode($_GET['id']);
if(!empty($id)){
$sql = mysql_query("DELETE FROM transaction WHERE id='$id' LIMIT 1") or die (mysql_error());
}
header("Location: vacct.php");
?>
<td>delete</td>
How are you passing the id to delete to your delete.php script?
Change:
<td>delete</td>
to:
<td>delete</td>
if $z[0] is the ID.
In your delete.php, make sure you also escape the word "transaction" using backtick:
DELETE FROM `transaction` WHERE id=123
this is because "transaction" is a reserved mysql keyword.
Please also read on SQL Injections.