My code is: (Edited after a suggestion from an answer)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SomuFinance - Personal Finance Manager</title>
<link rel="stylesheet" type="text/css" href="indexStyle.css">
<script src="scripts/jquery-3.1.0.min.js"></script>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div id="container">
<input type="submit" class="button" name="edit" value="Edit" />
<input type="button" class="button" name="delete" value="Delete" />
<input type="text" id="action" name="action">
<table id="listDB">
<tr>
<th>Select</th>
<th>ID</th>
<th>Category ID</th>
<th>Shop</th>
<th>Item</th>
<th>Quantity</th>
<th>Unit</th>
<th>Price Based On</th>
<th>MRP</th>
<th>Seller's Price</th>
<th>Last Updated On</th>
</tr>
<?php
$dbc = mysqli_connect('localhost','root','atlantis2016','itemDB')
or die("Error Connecting to Database");
if(isset($_POST['submit']))
{
echo "Action Set to ".$_POST['action'];
if($_POST['action']=='confirmDelete')
{
echo "Now Deleting!!";
foreach ($_POST['selected'] as $delete_id)
{
$query = "DELETE FROM grocery WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error querying database.');
}
}
}
$query1 = "SELECT DISTINCT category FROM grocery";
$result1 = mysqli_query($dbc, $query1)
or die("Error Querying Database");
while($row = mysqli_fetch_array($result1))
{
$category = $row['category'];
$query2 = "SELECT * FROM grocery WHERE category='$category' ORDER BY item ASC";
$result2 = mysqli_query($dbc, $query2)
or die("Error Querying Database");
echo '<tr>';
echo '<td class="catHead" colspan=11>'.$category.'</td>';
echo '</tr>';
$catCount=1;
while($inRow = mysqli_fetch_array($result2))
{
$id = $inRow['id'];
$shop = $inRow['shop'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
echo '<tr>';
echo '<td><input type="checkbox" value="' . $id . '" name="selected[]" /></td>';
echo '<td>'.$id.'</td>';
echo '<td>'.$catCount.'</td>';
echo '<td>'.$shop.'</td>';
echo '<td class="leftAligned">'.$item.'</td>';
echo '<td>'.$qnty.'</td>';
echo '<td>'.$unit.'</td>';
echo '<td>'.$price_based_on.'</td>';
echo '<td class="pri">₹'.$mrp.'</td>';
echo '<td class="pri">₹'.$sellers_price.'</td>';
echo '<td>'.$last_updated_on.'</td>';
echo '</tr>';
$catCount++;
}
}
mysqli_close($dbc);
?>
<input type="submit" value="Submit">
</table>
</div>
<div class="dialogBG">
<div id="deleteConfirmDialog" class="dialog">
<div class="closeDialog"></div>
<p>Sure you want to delete the selected Data?</p>
<input type="submit" id="confirmDelete" class="dialogButton" name="edit" value="Delete" />
<input type="button" class="dialogButton cancelButton" name="delete" value="Cancel" />
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(){
if($(this).val()=="Delete")
{
$(".dialogBG").fadeIn(200);
$("#deleteConfirmDialog").show(200);
$("#action").val('confirmDelete');
}
else if($(this).val()=="Edit")
{
}
});
$('#confirmDelete').click(function(){
$(".closeDialog").trigger("click");
});
$('#cancelDelete').click(function(){
});
$(".closeDialog").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
$(".cancelButton").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
$("form").submit(function(e){
alert("Form is being sumbitted!");
});
});
</script>
</body>
</html>
I want the elements for which the checkbox is selected, contained in the php array selected[], to be deleted from the database. Before deletion, I want a confirmation dialog box to open up, which will contain the "submit" button. This will cause the actual deletion. However, for some reason the above code doesn't work. I can't even be sure if the post is being submitted, as the line echo "Action Set to ".$_POST['action']; doesn't return any output. Please help.
I believe this entire section of code is not working (from manual testing).
if(isset($_POST['submit']))
{
echo "PHP Working here!";
echo "Action Set to ".$_POST['action'];
if($_POST['action']=='confirmDelete')
{
echo "Now Deleting!!";
foreach ($_POST['selected'] as $delete_id)
{
$query = "DELETE FROM grocery WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error querying database.');
}
}
}
Any ideas why?
you need to put these inputs inside a form and set an action. like below:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" role="form">
<input></input>
<input></input>
</form>
this will be your code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SomuFinance - Personal Finance Manager</title>
<link rel="stylesheet" type="text/css" href="indexStyle.css">
<script src="scripts/jquery-3.1.0.min.js"></script>
</head>
<body>
<div id="container">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" role="form">
<input type="submit" class="button" name="edit" value="Edit" />
<input type="button" class="button" name="delete" value="Delete" />
<input type="text" id="action" name="action">
<table id="listDB">
<tr>
<th>Select</th>
<th>ID</th>
<th>Category ID</th>
<th>Shop</th>
<th>Item</th>
<th>Quantity</th>
<th>Unit</th>
<th>Price Based On</th>
<th>MRP</th>
<th>Seller's Price</th>
<th>Last Updated On</th>
</tr>
<?php
$dbc = mysqli_connect('localhost','root','atlantis2016','itemDB')
or die("Error Connecting to Database");
if(isset($_POST['submit']))
{
echo "Action Set to ".$_POST['action'];
if($_POST['action']=='confirmDelete')
{
echo "Now Deleting!!";
foreach ($_POST['selected'] as $delete_id)
{
$query = "DELETE FROM grocery WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error querying database.');
}
}
}
$query1 = "SELECT DISTINCT category FROM grocery";
$result1 = mysqli_query($dbc, $query1)
or die("Error Querying Database");
while($row = mysqli_fetch_array($result1))
{
$category = $row['category'];
$query2 = "SELECT * FROM grocery WHERE category='$category' ORDER BY item ASC";
$result2 = mysqli_query($dbc, $query2)
or die("Error Querying Database");
echo '<tr>';
echo '<td class="catHead" colspan=11>'.$category.'</td>';
echo '</tr>';
$catCount=1;
while($inRow = mysqli_fetch_array($result2))
{
$id = $inRow['id'];
$shop = $inRow['shop'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
echo '<tr>';
echo '<td><input type="checkbox" value="' . $id . '" name="selected[]" /></td>';
echo '<td>'.$id.'</td>';
echo '<td>'.$catCount.'</td>';
echo '<td>'.$shop.'</td>';
echo '<td class="leftAligned">'.$item.'</td>';
echo '<td>'.$qnty.'</td>';
echo '<td>'.$unit.'</td>';
echo '<td>'.$price_based_on.'</td>';
echo '<td class="pri">₹'.$mrp.'</td>';
echo '<td class="pri">₹'.$sellers_price.'</td>';
echo '<td>'.$last_updated_on.'</td>';
echo '</tr>';
$catCount++;
}
}
mysqli_close($dbc);
?>
</table>
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(){
if($(this).val()=="Delete")
{
$(".dialogBG").fadeIn(200);
$("#deleteConfirmDialog").show(200);
$("#action").val('confirmDelete');
}
else if($(this).val()=="Edit")
{
}
});
$('#confirmDelete').click(function(){
$(".closeDialog").trigger("click");
});
$('#cancelDelete').click(function(){
});
$(".closeDialog").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
$(".cancelButton").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
});
</script>
<div class="dialogBG">
<div id="deleteConfirmDialog" class="dialog">
<div class="closeDialog"></div>
<p>Sure you want to delete the selected Data?</p>
<input type="submit" id="confirmDelete" class="dialogButton" name="edit" value="Delete" />
<input type="button" class="dialogButton cancelButton" name="delete" value="Cancel" />
</div>
</div>
</body>
</html>
The solution was simple. if(isset($_POST['confirmDelete'])) needs to be there instead of if(isset($_POST['submit'])) in the problem section in the question as there is no button called "submit" in the entire form.
Related
I'm wanting to make a URL that transfers all the placed product numbers (they are in multiple rows) from the cart into the URL to be passed to the next page. Not sure if this is possible!
I have tried making the URL with a variable:
$placeditems = $_POST['placeditems'];
$url = "myorder.php?id=".urlencode($placeditems);
As was requested in the comments, below is my coding for the entire file as of right now (with some edits from the suggested comments).
<?php
session_start();
$cart = $_COOKIE['crochetdamour'];
if(isset($_POST['clear'])) {
$expire = time() -60*60*24*7*365;
setcookie("crochetdamour", $cart, $expire);
header("Location:mycart.php");
}
if($cart && $_GET['id']) {
$cart .= ',' . $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("crochetdamour", $cart, $expire);
header("Location:mycart.php");
}
if(!$cart && $_GET['id']) {
$cart = $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("crochetdamour", $cart, $expire);
header("Location:mycart.php");
}
if($cart && $_GET['remove_id']) {
$removed_item = $_GET['remove_id'];
$arr = explode(",", $cart);
unset($arr[$removed_item-1]);
$new_cart = implode(",", $arr);
$new_cart = rtrim($new_cart, ",");
$expire = time() +60*60*24*7*365;
setcookie("crochetdamour", $new_cart, $expire);
header("Location:mycart.php");
}
$placeditems = $_GET['placeditems'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Crochet d'Amour</title>
<link rel="stylesheet" href="https://use.typekit.net/kfn2dzo.css">
<link href="SiteStyles.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</head>
<body>
<header class="clearfix">
<img src="images/ball.png" alt="Ball of yarn." id="ball"><img src="images/logo.png" alt="Crochet d'Amour" id="logo">
<?php include('includes/nav.inc');?>
</header>
<div class="clearfix">
<section style="width:100%;">
<h1>My Cart</h1>
<form method="get" action="<?php $_SERVER['PHP_SELF'];?>">
<table width="100%">
<tr>
<th class="hidden">Product ID</th>
<th>Placed Items</th>
<th>Item Name</th>
<th>Description</th>
<th>Price</th>
<th>Actions</th>
</tr>
<?php
$cart = $_COOKIE['crochetdamour'];
if ($cart) {
$i = 1;
include('includes/dbc.php');
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM orderplace WHERE orderplace_number = '$item'";
$result = mysqli_query($con, $sql);
if($result == false){
$mysql_error = mysqli_error($con);
echo "There was a query error: $mysql_error";
}else {
while($row=mysqli_fetch_assoc($result)) {
echo '<tr><td align="left" id="prodid" name="prodid" class="hidden">' .$row['product_id']. '</td>';
echo '<td align="left"><input type="text" name="placeditems" id="placeditems" value="' .$row['orderplace_number']. '"></td>';
echo '<td align="left" id="prodname" name="prodname">' .$row['product_name']. '</td>';
echo '<td align="left" class="desctd" id="proddesc" name="proddesc">' .$row['product_size']. ', ' .$row['product_gender']. ', ' .$row['product_theme']. ', ' .$row['product_specs']. '</td>';
echo '<td align="left" id="prodprice" name="prodprice">' .$row['product_price']. '</td>';
echo '<td align="left">Remove From Cart</td></tr>';
$sum += $row['product_price'];
}//end while
$i++;
}//end else
}//end foreach
}//end if
?>
<?php {echo '<tr><td align="right" colspan="5" style="font-size:110%;font-weight:400;" id="total" name="total">Total: ' .$sum. '</td></tr>';}
$url = "myorder.php?id=".urlencode($placeditems)."&total=".urlencode($sum);?>
</table>
<input type="submit" name="clear" value="Empty Cart" style="margin-left: 40px" class="emptycart"> <?php if(isset($url)) {echo '<input type="submit" name="order" value="Proceed with Order" style="margin-left: 40px" class="emptycart">';} ?>
</form>
</section>
</div>
<footer>
<p class="footerp">Copyright © 2018-2019 Crochet d'Amour. All Rights Reserved.</p>
</footer>
</body>
</html>
Just make your form post a GET action.
if , lets say you have a couple of fields:
<form method="get" action="<?php $_SERVER['PHP_SELF'];?>">
<input name="test" type="text"/>
<input name="test2" type="text"/>
<input type="submit" name="clear" value="Empty Cart" style="margin-left: 40px" class="emptycart"> <?php if(isset($url)) {echo '<input type="submit" name="order" value="Proceed with Order" style="margin-left: 40px" class="emptycart">';} ?>
</form>
It will produce a GET request with this params ?test=WATEVER_YOU_TYPED&test2=SECOND_FIELD&clear=Empty&20%Cart or whatever is enterpret whitespace, i do not remember that.
I am getting $pgcode value required for the second select option but the form is refreshed which I do not want. I also tried adding some html divs but in that case the form is duplicating some content and also refreshing.
How can I make this work without a refresh occurring?
<?php
if (session_id() == '') {
session_start();
ob_start();
}
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
include("dbc.php");
if (isset($_POST['model'])) {
$pgcode = $_POST['model'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="js/jquery-1.10.1.min.js" type="text/javascript"></script>
<script>
$('#dataTable').on('change','.select-desc',function(){
var cur_val = $(this).val();
$.ajax({
method:"POST",
url:"cashtran.php",
data:{model:cur_val},
success:function(result){
$('body').html(result);
},
});
});
});
</script>
</head>
<body id="top">
<br class="clear" />
<div class="wrapper col4">
<div id="container">
<div id="content">
<form method="post" name="frmcashtran" action="">
<h3><span class="orange">Cash Payment Details</span></h3>
<fieldset>
<table>
<tr>
<td><input type="button" value="Add Row" id="addRow" /></td>
<td><input type="button" value="Remove Row" id="deleteRow"/></td>
</tr>
</table>
<table id="dataTable" border="0">
<tr>
<td></td>
<td><label>Main A/c</label></td>
<td><label>Subledger</label></td>
<td><label>Narration</label></td>
<td><label>Amount</label></td>
</tr>
<tr>
<td>
<?php
$sql = "SELECT gcode,acname FROM account ";
$result = mysqli_query($conn, $sql) or die(mysqli_error());
echo "<select name='acname[]' class='select-desc' tabindex='2'>";
echo "<option value=''>-- Select Main A/c --</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value = '{$row['gcode']}'";
if ($pgcode == $row['gcode'])
echo "selected = 'selected'";
echo ">{$row['acname']}</option>";
}
echo "</select>";
?>
</td>
<td>
<?php
$sql = "SELECT scode,sname FROM subldg where gcode='$pgcode' ";
$result = mysqli_query($conn, $sql) or die(mysqli_error());
echo "<select name='slname[]' tabindex='2'>";
echo "<option value=''>-- Select Subledger--</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value = '{$row['scode']}'";
if ($pscode == $row['scode'])
echo "selected = 'selected'";
echo ">{$row['sname']}</option>";
}
echo "</select>";
?>
</td>
</table>
</form>
</body>
</html>
If the entire page is being sent back as the response to the ajax request change the following PHP code
if (isset($_POST['model'])) {
$pgcode = $_POST['model'];
}
to
if( isset( $_POST['model'] ) ) {
ob_clean();
$pgcode = $_POST['model'];
exit( $pgcode );
}
I want to create a select dropdownlist which retrieves data from a table "teamtable" and displays it on a page where the user enters his choice and the corresponding ID for the choice is submitted in other database "user" where the column is a foreign key.
Tables and their contents-
teamtable-
idTeam(INT)(PK) - 1,2,3
teamName(VARCHAR) - Team-1, Team-2, Team-3
user-
team(INT)(FK)
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var f=document.forms["reg"]["team"].value;
if ((f==null || f==""))
{
alert("All Field must be filled out");
return false;
}
}
</script>
<form name="reg" action="user_exec.php" onsubmit="return validateForm()" method="post">
<table width="274" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<td colspan="2">
<div align="center">
<?php
$remarks=$_GET['remarks'];
if ($remarks==null and $remarks=="")
{
echo 'Register a new user';
}
if ($remarks=='success')
{
echo 'Registration Success';
}
?>
</div></td>
</tr>
<tr>
<td><div align="right">Team:</div></td>
<td>
<?php
$mysqli_hostname = "localhost";
$mysqli_user = "root";
$mysqli_password = "my_pass";
$mysqli_database = "my_db";
$prefix = "";
$bd = mysqli_connect($mysqli_hostname, $mysqli_user, $mysqli_password) or die("Could not connect database");
mysqli_select_db($mysqli_database, $bd) or die("Could not select database");
$sql = "SELECT idTeam,teamName FROM teamtable ";
$result = mysqli_query($sql);
echo "<select name='team'>";
while ($row=mysqli_fetch_array($result))
{
echo "<option value='" . $row['idTeam'] ."'>" . $row['teamName'] ."</option>";
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td><div align="right"></div></td>
<td><input name="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</head>
</html>
<?php
include('connection.php');
$sql = "SELECT idTeam, teamName FROM team";
$result = $conn->query($sql);
echo "<select name='team'>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row['idTeam'] ."'>" . $row['teamName'] ."</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
I have three buttons on a page and I want to submit that form on the same page, depending to the button press, corresponding query will run. But there are some problem with the script.
<?php
$db = mysql_connect('localhost', 'root', '') or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db('easy_excel', $db) or die(mysql_error($db));
if ($_POST['submit'] =='delete_aabb')
{
$query ='DELETE FROM aabb';
mysql_query($query, $db) or die(mysql_error($db));
echo 'All Data from aabb Deleted succecfully!';
}
elseif ($_POST['submit'] =='delete_bbcc') {
$query ='DELETE FROM bbcc';
mysql_query($query, $db) or die(mysql_error($db));
echo 'All Data from bbcc Deleted succecfully!';
}
elseif ($_POST['submit'] =='show_bbcc') {
$query = 'SELECT
name
FROM bbcc';
$result = mysql_query($query, $db) or die(mysql_error($db));
echo '<table border="1">';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
?>
<html>
<head>
<title>Say My Name</title>
</head>
<body>
<form action="#" method="post">
<table>
<tr>
<input type="submit" name="submit" value="delete_aabb" />
</tr>
<tr>
<input type="submit" name="submit" value="delete_bbcc" /></td>
</tr>
<tr>
<input type="submit" name="submit" value="show_bbcc" /></td>
</tr>
</table>
</form>
</body>
</html>
This script is not running. Please help me.
I advice you to use MySQLi instead of deprecated MySQL. And I think you're referring to the isset() function.
<html>
<head>
<title>Say My Name</title>
</head>
<body>
<?php
/* ESTABLISH CONNECTION USING MYSQLi */
$con=mysqli_connect("localhost","root","","easy_excel");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
if (isset($_POST['delete_aabb'])) /* IF DELETE_AABB IS CLICKED */
{
mysqli_query($con,"DELETE FROM aabb");
echo 'All Data from aabb Deleted succecfully!';
}
else if (isset($_POST['delete_bbcc'])) { /* IF DELETE_BBCC IS CLICKED */
mysqli_query($con,"DELETE FROM bbcc");
echo 'All Data from bbcc Deleted succecfully!';
}
else if (isset($_POST['show_bbcc'])) { /* IF SHOW_BBCC IS CLICKED */
$result=mysqli_query($con,"SELECT name FROM bbcc");
echo '<table border="1">';
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
?>
<form action="" method="POST">
<table>
<tr>
<input type="submit" name="submit" value="delete_aabb" name="delete_aabb"/>
</tr>
<tr>
<input type="submit" name="submit" value="delete_bbcc" name="delete_bbcc"/></td>
</tr>
<tr>
<input type="submit" name="submit" value="show_bbcc" name="show_bbcc"/></td>
</tr>
</table>
</form>
</body>
</html>
I'm having a strange problem. I have a HTML page with PHP code which inserts data to a MySQL database. The data gets saved to the DB without any errors but in an incorrect order.
Here's a screenshot. The table on the right side displays the existing records. The first 2 records are shown correctly.
But when I save more records, it displays like this.
Even in the MySQL table, the records are inserted that way.
I'm not sure where exactly the problem is so I've shown the whole code for the page below. I've commented what each code block does. Please comment if you need me to clarify something.
The Location ID is an auto-generated code.
<html>
<head>
<script language="javascript">
function SelectAll(source)
{ //The code for the 'Select All' checkbox
checkboxes = document.getElementsByTagName("input");
for(var i in checkboxes)
{
if(checkboxes[i].type == 'checkbox')
{
checkboxes[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<?php
//Database connection initialization
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new Location ID */
$query = "SELECT LID FROM locations ORDER BY LID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row['LID'];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
//$id_num = sprintf("%03d", $id_num);
$new_id = $id_letter . $id_num;
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<! The table which displays the existing records >
<div id="display">
<b>Locations</b><br/><br/>
<form name="displayLocs" action="<?php echo $PHP_SELF; ?>" method="post" >
<table border="1">
<tr>
<th>Location ID</th>
<th>Code</th>
<th>Location</th>
<th><i>Delete</i></th>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><? echo $row["LID"]; ?></td>
<td align="center"><? echo $row["Code"]; ?></td>
<td><? echo $row["Location"]; ?></td>
<td align="center"><input type="checkbox" name="checkbox[]" value="<? echo $row["LID"]; ?>" /></td>
</tr>
<?php
}
?>
</table>
<br/>
<div id="buttons2">
<input type="checkbox" onclick="SelectAll(this)" />Select All <input type="reset" value="Clear" /> <input type="submit" value="Delete" name="deletebtn" />
</div>
</form>
</div>
<! New record saving area >
<b id="loc_caption_1">Enter a new location</b>
<div id="loca">
<form name="locForm" action="<?php echo $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Location ID</td>
<td><input type="text" name="lid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" name="code" style="text-align:right" /></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="loc" style="text-align:right" /></td>
</tr>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</div>
</form>
<?php
//Saving record
if(isset($_POST["savebtn"]))
{
$id = $_POST["lid"];
$code = $_POST["code"];
$location = $_POST["loc"];
$query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')";
$result = mysql_query($query, $conn);
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<br/><br/>";
echo "<strong>1 record added successfully!</strong>";
echo "<meta http-equiv=\"refresh\" content=\"3;URL=locations.php\">";
}
mysql_close($conn);
}
//Deleting selected records
if(isset($_POST["deletebtn"]))
{
for($i = 0; $i < $count; $i++)
{
$del_id = $_POST["checkbox"][$i];
$query = "DELETE FROM locations WHERE LID = '$del_id' ";
$result = mysql_query($query, $conn);
}
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=locations.php\">";
}
mysql_close($conn);
}
?>
</body>
</html>
Can anyone please tell me what is causing this and how to rectify it.
Thank you.
The records in the database are stored in the database in no particular order (well, there's some order to it, but it's up to the engine to determine it). If you want to get the results in a particular order, then you need to explicitly specify it when querying the data. In your case, make this change:
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations ORDER BY lid";
$result = mysql_query($query, $conn);