Choosing specific table to submit - javascript

I am currently calling tables using php in order to show pending purchase requests. An admin will either approve or deny these requests based on the contents of each table. Each table will have a unique identifier and this is how they are divided. I am trying to determine how I can approve/deny each table individually, but I'm new to jQuery. I've used it before in a similar manner but can't seem to find a solution for what I am trying to do.
Right now, I'm just trying to set up an alert to make sure that the function is working properly.
PHP code showing table format (code is in a while loop):
echo "<form method='POST' onsubmit='moveTable(this)'>
<table id='pendingTable'>
<tbody>
<tr style='background-color:$bgcolor'>
<input type='hidden' value='".$RNrow['request_number']."'>
<td id='name'>".$PRrow['ItemName']."</td>
<td>".$PRrow['ItemDesc']."</td>
<td>".$PRrow['BrandName']."</td>
<td>".$PRrow['ManNum']."</td>
<td>".$PRrow['NSN']."</td>
<td>".$PRrow['ItemCost']."</td>
<td>".$PRrow['Qty']."</td>
</tr>
</tbody>";
<input type='submit' value='Approve' onclick=\"return confirm ('Are you sure you want to approve this request?')\">
<input style='margin-left:5px' type='submit' value='Deny' onclick=\"return confirm ('Are you sure you want to deny this request?')\">
<script type="text/javascript">
function moveTable(){
$('#pendingTable tr').each(function(){
alert('hello');
});
}
</script>
The information from these tables would then be moved to an 'approved/denied' mysql table. I figure it may have to do with the uniqueness of the table id but haven't found a way around that. Any help would be appreciated.

You cannot use id as it is supposed to be unique within the DOM, you can use classes instead like this:
echo "<form method='POST' onsubmit='moveTable(this)'>
<table class='pendingTable'>
<tbody>
<tr style='background-color:$bgcolor'>
<input type='hidden' value='".$RNrow['request_number']."'>
<td id='name'>".$PRrow['ItemName']."</td>
<td>".$PRrow['ItemDesc']."</td>
<td>".$PRrow['BrandName']."</td>
<td>".$PRrow['ManNum']."</td>
<td>".$PRrow['NSN']."</td>
<td>".$PRrow['ItemCost']."</td>
<td>".$PRrow['Qty']."</td>
</tr>
</tbody>";
<input type='submit' value='Approve' onclick=\"return confirm ('Are you sure you want to approve this request?')\">
<input style='margin-left:5px' type='submit' value='Deny' onclick=\"return confirm ('Are you sure you want to deny this request?')\">
<script type="text/javascript">
function moveTable(form){
$(form).find('.pendingTable tr').each(function(){
alert('hello');
});
}
</script>

You can paste this entire script into one PHP script and you should be able to see how it passes the table id via ajax to the script at the bottom of the page. Give it a try!
<?php if (!isset($_POST['doAjaxAction'])) { ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Dev Doc</title>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<style>
form {
margin-bottom: 50px;
}
</style>
</head>
<body>
<?php
$RNrow['request_number'] = '123';
$RNrow['ItemName'] = 'ItemName';
$RNrow['ItemDesc'] = 'ItemDesc';
$RNrow['BrandName'] = 'BrandName';
$RNrow['ManNum'] = 'ManNum';
$RNrow['NSN'] = 'NSN';
$RNrow['ItemCost'] = 'ItemCost';
$RNrow['Qty'] = 'Qty';
$bgcolor = 'grey'
?>
<form method='POST'>
<table id='<?php echo $RNrow['request_number'] ?>' class="pendingTable">
<tbody>
<tr style='background-color:<?php echo $bgcolor; ?>'>
<input type='hidden' value='<?php echo $RNrow['request_number'] ?>'>
<td id = 'name'>"<?php echo $RNrow['ItemName'] ?>"</td>
<td>"<?php echo $RNrow['ItemDesc'] ?>"</td>
<td>"<?php echo $RNrow['BrandName'] ?>"</td>
<td>"<?php echo $RNrow['ManNum'] ?>"</td>
<td>"<?php echo $RNrow['NSN'] ?>"</td>
<td>"<?php echo $RNrow['ItemCost'] ?>"</td>
<td>"<?php echo $RNrow['Qty'] ?>"</td>
</tr>
</tbody>
<input type='submit' value='Approve' onclick="moveTable(<?php echo $RNrow['request_number'] ?>, 'Approve')">
<input style='margin-left:5px' type='submit' value='Deny' onclick="moveTable(<?php echo $RNrow['request_number'] ?>, 'Deny')">
</table>
</form>
<?php
$RNrow['request_number'] = '456';
$RNrow['ItemName'] = 'ItemName2';
$RNrow['ItemDesc'] = 'ItemDesc2';
$RNrow['BrandName'] = 'BrandName2';
$RNrow['ManNum'] = 'ManNum2';
$RNrow['NSN'] = 'NSN2';
$RNrow['ItemCost'] = 'ItemCost2';
$RNrow['Qty'] = 'Qty2';
$bgcolor = 'lightblue'
?>
<form method='POST'>
<table id='<?php echo $RNrow['request_number'] ?>' class="pendingTable">
<tbody>
<tr style='background-color:<?php echo $bgcolor; ?>'>
<input type='hidden' value='<?php echo $RNrow['request_number'] ?>'>
<td id = 'name'>"<?php echo $RNrow['ItemName'] ?>"</td>
<td>"<?php echo $RNrow['ItemDesc'] ?>"</td>
<td>"<?php echo $RNrow['BrandName'] ?>"</td>
<td>"<?php echo $RNrow['ManNum'] ?>"</td>
<td>"<?php echo $RNrow['NSN'] ?>"</td>
<td>"<?php echo $RNrow['ItemCost'] ?>"</td>
<td>"<?php echo $RNrow['Qty'] ?>"</td>
</tr>
</tbody>
<input type='submit' value='Approve' onclick="moveTable(<?php echo $RNrow['request_number'] ?>, 'Approve')">
<input style='margin-left:5px' type='submit' value='Deny' onclick="moveTable(<?php echo $RNrow['request_number'] ?>, 'Deny')">
</table>
</form>
<script>
function moveTable(id, action) {
//Opens OK or Cancel Dialog
if (confirm('Are you sure you want to approve this request?')) {
//Hit F12 in your browser to the console. This shows what passed in
alert('ID Sent: ' + id, ' -- Action: ' + action);
//Posts ID and Action to self, with 'doAjaxAction' set to 1, so only the php script at bottom executes during AJAX call
$.post('<?php echo basename($_SERVER['PHP_SELF']); ?>',
{
//seen as $_POST['id'] and $_POST['action'] to script at the bottom
doAjaxAction: '1',
id: id,
action: action
},
//This function gives us the data returned from approve_deny.php
function (data, status) {
// 'data' returns 'DID SOMETHING'
// 'status' returns status of ajax call
alert("Data Sent: " + data + "\nStatus: " + status);
if (status === 'success') {
//Removes the order from the page. Can change this to grey it out, shrink it, etc
alert('AJAX call was a.. ' + status);
// $("#" + id + "\"").empty();
}
});
}
//If user changes mind, and clicks cancel on confirm
else {
alert('Action Cancelled.')
}
}
</script>
</body>
</html>
<?php } ?>
<?php
if (isset($_POST['doAjaxAction']) && $_POST['doAjaxAction'] == '1') {
$id = $_POST['id'];
$action = $_POST['action'];
if ($action == 'Approve') {
echo "APPROVED ID # " . $_POST['id'] . " do something with passed ID " . PHP_EOL;
}
if ($action == 'Deny') {
echo "DENIED ID # " . $_POST['id'] . " do something with passed ID " . PHP_EOL;
}
echo "DID SOMETHING AT END" . PHP_EOL;
}
?>

Related

Populating dynamic form row from generated list PHP

I'm making something for a stocktake.
I have a form that generates with 4 fields. item_code, item_name, packing, quantity
<form action="goods.php" method="post">
<table>
<!-- Headers -->
<tr>
<td><b>Item Code</b></td>
<td><b>Description</b></td>
<td><b>Packing</b></td>
<td><b>Quantity</b></td>
</tr>
<?php
for ($i = 0; $i <= 50; $i++) {
?>
<tr>
<td>
<INPUT TYPE="TEXT" NAME="item_code[<?php echo $i; ?>]" SIZE="6" VALUE="
<?php
if (!empty($_POST["item_code"][($i)])) {
echo $_POST["item_code"][($i)];
}
?>"></td>
<td><?php
if (!empty($_POST["item_code"][($i)])) {
$result = FetchData($_POST["item_code"][($i)]);
echo $result['category'];
}
?>
</td>
<td>
<?php
if (!empty($_POST["item_code"][($i)])) {
echo $result['item_name'];
}
?></td>
<td>
<?php
if (!empty($_POST["item_code"][($i)])) {
echo $result['packing'];
}
?></td>
<td><INPUT TYPE="TEXT" NAME="quantity[<?php echo $i; ?>]" SIZE="5" VALUE="
<?php
if (!empty($_POST["quantity"][($i)])) {
echo $_POST["quantity"][($i)];
} else {
echo "";
}
?>"></td>
A js function for the button
<script>
function fillForm(value) {
document.getElementById('value').innerHTML = value;
}
</script>
and a list that is generated with 3 fields. item_code, item_name, packing
<?php
$dbh = dbh_get();
$sql = 'SELECT * FROM goods as goods(item_code, sort) order by human_sort(goods.item_code)';
$v = array();
$stmt = $dbh->prepare($sql);
$stmt->execute();
while (true) {
$r = $stmt->fetch();
if (is_bool($r)) break;
print '
<tr>
<td class="buttonL" id="<php ' . $r['item_code'] . ' ?>" onclick="fillForm()">' . $r['item_code'] . '</td>
<td>' . $r['item_name'] . '</td>
<td>' . $r['packing'] . '</td>
</tr>' . "\n";
}
dbh_free($dbh);
?>
}
I want to put a button on each list row and when it's clicked it populates the first three fields in the form, leaving quantity to be filled out. Then when another is clicked it populates the next form row etc,. It's working fine manually entering from the list, but the list is nearly 5000 items so it's a hassle to keep searching then scrolling up and entering the values.
I don't see how to do this with PHP so I assume I need a javascript function, which is where I'm lost. Let me know if you need more info.

Create a text form inside table row that stays after submission and updates database

I want to create a column that has a text box inside each table row. The user can write any text inside the text box and click the 'Save' button to save it in the database. Additionally, the text box can be edited unlimited times. My code is the following:
index.php
<?php
...
while($row = $result->fetch_assoc()){
echo "<form action= 'search.php' method='post'>";
echo "<form action='' method='get'>";
echo "<tr>
<td><input type='checkbox' name='checkbox_id[]' value='" . $row['test_id'] . "'></td>
<td> ".$row['test_id']." </td>
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
<td> ".$row['path']." </td>
<td> ".$row['video1_path']." </td>
<td> ".$row['video2_path']." </td>
<td> ".$row['video3_path']." </td>
<td> ".$row['video4_path']." </td>";
if(empty($row["directory"])){
echo "<td></td>";
}else {
echo "<td><div><button class='href' id='" . $row['test_id'] . "' >View Report</button><div></td>";
}
echo " <td style='display: none;'> ".$row['directory']." </td>
</tr>";
}
?>
</table> <br>
<input id= 'select_btn' type='submit' name='submit' value='Submit' class='w3-button w3-blue'/>
</form>
</form>
</div>
<!-- Opens the pdf file from the pdf_report column that is hidden -->
<script type="text/javascript">
$(document).on('click', '.href', function(){
var result = $(this).attr('id');
if(result) {
var dir = $(this).closest('tr').find("td:nth-child(9)").text();
window.open(dir);
return false;
}
});
</script>
<!-- Updates text input to database -->
<script type="text/javascript">
$(document).on('click', '.name', function(){
var fcookie1= 'mycookie1';
var fcookie2= 'mycookie2';
var name = $(this).attr('id');
if(name) {
var text1 = $(this).closest('tr').find("td:nth-child(2)").text();
var text2 = $(this).closest('tr').find("td:nth-child(3)").text();
document.cookie='fcookie1='+text1;
document.cookie='fcookie='+text2;
$.ajax({
url: "name_edit.php",
type:"GET",
success: function() {
// alert("Edited Database");
}
});
}
});
</script>
name_edit.php
<?php include 'dbh.php' ?>
<?php include 'search.php' ?>
<?php
if (isset($_COOKIE["fcookie1"]))
echo $_COOKIE["fcookie1"];
else
echo "Cookie Not Set";
if (isset($_COOKIE["fcookie2"]))
echo $_COOKIE["fcookie2"];
else
echo "Cookie Not Set";
$var1 = $_COOKIE["fcookie1"];
$var2 = $_COOKIE["fcookie2"];
$conn = mysqli_connect($servername, $username, $password, $database);
$sql = "UPDATE test_data SET name='$var2' WHERE id='$var1'";
$query_run= mysqli_query($conn,$sql);
if($query_run){
echo '<script type="text/javascript"> alert(Data Updated)</script>';
} else {
echo '<script type="text/javascript"> alert(Data Not Updated)</script>';
}
?>
My idea was for the user to write any text. Then i will 'grab' the text and its expected id and save it to a cookie, when the save button is clicked. The cookie will then be echoed in name_edit.php and insert it in the sql code which will then update my database.
Im not sure what to include in 'value' inside the form tag. If there is data inside the database then display it inside the text box which can also be edited, else display blank for a text to be inserted.
I am new to coding and I'm a bit confused if my idea is correct or should i approach it another way.
I did some research and found out i did not have to use form but instead use 'contenteditable'. To edit the specific column i changed
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
to this:
<td class='name' data-id1='" . $row['test_id'] . "' contenteditable='true'>".$row['name']."</td>
and for my jquery i added the following:
<style>
.editMode{
border: 1px solid black;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
// Add Class
$('.name').click(function(){
$(this).addClass('editMode');
});
// Save data
$(".name").focusout(function(){
$(this).removeClass("editMode");
var id = $(this).closest('tr').find("td:nth-child(2)").text();;
var value = $(this).text();
$.ajax({
url: 'name_edit.php',
type: 'post',
data: { value:value, id:id },
success:function(response){
alert('Edits Saved');
return false;
}
});
});
});
</script>
and in the php side, i simply did the following:
<?php include 'dbh.php' ?>
<?php
$conn = mysqli_connect($servername, $username, $password, $database);
$field = $_POST['field'];
$value = $_POST['value'];
$id= $_POST['id'];
$sql = "UPDATE test_data SET name='".$value."' WHERE test_id='".$id."'";
mysqli_query($conn,$sql);
echo 1;
?>

Refresh page if certein php script is executed

I have a somefile.php and someotherfile.js with the code as below
javascript file
function deleteSelectedRow() {
return (confirm('Are you sure you want to delete this record))
};
<!DOCTYPE html>
<html lang=" en">
<head>
<title> Title </title>
</head>
<body>
<h1>Select the user to delete from the list below </h1>
<form action="" method="POST">
<?php
if(require_once('../SQL/mySQL_connect.php'))
{
$query = "SELECT id, FirstName, LastName, PhoneNumber FROM participants ORDER BY id ASC";
$userDetails = #mysqli_query($mysqli, $query);
}
else
{
echo "Couldn't connect to database";
echo mysqli_error($mysqli);
}
// mysqli_close($mysqli);
?>
<br><br><br>
<table name="userDetailsTable" id="userDetailsTable" align="left" cellspacing="7" cellpadding="8">
<tr>
<td align="center"><b>S No</b></td>
<td align="center"><b>Id</b></td>
<td align="center"><b>Rank</b></td>
<td align="center"><b>First Name</b></td>
<td align="center"><b>Last Name</b></td>
</tr>
<?php
for($i = 1; $i <= mysqli_num_rows($userDetails); $i++)
// while($row=mysqli_fetch_array($userDetails))
{
$row=mysqli_fetch_array($userDetails);
echo '<tr>
<td align ="center" >'. $i .'</td>
<td align ="center" >' . $row['id'] . '</td>
<td align ="center">' . $row['Rank'] . '</td>
<td align ="center">' . $row['FirstName'] . '</td>
<td align ="center">' . $row['LastName'] . '</td>
<td align ="center"> <input type = submit name="delete" value="delete" onclick="return deleteSelectedRow();" ></input></td>';
echo '</tr>';
}
?>
</table>
</form>
<?php
if(isset($_POST['delete']))
{
require_once('../SQL/mySQL_connect.php');
$query="DELETE FROM `participants` WHERE `participants`.`id` = ".$_POST['IDNumber']."";
$response = #mysqli_query($mysqli, $query);
if($response)
{
echo "Deleted from Database Successfully";
}
else
{
echo "Couldn't Delete from database";
echo'<br>';
echo mysqli_error($mysqli);
}
mysqli_close($mysqli);
}
?>
</body>
What this code does is as follows
Connects to database and retrieves the user details
Creates a table and prints out the user details in it
user clicks on delete button in front of any record and it gets deleted after confirmation
A success message is displayed that the message is deleted
What I want to do is that after displaying the success message the above printed table should get updated automatically so that user is confirmed that the id no longer exists in the table
I tried the following solutions
reload page just before the success message is displayed so that user sees the success message as well as the updated table as well (since reload will re-connect to database and refetch the table)
I tried to use "location.reload(true)" command but i can't figure out where to place this line so that it gets executed just before the success message is displayed.
Any help is much appreciated
A few things:
you'll want the delete operation to be the first thing you do on the page (if it's a form submit) because otherwise you'll print the "pre-deleted" table.
you need to pass the ID through post in the form. It's easier if you just have a unique for for every row, and have a hidden ID input for each.
The confirm is better attached to the form submit event, because otherwise you'll miss other, non-click, input methods.
Your delete operation, as it was written in the question, is susceptible to an SQL Injection attack. You'll want to escape that POST value.
Something like the below should work
function deleteSelectedRow() {
return (confirm('Are you sure you want to delete this record))
};
<?php
$message = '';
$connected = false;
if(require_once('../SQL/mySQL_connect.php'))
{
$connected = true;
}
if($connected && isset($_POST['delete']))
{
$id_to_delete = mysqli_real_escape_string($mysqli, $_POST['IDNumber']);//escape value to prevent sql injection attack
$query="DELETE FROM `participants` WHERE `participants`.`id` = ".$id_to_delete."";
$response = #mysqli_query($mysqli, $query);
if($response)
{
$message = "Deleted from Database Successfully";
}
else
{
$message = "Couldn't Delete from database";
$message .='<br>';
$message .= mysqli_error($mysqli);
}
//mysqli_close($mysqli);
}else{
$message = "unable to connect to database";
}
?><!DOCTYPE html>
<html lang=" en">
<head>
<title> Title </title>
</head>
<body>
<h1>Select the user to delete from the list below </h1>
<?php
if($connected)
{
$query = "SELECT id, FirstName, LastName, PhoneNumber FROM participants ORDER BY id ASC";
$userDetails = #mysqli_query($mysqli, $query);
}
else
{
echo "Couldn't connect to database";
echo mysqli_error($mysqli);
}
?>
<br><br><br>
<?php if($message){ /* do we have a success/error message from the delete operation? */ ?>
<p><?php echo $message; ?></p>
<?php } ?>
<table name="userDetailsTable" id="userDetailsTable" align="left" cellspacing="7" cellpadding="8">
<tr>
<td align="center"><b>S No</b></td>
<td align="center"><b>Id</b></td>
<td align="center"><b>Rank</b></td>
<td align="center"><b>First Name</b></td>
<td align="center"><b>Last Name</b></td>
</tr>
<?php
for($i = 1; $i <= mysqli_num_rows($userDetails); $i++)
// while($row=mysqli_fetch_array($userDetails))
{
$row=mysqli_fetch_array($userDetails);
echo '<tr>
<td align ="center" >'. $i .'</td>
<td align ="center" >' . $row['id'] . '</td>
<td align ="center">' . $row['Rank'] . '</td>
<td align ="center">' . $row['FirstName'] . '</td>
<td align ="center">' . $row['LastName'] . '</td>
<td align ="center"> <form action="" method="POST" onsubmit="return deleteSelectedRow();"><input type="hidden" name="IDNumber" value="'.$row['id'].'" /><input type = submit name="delete" value="delete"></form></td>';
echo '</tr>';
}
?>
</table>
<?php if($connected){
mysqli_close($mysqli);
} ?>
</body>
You need to store the Success/Error message in a $_SESSION["flash"] instead of show by echo and after delete the user you must redirect to the same page.
On the top of the page, if isset the $_SESSION["flash"] you can show the message and remove it from the session. In code:
if(isset($_POST['delete']))
{
require_once('../SQL/mySQL_connect.php');
$query="DELETE FROM `participants` WHERE `participants`.`id` = ".$_POST['IDNumber']."";
$response = #mysqli_query($mysqli, $query);
if($response)
{
$_SESSION["flash"] = "Deleted from Database Successfully";
}
else
{
$_SESSION["flash"] = "Couldn't Delete from database";
//echo'<br>';
//echo mysqli_error($mysqli);
}
mysqli_close($mysqli);
header('Location: '.$_SERVER['PHP_SELF']);
}
and on the top of the page of before isset($_POST['delete']):
if(isset($_SESSION["flash"])){
echo $_SESSION["flash"];
unset($_SESSION["flash"]);
}
don't forget to start_session() on the top of the page.
I'll notice that your code have a SQL Injection Vulnerability. You shouldn't do MySQL queries without validate GET and POST input data.

How to uniquely set id's to buttons generated dynamically in php that are accessible in javascript code

Okay so I'm having a small problem. So I have an inventory system connected to a database and for each item in the database a button is generated on screen and I'm trying to give each button a unique Id in php that I can access through javascript. the code for generating the buttons looks like this
<table class = "table">
<thead>
<tr>
<td><center><strong>Item Id</strong></center> </td>
<td><center><strong>Item Description</strong></center> </td>
<td><center><strong>Item Type</strong> </center></td>
<td><center><strong>Availability</strong></center></td>
<td><center><strong>Name</strong></center></td>
<td><center><strong>Check in/out button</strong></center></td>
</tr>
</thead>
<tbody>
<?php
mysql_select_db('inventory management system');
$query="SELECT * FROM inventory";
$results = mysql_query($query);
$a = 0;
while($row = mysql_fetch_array($results)) {
$a++;
echo '<script type = "text/javascript">c++;</script>'
?>
<tr>
<td><center><?php echo $row['item_id']?></center></td>
<td><center><?php echo $row['item_desc']?></center></td>
<td><center><?php echo $row['item_type']?></center></td>
<td><center><?php echo $row['availability_status']?></center></td>
<td><center><?php echo $row['name']?></center></td>
<td><center><?php
if(is_null($row['name'])){//generates the buttons whether or not an item is signed in or out
echo "<input class='btn btn-default' type='submit' value='Check Out' id ='$a' onclick='updateinventory()'>";//how can I get a unique id here ?
}else if(!is_null($row['name'])){
$lol = "<?php <script type = 'text/javascript'> x++; </script> ?>";
echo "<input class='btn btn-default' type='submit' value='Check In' id ='$a' onclick='checkingitemin()'>";
}
?></center></td>
</tr>
<?php
}
?>
</tbody>
</table
>
i need to be able to access each specific unique button to be able to change the text on each button as well as execute some ajax to change some stuff in the database.
Replace your conditions with this :
if(is_null($row['name'])) {//generates the buttons whether or not an item is signed in or out
echo "<input class='btn btn-default' type='submit' value='Check Out' id='".$row['item_id']."' onclick='updateinventory()'>";
} else { // You don't need another `if` statement here
// I don't think the next instruction is usefull :)
// $lol = "<?php <script type = 'text/javascript'> x++; </script>";
echo "<input class='btn btn-default' type='submit' value='Check In' id='".$row['item_id']."' onclick='checkingitemin()'>";
}

Passing an id to a PHP script using jQuery/Ajax

This is the code that the user have a participation with.
<html>
<head>
<title></title>
<script src="jquery-1.9.1.js"></script>
<script src="jquery.form.js"></script>
</head>
<body>
<?php
include 'connection.php';
$sql="SELECT * FROM blog";
$result=mysqli_query($link, $sql);
if(!$result)
{
$output='Error fetching students:'.mysqli_error($link);
}
?>
<div id="table">
<table border='1' cellpadding='10' id="table">
<tr>
<td><b>Title<b></td>
<td><b>Edit<b></td>
<td><b>Delete<b></td>
</tr>
<?php
while($row=mysqli_fetch_array($result))
{
echo '<tr class="record">';
echo '<td>'.$row['articletitle'] .'';
echo '<td>Edit';
echo "<input type='hidden' name='id' value='".$row['articleid']."'></td>";
echo '<td><div align="center">Delete</div></td>';
echo "</tr>\n";
}
echo '<form method="post" id="myForm" action="postview.php">';
echo '<input type="hidden" name="myID">';
echo '</form>';
?>
</table>
<button id="addrecord">Add New Post</button>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#addrecord").click(function(){
$("#table").load("addpost.php");
$("#addrecord").hide();
});//add
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this Record?"))
{
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function(){}
});//ajax
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});//delete
$(".title").click(function(){
$('[name=myID]').val($(this).attr('id'));
$('#myForm').submit();
});//view
$(".edit").click(function(){
var data=$("#tryform").serialize();
$.ajax({
type: "POST",
url: "editpost.php",
data: data
}).done(function( msg ) {
$("#table").html(msg);
});//ajax
});//delete
});
</script>
</body>
</html>
and this the PHP script that the code above redirect to.
<?php
include 'connection.php';
$id=$_GET['id'];
echo $id;
$sql="SELECT * FROM blog WHERE articleid='$id'";
$result=mysqli_query($link, $sql);
echo "<table>";
$row=mysqli_fetch_array($result);
echo "<tr>";
echo "<td>".$row['articletitle'] . "</td>";
echo "<td><img src='image.php?id=$row[articleid]' width='200' height='200' /><br/></td>";
echo "<td>".$row['articlemore'] . "</td>";
echo "</tr>";
echo "</table>";
//echo "</div>";
?>
I'm having this kind of error:
Undefined index: id in C:\xampp\htdocs\ckeditor\samples\postview.php on line 4
You need to check if argument "id" is passed to the php script first
<?php
include 'connection.php';
if( (isset($_GET['id'])) && ($_GET['id'] != '') ){ //check if the argument "id" is passed to the script
$id=$_GET['id'];
echo $id;
$sql="SELECT * FROM blog WHERE articleid='$id'";
$result=mysqli_query($link, $sql);
echo "<table>";
$row=mysqli_fetch_array($result);
echo "<tr>";
echo "<td>".$row['articletitle'] . "</td>";
echo "<td><img src='image.php?id=$row[articleid]' width='200' height='200' /><br/></td>";
echo "<td>".$row['articlemore'] . "</td>";
echo "</tr>";
echo "</table>";
//echo "</div>";
}
?>
Not so much an answer to your question, but probably a good suggestion to make your code a lot cleaner- try using PHP Alternative Syntax and moving in and out of PHP to make your HTML clean.
<?php while($row=mysqli_fetch_array($result)):?>
<tr class="record">';
<td><?php echo $row['articletitle'];?>
<td>Edit
<input type='hidden' name='id' value='<?php echo $row['articleid'];?>'></td>
<td>
<div align="center">
Delete
</div>
</td>
</tr>
<?php endwhile;?>
<form method="post" id="myForm" action="postview.php">
<input type="hidden" name="myID">
</form>
$sql="SELECT * FROM blog WHERE articleid='".$id."'";
try this line
That isnt an error, but a notice, which is lowlevel It simple means $_GET['id'] doesnt hav a value
echo $example['something']; // will give undefined index notice
$example['something'] = 'abc';
echo $example['something']; // No notices
Your website should be domain.ext/?id=123, if not, this notice will show.

Categories

Resources