I'm trying to insert multiple row, when I'm insert data it take extra two null row. but why it is happening...Please some one help me to solve this problem.........
this is my form page
<?php
require_once 'Insert_class.php';
$obj_Insert_class=new Insert_class();
$new= $obj_Insert_class->employee_select_data();
$massage='';
if(isset($_POST['btn'])){
$massage=$obj_Insert_class->time_add();
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
<h2>Multiple Insert</h2>
<?php echo $massage; ?>
<form action="" method="post">
<table width='30%'>
<tr>
<td><u><b>EMPLOYEE NAME</b></u></td>
</tr>
<?php
while ($row = mysqli_fetch_assoc($new)) {
?>
<tr>
<td><input name="eid[]" class="case" type="text" value="<?php echo $row['eid']; ?>" /></td>
<td><input name="employee_name[]" class="case" type="text" value="<?php echo $row['employee_name'] ?>"/></td>
<td><input name="status[]" class="case" type="text" value="1"/></td>
<td><input name="first[]" id="first" type="number"/></td>
<td><input name="second[]" id="second" type="number"/></td>
</tr>
<?php } ?>
<tr>
<td></td>
<td><input type="submit" name="btn" value="Submit" /></td>
</tr>
</table>
</form>
</center>
</body>
</html>
this is my insert class page
<?php
require './connect.php';
class Insert_class extends Connect {
protected $link;
public function __construct() {
$this->link = $this->conntection();
}
public function time_add() {
$i = 0;
foreach ($_POST as $val) {
error_reporting(0);
$eid = $_POST['eid'][$i];
$name = $_POST['employee_name'][$i];
$status = $_POST['status'][$i];
$first = $_POST['first'][$i];
$second = $_POST['second'][$i];
$new_add = $first + $second;
$SQL = "INSERT INTO time(eid,name,status,first,seconc,new_add)VALUES('$eid','$name','$status','$first','$second','$new_add')";
if (mysqli_query($this->link, $SQL)) {
$massage = 'DATA Susseccfully inserted';
} else {
die('Select query problem' . mysqli_error($this->link));
}
$i++;
}
return $massage;
}
public function employee_select_data() {
$SQL = "SELECT * FROM employee";
if (mysqli_query($this->link, $SQL)) {
$result = mysqli_query($this->link, $SQL);
return $result;
} else {
die('Select query problem' . mysqli_error($this->link));
}
}
}
Your code contains this loop.
$i = 0;
foreach ($_POST as $val) { /* wrong! */
/* do the insert */
$i ++;
}
This makes no sense. The $_POST is an array of values posted from your form. This loop iterates over each value in that array. That's too many iterations.
Instead, you need to figure out the size of the arrays in your form-field elements of $_POST. Try something like this:
$some_field = $_POST['eid'];
$i = 0;
foreach ($some_field as $junk) {
/* do the insert */
$i++;
}
Related
My problem is a submit button renders under each row of table data. I have searched all over the web to find out, how I can code to use only one submit for the entire form. As it is I can only submit $_POST for one row whereas I need to submit the entire form for processing.
Here is my Code:
<?php
require("config.inc.php");
session_start();
$usrname = $_POST["uname"]; //variable passed from validateuser.html
global $usrname;
//echo $usrname;
// initial query
$query = "SELECT * FROM dfd_usr_profiles WHERE username= '".$usrname."'";
/*$query2 = "UPDATE dfd_usr_profiles SET filters = :fltrs,
regions = :regns
WHERE $usrname = :username"; */
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Profile Information Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["userID"] = $row["userID"];
$post["username"] = $row["username"];
$post["filters"] = $row["filters"];
$post["regions"] = $row["regions"];
//update our repsonse JSON data
array_push($response["posts"], $post);
$endi = count($post);
//echo $endi;
?>
<!DOCTYPE html>
<html>
<script type="text/javascript">
function getRow(n) {
var row = n.parentNode.parentNode;
var cols = row.getElementsByTagName("td");
var i=0;
while (i < cols.length) {
alert(cols[i].textContent);
i++;
}
}
</script>
<body>
<form name="updatefilters" action="update_action.php" method="post" enctype="multipart/form-data>" id="update">
<!-- <input type="submit" name="submit" id="update" value="Update" /> -->
<fieldset>
<table border="1" >
<legend>Update Filters and Regions</legend>
<tr>
<td><input type="checkbox" name="pID[]" value="<?php echo $post['userID']; ?>" onclick="getRow(this)" /></td>
<td><input type="input" name="uname" value="<?php echo $usrname;?>" /></td>
<td><?php echo $post['filters']; ?></td>
<td><label valign="top" for="" id="mfiltervals">Select Deal Type(s) you want:</label></p></td>
<td><?php require("dtypelist.php");?></td>
<td><?php echo $post['regions']; ?></td>
<td><label valign="top" for="" id="mregionvals">Select Region(s) you want:</label></td>
<td><?php require("regionslist.php");?></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
<?php
echo '<button type="submit" name="submitupdate" form="update">Update</button>';
}
// echoing JSON response
// echo json_encode($response); // Commented out: Displays profile unformatted data. TC 070516.
} else {
$response["success"] = 0;
$response["message"] = "No information for this Username is available!";
die(json_encode($response));
}
// session_start(); place-holder
?>
Please help.
You need to move the foreach and the submit button that you have in the code below. All the other code is not relevant for this change. I have marked the 3 parts that need to be moved with // **** Move:
// **** Move this block to just before the `<tr>` tag
foreach ($rows as $row) {
$post = array();
$post["userID"] = $row["userID"];
$post["username"] = $row["username"];
$post["filters"] = $row["filters"];
$post["regions"] = $row["regions"];
//update our repsonse JSON data
array_push($response["posts"], $post);
$endi = count($post);
//echo $endi;
?>
<!DOCTYPE html>
<html>
<script type="text/javascript">
function getRow(n) {
var row = n.parentNode.parentNode;
var cols = row.getElementsByTagName("td");
var i=0;
while (i < cols.length) {
alert(cols[i].textContent);
i++;
}
}
</script>
<body>
<form name="updatefilters" action="update_action.php" method="post" enctype="multipart/form-data>" id="update">
<!-- <input type="submit" name="submit" id="update" value="Update" /> -->
<fieldset>
<table border="1" >
<legend>Update Filters and Regions</legend>
<tr>
<td><input type="checkbox" name="pID[]" value="<?php echo $post['userID']; ?>" onclick="getRow(this)" /></td>
<td><input type="input" name="uname" value="<?php echo $usrname;?>" /></td>
<td><?php echo $post['filters']; ?></td>
<td><label valign="top" for="" id="mfiltervals">Select Deal Type(s) you want:</label></p></td>
<td><?php require("dtypelist.php");?></td>
<td><?php echo $post['regions']; ?></td>
<td><label valign="top" for="" id="mregionvals">Select Region(s) you want:</label></td>
<td><?php require("regionslist.php");?></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
<?php // **** Move this up to just after the `</table>` tag
echo '<button type="submit" name="submitupdate" form="update">Update</button>';
// **** Move this closing brace just after the `</tr>` tag
}
After the 3 moves, it looks as follows -- see comments with ****MOVED****:
?>
<!DOCTYPE html>
<html>
<script type="text/javascript">
function getRow(n) {
var row = n.parentNode.parentNode;
var cols = row.getElementsByTagName("td");
var i=0;
while (i < cols.length) {
alert(cols[i].textContent);
i++;
}
}
</script>
<body>
<form name="updatefilters" action="update_action.php" method="post" enctype="multipart/form-data>" id="update">
<!-- <input type="submit" name="submit" id="update" value="Update" /> -->
<fieldset>
<table border="1" >
<legend>Update Filters and Regions</legend>
<?php // ****MOVED****
foreach ($rows as $row) {
$post = array();
$post["userID"] = $row["userID"];
$post["username"] = $row["username"];
$post["filters"] = $row["filters"];
$post["regions"] = $row["regions"];
//update our repsonse JSON data
array_push($response["posts"], $post);
$endi = count($post);
//echo $endi;
?>
<tr>
<td><input type="checkbox" name="pID[]" value="<?php echo $post['userID']; ?>" onclick="getRow(this)" /></td>
<td><input type="input" name="uname" value="<?php echo $usrname;?>" /></td>
<td><?php echo $post['filters']; ?></td>
<td><label valign="top" for="" id="mfiltervals">Select Deal Type(s) you want:</label></p></td>
<td><?php require("dtypelist.php");?></td>
<td><?php echo $post['regions']; ?></td>
<td><label valign="top" for="" id="mregionvals">Select Region(s) you want:</label></td>
<td><?php require("regionslist.php");?></td>
</tr>
<?php // ****MOVED****
}
?>
</table>
<?php // ****MOVED****
echo '<button type="submit" name="submitupdate" form="update">Update</button>';
?>
</fieldset>
</form>
</body>
</html>
<?php
Make sure to add <?php and ?> where necessary to switch correctly between PHP and normal output.
I need help on how to retain the entered values in the text fields where user entered the value after submit. I'm having difficulty trying to figure out how to retain the values, because when I click on the submit button, the page refreshes and then values gone, and I have to retype them again.
Below is my form:
<?php $count_name = count($x); ?>
<table>
<thead>
<tr>
<th colspan="<?php echo $count_name; ?>"><strong>MR</strong></th>
<th colspan="<?php echo $count_name; ?>"><strong>MS</strong></th>
</tr>
</thead>
<tbody>
<?php $_college = mysql_query("SELECT * FROM college");
if(mysql_num_rows($_college)) {
$i=0;
while($row_college=mysql_fetch_array($_college)) { ?>
<tr>
<?php for($j=0;$j<$count_name;$j++) { ?>
<td>
<input type="text" name="mr<?php echo $j; ?>[]" value=""/>
<td>
<?php } for($k=0;$k<$count_name;$k++) { ?>
<td>
<input type="text" name="ms<?php echo $k; ?>[]" value=""/>
<td>
<?php } ?>
</tr>
<?php } $i++;} ?>
</tbody>
<table>
<input type="hidden" value="<?php echo $count_name; ?>" name="totrows"/>
<input type="submit" value="Submit" name="submit"/>
Here's my code if button submit is click
<?php
if(isse($_POST['submit'])) {
$y = $_POST['totrows'];
$count_totcriteria = $y;
for($ab=0;$ab<$count_totcriteria;$ab++) {
$mr = 'mr_'.$ab;
$ms = 'ms_'.$ab;
$mr_score = $_POST[$mr];
$ms_score = $_POST[$mr];
foreach($mr_score as $key1 => $val1) {
if(is_numeric($val1) && !empty($val1)) {
$mr_val[] = $val1;
} else {
$msg = 'All fields are required and must be a valid score';
}
}
foreach($ms_score as $key2 => $val2) {
if(is_numeric($val2) && !empty($val2)) {
$ms_str[] = $val2;
} else {
$msg = 'All fields are required and must be a valid score';
}
}
}
}
I know I have to put some code in the 'value=""' in order to display back the entered values when form is submitted but I am not sure what code to use. Not sure how to catch each array values.
I think instead of
<input type="text" name="mr<?php echo $j; ?>[]" value=""/>
you are looking for something like this (assuming $i is your new outer loop)
<input type="text" name="mr_<?= $j ?>[<?= $i ?>]" value="<?= #$_POST['mr_'.$j][$i] ?>"/>
and the same change for the ms line.
Does that work?
I'm doing a database project for university and I'm having a problem in here.
I receive from a previous page an id as $_POST['ids'] and in the form I send that same value in a hidden field so it can do a sort of a cicle.
But when I click the submit button I got a lot of errors on $service_info and no information is loaded on the page. I tried do var_dump() everything and I just can't find what is the problem in here.
<?php
//error_reporting();
require 'core/init.php';
require 'db/connect.php';
require 'functions/security.php';
?>
<html>
<head>
<title>Make a reservation</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/common.css">
</head>
<body>
<?php require 'parts/header.php'; ?>
<hr>
<?php
$query = "SELECT * FROM service WHERE id=" . $_POST['ids'];
if ($result = $db->query($query)) {
if ($result->num_rows) {
$service_info = $result->fetch_object();
$result->close();
}
}
$query = "SELECT name FROM tour WHERE id =" . $service_info->idtour;
if ($result = $db->query($query)) {
if ($result->num_rows) {
$tour_name = $result->fetch_object();
$result->close();
}
}
$query = "SELECT SUM(nrseats) AS res_seats FROM reservation_service WHERE idservice =" . $service_info->id;
$nr_reservations_info = $db->query($query);
$nr_reservations = $nr_reservations_info->fetch_row();
$nr_reservations_info->close();
$count = $service_info->nrseats - $nr_reservations[0];
if($count === 0){
echo "<script>alert('There are no more places available for this tour. You are being redirected for the main page!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
$count = $service_info->nrseats;
}
?>
<form action="" method="POST">
<div class="registering">
<table>
<tbody>
<tr>
<td>
<label for="tname">Related tour</label>
</td>
<td>
<label for="splace"><br>Service name</label>
</td><p><br></p>
</tr>
<tr>
<td>
<input type="text" readonly="" name="tour" id="tour" required="" autofocus="" value="<?php echo $tour_name->name ?>">
</td>
<td>
<input type="text" readonly="" name="name" id="name" required="" value="<?php echo $service_info->name ?>">
</td>
</tr>
<tr>
<td>
<label for="sprice"><br>Price (€)</label>
</td>
<td>
<label for="sdescription"><br>Description</label>
</td>
</tr>
<tr>
<td>
<input type="number" name="price" id="price" readonly="" required="" value="<?php echo $service_info->price ?>">
</td>
<td>
<input type="text" name="description" id="description" required="" readonly="" value="<?php echo $service_info->description ?>">
</td>
</tr>
<tr>
<td>
<label for="sseats"><br>Seats left</label>
</td>
<td>
<label for="snreservations"><br>Number of reservations (people)</label>
</td>
</tr>
</tr>
<tr>
<td>
<input type="number" name="nrseats" id="nrseats" required="" value="<?php echo $count ?>" readonly="">
</td>
<td>
<input type="number" name="nrreservations" id="nrreservations" required="" value="1">
</td>
<td>
<input type="hidden" name="ids" required="" value="<?php $service_info->id ?>">
</td>
</tr>
</tr>
<tr>
<td colspan="2">
<label for="next"><br></label>
<input type="submit" value="Next">
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html>
<?php
if (!empty($_POST)) {
if (isset($_POST['name'], $_POST['ids'], $_POST['tour'], $_POST['price'], $_POST['description'], $_POST['nrseats'], $_POST['nrreservations'])) {
$_POST = array_map("trim", $_POST);
$name = $_POST['name'];
$tour = $_POST['tour'];
$price = $_POST['price'];
$description = $_POST['description'];
$nrseats = $_POST['nrseats'];
$nrreservations = $_POST['nrreservations'];
$ids = $_POST['ids'];
if (!empty($name) && !empty($ids) && !empty($tour) && !empty($price) && !empty($description) && !empty($nrseats) && !empty($nrreservations)) {
$query = "SELECT id FROM customer WHERE email='" . $_SESSION['user_email'] . "'";
if ($result = $db->query($query)) {
$id_user = $result->fetch_object();
$result->close();
}
$query = "SELECT id FROM reservation WHERE idtour={$service_info->idtour} AND idcustomer={$id_user->id}";
if ($result = $db->query($query)) {
if ($result->num_rows) {
$id_reservation = $result->fetch_object();
$result->close();
}
}
$query = "SELECT * FROM reservation_service WHERE idservice=" . $service_info->id;
if ($result = $db->query($query)) {
if ($result->num_rows) {
$reservation_service_exists = $result->fetch_object();
if ($nrreservations < 1) {
echo "<script>alert('Your must make a reservation for, at least, one person!')</script>";
echo "<script>window.open('new_reservation_service.php','_self')</script>";
} else if ($count - $nrreservations < 0) {
echo "<script>alert('You can not make the reservation because there are only " . $count . " seats available in this tour!')</script>";
echo "<script>window.open('new_reservation_service.php','_self')</script>";
} else if ($result->num_rows) {
$query = "SELECT * FROM reservation WHERE idcustomer= '" . $id_user->id . "' AND idtour= '" . $service_info->idtour . "'";
if ($result = $db->query($query)) {
if ($result->num_rows) {
$reservation_exists = $result->fetch_object();
$result->close();
if ($reservation_exists->idcustomer === $id_user->id) {
if ($reservation_exists->id === $reservation_service_exists->idreservation) {
echo "<script>alert('You already made a reservation for this service. Please see your reservation panel!')</script>";
echo "<script>window.open('reservations.php','_self')</script>";
}
}
}
}
}
}else {
$query = "INSERT INTO reservation_service (idreservation, idservice, date, nrseats) VALUES (?, ?, NOW(), ?)";
$insert = $db->prepare($query);
$insert->bind_param('iii', $id_reservation->id, $service_info->id, $nrreservations);
$insert->execute();
echo "<script>alert('You successfully made a reservation! You are being redirected to your reservations page')</script>";
echo "<script>window.open('reservations.php','_self')</script>";
}
}
}
}
}
?>
change inside your form this input hidden you created:
<input type="hidden" name="ids" required="" value="<?php $service_info->id ?>">
to
<input type="hidden" name="ids" required="" value="<?php echo $service_info->id ?>">
If you don't echoing this value, $_POST['ids'] won't be get any value passed from form.
This is weird, and ive never seen this before. Im using post to post values back to the same page for processing. Everything is working fine until I try to use a hidden field to post values. Using the same convention ive used a million times before. The odd thing is that its not posting using the name supplied, its just using hiddenField as the name. Here is the code
<input name="eid" type="hidden" id="eid" value="<? print $_GET['eid']; ?>" />
And im using this to figure it out
print_r($_POST);
This is the result
[hiddenField] => 6
Now, its posting the value, and its posting the correct value that is put into the hidden field before its submitted, but for some reason that I cant seem to figure out, its not using the name attribute that I set in HTML to identify it. All my other values are using there posted names. Any insight would be greatly appreciated as I do not wish to have to deal with an awkward array of hiddenFields later on.
Edit: Here is the rest of the code for the page (pertinent parts)
<?
if (isset($_POST['Submit']))
{
print "<p>EID: " . $_POST['hiddenField'] . "</p>";
$eid = $_POST['hiddenField'];
$name = $_POST['name'];
$email = $_POST['email'];
$ncount = count($name);
$ecount = count($email);
$hash = uniqid() . "-" . count($name);
if ($ncount == $ecount)
{
$test = true;
for ($i = 0; $i < $ncount; $i++)
{
if ($name[$i] == "" || $email[$i] == "")
{
$test = false;
}
}
if ($test)
{
$tickets[] = array();
for ($i = 0; $i< $ncount; $i++)
{
$unique = false;
while (!$unique)
{
$tickets[$i] = generateCode();
$check_query = "SELECT id FROM ticket WHERE ticket_number='" . $tickets[$i] . "'";
if ($stmt = $mysqli->prepare($check_query))
{
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
$stmt->close();
if ($count == 0)
{
$unique = true;
} else {
print "<p>Not unique</p>";
}
} else {
print "<p>Failed to work database</p>";
}
}
if ($unique == true)
{
$query = "INSERT INTO ticket (`ticket_number`, `event_id`, `name`, `email`,`date_created`, `hash`) VALUES (?,?,?,?,NOW(),?)";
print "<p>Ticket #" . $tickets[$i] . " Event Id: " . $eid . " Name: " . $name[$i] . " Email: " . $email[$i] . " Hash: " . $hash . "</p>";
if ($stmt = $mysqli->prepare($query))
{
$stmt->bind_param('sisss', $tickets[$i], $eid, $name[$i], $email[$i], $hash);
$stmt->execute();
$number = $stmt->affected_rows;
} else {
print "<p>Could not insert into DB because " . $stmt->error . "</p>";
}
}
}
}
}
}
<form action="register.php" method="post">
<table width="896" border="0">
<?
for($i = 0; $i<$_GET['quant']; $i++)
{
?> <tr>
<td><strong>Attendee <? print $z = $i+1; ?></strong></td>
<td> </td>
</tr>
<tr>
<td width="215">Name</td>
<td width="671"><label for="name"></label>
<input type="text" name="name[]" id="name" /></td>
</tr>
<tr>
<td>Email Address</td>
<td><input type="text" name="email[]" id="name2" /></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<?
}
}
?>
<tr>
<td><input name="eid" type="hidden" id="eid" value="<? print $_GET['eid']; ?>" /></td>
<td><input type="submit" name="Submit" id="Submit" value="Submit" /></td>
</tr>
</table>
</form>
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);