Inserting multiple checkbox values to MySQL - php

I know there are multiple questions here on SO regarding this same issue already and I've looked into them but didn't quite get a satisfying answer. So here goes my question,
I have a form which consists of a few textboxes and checkboxes. It looks like this,
The user can select multiple checkboxes. I'm trying to insert the values(not the displaying text string) of those checkboxes into a MySQL table. It should look like this,
One Service ID(SID) can have multiple Locations(Loc_Code). Those location codes (CO, GQ) are the values of the checkboxes.
I've written this following code so far.
<html>
<head>
</head>
<body>
<?php
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new ServiceID */
$query = "SELECT SID FROM taxi_services ORDER BY SID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row["SID"];
$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);
$new_id = $id_letter . $id_num;
//Selecting locations
$query = "SELECT Loc_Code, Name FROM districts";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<?php
if(isset($_POST["savebtn"]))
{
//inserting the new service information
$id = $_POST["sid"];
$name = $_POST["name"];
$cost = $_POST["cost"];
if($_POST["active"] == "on") $active = 1; else $active = 0;
$query = "INSERT INTO taxi_services(SID, Name, Cost, Active) VALUES('$id', '$name', '$cost', '$active')";
$result = mysql_query($query, $conn);
//inserting the location details
for($j = 0; $j < $count; $j++)
{
$loc_id = $_POST["checkbox2"][$j];
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
if (!$result || !$result5)
{
die("Error " . mysql_error());
}
else
{
?>
<script type="text/javascript">
alert("Record added successfully!");
</script>
<?php
}
mysql_close($conn);
}
?>
<div id="serv">
<b>Enter a new taxi service</b>
<br/><br/>
<form name="servForm" action="<?php $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Service ID</td>
<td><input type="text" name="sid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name" style="text-align:right" /></td>
</tr>
<tr>
<td>Cost</td>
<td><input type="text" name="cost" style="text-align:right" onkeypress="return isNumberKey(event)" /></td>
</tr>
<tr>
<td>Active</td>
<td><input type="checkbox" name="active" /></td>
</tr>
</table>
</div>
<div id="choseLoc">
Locations <br/><br/>
<table border="0">
<?php
$a = 0;
while($row = mysql_fetch_array($result))
{
if($a++ %5 == 0) echo "<tr>";
?>
<td align="center"><input type="checkbox" name="checkbox2[]" value="<?php echo $row['Loc_Code']; ?>" /></td>
<td style="text-align:left"><?php echo $row["Name"]; ?></td>
<?php
if($a %5 == 0) echo "</tr>";
}
?>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</form>
</div>
</body>
</html>
It inserts the Service details correctly. But when it inserts location data, a problem like this occurs,
I selected 4 checkboxes and saved. The 4 location codes gets saved along with the service ID. But as you can see from the screenshot above, a bunch of empty rows gets inserted too.
My question is how can I stop this from happening? How can I insert the data from the checkboxes only I select?
Thank you.

One way would be to only loop over the checkboxes that were submitted:
//inserting the location details
foreach($_POST["checkbox2"] as $loc_id)
{
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
I reiterate here the SQL injection warning given above: you would be much better off preparing an INSERT statement and then executing it with parameters. Using PDO, it would look something like:
//inserting the location details
$stmt = $dbh->prepare('
INSERT INTO service_locations(SID, Loc_Code) VALUES(:id, :loc)
');
$stmt->bindValue(':id', $id);
$stmt->bindParam(':loc', $loc_id);
foreach($_POST["checkbox2"] as $loc_id) $stmt->execute();

from these sentence:
for($j = 0; $j < $count; $j++)
{
$loc_id = $_POST["checkbox2"][$j];
$query = "INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id')";
$result5 = mysql_query($query, $conn);
}
i find the problem is that the value of loc_code must be the last loction you selected. because in this loop, the value of loc_code will replaced everytime. if you want to insert all the location, you should put it on the one sentence, like INSERT INTO service_locations(SID, Loc_Code) VALUES('$id', '$loc_id'), the value of $loc_id should be CO,GQ,GL.

This is happening because the checkboxes that weren't ticked still get posted, they just have empty values. Before you do your insert to service_locations just check if $loc_id is empty or not, only do the insert if it isn't.

Related

Update MySQL using HTML Form

I'm trying to create a form which allows you to update a database table using php.
I'm kinda new to PHP so excuse me if I make a stupid mistake in the code.
This is my edit.php code:
<html>
<head>
</head>
<body>
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM cats");
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<?php
while($row = mysqli_fetch_array($result))
{
$name = $row['name'];
$email = $row['email'];
$rank = $row['rank'];
$birth = $row['birth'];
$joined = $row['joined'];
$steamid = $row['steamid'];
?>
<td width="100"></td>
<td><?=$name?></td>
</tr>
<tr>
<td width="100">Email</td>
<td><input name="emailid" type="text" value="<?=$email?>"></td>
</tr>
<tr>
<td width="100">Rank</td>
<td><input name="rankid" type="text" value="<?=$rank?>"></td>
</tr>
<tr>
<td width="100">Birth</td>
<td><input name="birthid" type="text" value="<?=$birth?>"></td>
</tr>
<tr>
<td width="100">Joined</td>
<td><input name="joinedid" type="text" value="<?=$joined?>"></td>
</tr>
<tr>
<td width="100">Steamid</td>
<td><input name="steamidid" type="text" value="<?=$steamid?>"></td>
</tr>
<?php } ?>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
if(isset($_POST['update']))
{
$name = $row['nameid'];
$email = $row['emailid'];
$rank = $row['rankid'];
$birth = $row['birthid'];
$joined = $row['joinedid'];
$steamid = $row['steamidid'];
$update = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
$retval = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
}
echo "Updated data successfully\n";
}
mysqli_close($con);
?>
</body>
</html>
It shows the table and information but the updating isn't working.
Updated data successfully
I've checked the database but it's not updating anything.
Dear i think you change the record based on Name because you can use $name in where clause and you can also change the Name than never true where clause so that your query execute successfully but not effected on any of the row.
you want to get for editable record and that's unique id base update row it will defiantly work.
Try to use PHP PDO database access functions, your code as it stands is vulnerable to SQL-Injection! PDO will also make debugging and working with the database much easier.
I think your check for "update" in $_POST is not working because update is not a field inside your form but the submit button itself, try to check for one of the fields instead.
Informations:
With mysqli_error() you need to write about which connection you want to get errors, like this:
mysqli_error($con);
With mysqli_query() you need to give two parameters, connection and query like this:
$update = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
How to debug:
If you want to check that UPDATE query return any error you can do something like this:
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
}
You can try to debug your query with something like this:
$sql = "UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';";
echo $sql; // this output write in your phpMyadmin to check if there are any errors.
$update = mysqli_query($con, $sql);
Other problem we got:
1. I think also you should have else in your code, f.ex.:
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
} else {
echo "Updated data successfully\n";
}
2. You are not getting data from $_POST it should be like:
$name = $_POST['nameid']; // not $row['nameid']
$email = $_POST['emailid'];
$rank = $_POST['rankid'];
$birth = $_POST['birthid'];
$joined = $_POST['joinedid'];
$steamid = $_POST['steamidid'];
More about used functions:
PHP: mysqli::$error
PHP: mysqli::query
In your case it is Procedural style

How to insert multiple rows of student records scores in a while loop in a database table?

I want to create a table with input fields where student records can be inserted. The name of the students are in the first column of the table fetched from the database with a while loop. The other columns contain fields for inputing the student scores. The challenge I'm facing is how to insert the records of all the students in different row of a table called result_sec into the database. I've search for similar post but couldn't get a suitable answer. Below is the code. Thanks in advance.
<?php require('header.php'); ?>
<?php
$query_form = sprintf("SELECT * FROM regform LIMIT 2");
$form = mysqli_query($conn, $query_form) or die(mysqli_error($conn));
$formdata = mysqli_fetch_assoc($form);
if(isset($_POST['submit']))
{
$exes = $_POST['exe'];
$asss = $_POST['ass'];
$ca1s = $_POST['ca1'];
$ca2s = $_POST['ca2'];
$exams = $_POST['exam'];
foreach($exes as $key => $exe)
{
$sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam) VALUES ('$exe', '$asss[$key]', '$ca1s[$key]', '$ca2s[$key]', '$exams[$key]')";
}
$insert = mysqli_multi_query($conn, $sql);
}
?>
<form method="POST">
<table>
<thead>
<tr>
<th>Name</th>
<th>Ass.</th>
<th>Exe.</th>
<th>1st C.A.</th>
<th>2nd C.A.</th>
<th>Exam</th>
</tr>
</thead>
<tbody>
<?php do { ?>
<tr>
<td><?php echo $formdata['surname']." ".$formdata['firstname']; ?></td>
<td><input name="ass[]" size="1px"/></td>
<td><input name="exe[]" size="1px" /></td>
<td><input name="ca1[]" size="1px" /></td>
<td><input name="ca2[]" size="1px" /></td>
<td><input name="exam[]" size="1px" /></td>
<input type="hidden" name="regformid[]" value="<?php echo $formdata['regformid'];?>" />
</tr>
<?php } while ($formdata = mysqli_fetch_assoc($form)); ?>
</tbody>
</table>
<button type="submit">Insert Student Record</button>
</form>
<?php require('footer.php'); ?>
See If this resolve your problem
if(isset($_POST['submit'])){
$exes = $_POST['exe'];
$asss = $_POST['ass'];
$ca1s = $_POST['ca1'];
$ca2s = $_POST['ca2'];
$exams = $_POST['exam'];
//You can use a foreach loop to loop over one of the repeated inputs, and then use the index to access the corresponding elements in the others:
foreach ($exes as $i => $exe) {
$exee = mysqli_real_escape_string($exe);
$ass = mysqli_real_escape_string($asss[$i]);
$ca1 = mysqli_real_escape_string($ca1s[$i]);
$ca2 = mysqli_real_escape_string($ca2s[$i]);
$exam = mysqli_real_escape_string($exams[$i]);
$sql = "INSERT INTO result_sec (exe, ass, ca1, ca2, exam)
VALUES ('$exee', '$ass', '$ca1', '$ca2', '$exam')";
$insert = mysqli_multi_query($conn, $sql);
}
}

form wont send data to mysql

I'm trying to code a form that gets some data from a mysql db, and the rest i have to fill inn myself. The problem is that in add.php witch insert to mysql dont get data from the form.
My codes are:
<form action="add.php" method="post">
<table border="0px" align="center" width="300px">
<tr align="center">
<td><h2>Flight</h2></td>
<td><h2>Org</h2></td>
<td><h2>Dest</h2></td>
<td><h2>STD</h2></td>
<td><h2>ATD</h2></td>
<td><h2>Delay</h2></td>
<td><h2>NET</h2></td>
<td><h2>Gros</h2></td>
<td><h2>Core Material</h2></td>
<td><h2>ACS</h2></td>
<td><h2>Total sorted</h2></td>
</tr>
<?php
$con = mysql_connect("localhost","db","pass") or die('Could not connect: ' .mysql_error());
mysql_select_db("db", $con) or die(mysql_error());
$q="SELECT flightnr, org, dest, std FROM flight";
$sql = mysql_query($q) or die("MySQL ERROR: ".mysql_error());
while($row = mysql_fetch_array($sql))
{
$flightnr2 = $row['flightnr'];
$org2 = $row['org'];
$dest2 = $row['dest'];
$std2 = $row['std'];
}
?>
<tr>
<td><input type="text" name="flightnr" value="<?php echo $flightnr2;?>" /></td>
<td><input type="text" name="org" id="org" value="<?php echo $org2;?>" /></td>
<td><input type="text" name="dest" id="dest" value="<?php echo $dest2;?>" /></td>
<td><input type="text" name="std" id="std" value="<?php echo $std2;?>" /></td>
<td><input type="time" name="adt" id="adt" placeholder="ATD"></td>
<td><input type="time" name="delay" id="delay" placeholder="Delay"></td>
<td><input type="int" name="net" id="net" placeholder="NET"></td>
<td><input type="int" name="gros" id="gros" placeholder="Gros"></td>
<td><input type="int" name="core" id="core" placeholder="Core Material"></td>
<td><input type="int" name="acs" id="acs" placeholder="ACS"></td>
<td><input type="int" name="tot" id="tot" placeholder="Total sorted"></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
add.php:
<?php
$con = mysql_connect("localhost","db","pass") or die('Could not connect: ' .mysql_error());
mysql_select_db("db", $con) or die(mysql_error());
$date = date("D-m-Y");
$flightnr = $_POST['flightnr'];
$org = $_POST['org'];
$dest = $_POST['dest'];
$std = $_POST['dest'];
$adt = mysql_real_escape_string($_POST['adt']);
$delay = mysql_real_escape_string($_POST['delay']);
$net = mysql_real_escape_string($_POST['net']);
$gros = mysql_real_escape_string($_POST['gros']);
$core = mysql_real_escape_string($_POST['core']);
$acs = mysql_real_escape_string($_POST['acs']);
$tot = mysql_real_escape_string($_POST['tot']);
$sql="INSERT INTO fly (date, flightnr, org, dest, std, adt, delay, net, gros, core, acs, tot)VALUES('$date', '$flightnr', '$org', '$std', '$adt', '$delay', '$net', '$gros', '$core', '$acs', '$tot')";
$result=mysql_query($sql);
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
?>
Any idea how I can get it to work...
In add.php you're checking $row instead of $_POST.
It should be:
if (isset($_POST['atd']) && isset($_POST['..']) && ... )
{
$values = Array($_POST['atd'], $_POST['..'], ...);
$values = array_map("mysql_real_escape_string", $values);
$sql = "INSERT INTO fly (date, flightnr, org, dest, std, adt, delay, net, gros, core, asc, tot) VALUES ('" . implode(',', $values) . "');";
}
Anyway you should use PDO or MySQLi because MySQL is deprecated.
There is a lot of miss spelling and mistakes here.. take a look at this:
echo '<td><input type="int" name="acs" id="acs" placeholder="ACS"></td>'
and
$asc = mysql_real_escape_string($_POST['asc']);
So you realy have to read your codes, and check your spelling.
Here is one more:
$dest = $row['dest'];
$std = $row['dest'];
This should be like this:
$dest = $row['dest'];
$std = $row['std'];
in your form add hidden field like
">
in your add.php file get your data like
$flightner=$_POST['flightnr'];
then fire sql query insert into..
<input type="hidden" name="test" id="test" value="<?php echo $row['flightnr'];?>"/>
Hi.. xzibiz
First,you have to store a value $row['flightnr'] in specific hidden field then use $_POST['test'] to fetch actual value
$flightnr=$_POST['test'];
Reason for error...
php only reads those data which sent by html input field so you can fetch those value from inputed field html using php server variable $_REQUEST['html_input_field']
I've got it working now.. my new code is:
$q="SELECT flightnr, org, dest, std FROM flight";
$sql = mysql_query($q) or die("MySQL ERROR: ".mysql_error());
while($row = mysql_fetch_array($sql))
{
$flightnr2 = $row['flightnr'];
$org2 = $row['org'];
$dest2 = $row['dest'];
$std2 = $row['std'];
}
?>
<tr>
<td><input type="text" name="flightnr" value="<?php echo $flightnr2;?>" /></td>
<td><input type="text" name="org" id="org" value="<?php echo $org2;?>" /></td>
<td><input type="text" name="dest" id="dest" value="<?php echo $dest2;?>" /></td>
<td><input type="text" name="std" id="std" value="<?php echo $std2;?>" /></td>
add.php:
$date = date("D-m-Y");
$flightnr = $_POST['flightnr'];
$org = $_POST['org'];
$dest = $_POST['dest'];
$std = $_POST['dest'];
$adt = mysql_real_escape_string($_POST['adt']);
$delay = mysql_real_escape_string($_POST['delay']);
$net = mysql_real_escape_string($_POST['net']);
$gros = mysql_real_escape_string($_POST['gros']);
$core = mysql_real_escape_string($_POST['core']);
$acs = mysql_real_escape_string($_POST['acs']);
$tot = mysql_real_escape_string($_POST['tot']);
$sql = "INSERT INTO fly ".
"(date, flightnr, org, dest, std, adt, delay, net, gros, core, acs, tot) ".
"VALUES ('$date', '$flightnr', '$org', '$dest', '$std', '$adt', '$delay', '$net', '$gros', '$core', '$acs', '$tot')";
$retval = mysql_query( $sql, $con );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($con);
?>

Image is not storing in mysql database via php

I am trying to upload image and store it in mysql database through php. but no image is storing in database.
<form action="" method="get" name="frmPostImage" class="box" enctype="multipart/form-data">
<table>
<tr>
<td><b>City:</b></td>
<td>
<select name="cityid">
<?php
$sql = "SELECT cityid, cityname, countryname
FROM $t_cities ct
INNER JOIN $t_countries c ON ct.countryid = c.countryid
ORDER BY c.pos, ct.pos";
$res = mysql_query($sql) or die(mysql_error());
while($row=mysql_fetch_array($res))
{
echo "<option value=\"$row[cityid]\"";
if ($row['cityid'] == $_REQUEST['cityid']) echo " selected";
echo ">$row[countryname] > $row[cityname]</option>";
}
?>
</select>
</td>
</td>
</tr>
<tr>
<tr>
<td><b><?php echo $lang['POSTIMG_IMAGE_TITLE']; ?>:</b><span class="marker">*</span></td>
<td><input name="imgtitle" type="text" id="imgtitle" size="55" maxlength="100" value="<?php echo isset($data
['imgtitle']); ?>"><br><img
src="images/spacer.gif"></td>
</tr>
<tr>
<td><b><?php echo $lang['POSTIMG_IMAGE_FILE']; ?>:</b><span class="marker">*</span></td>
<td><input name="img" type="file" size="45"><br><img src="images/spacer.gif"></td>
</tr>
<tr>
<td><b><?php echo $lang['POSTIMG_IMAGE_DESCRIPTION']; ?>:</b></td>
<td><textarea name="imgdesc" type="text" rows="5" cols="54"><?php echo $data['imgdesc']; ?></textarea><br><img
src="images/spacer.gif"></td>
<td> <input type="hidden" name="do" value="save"><button type="submit">Go</button></td>
</tr>
</table>
</form>
and following code to store it into database.
$expiry = time()+($expire_images_after*24*60*60);
$expiry_dt = date("Y-m-d H:i:s", $expiry);
$city = $_REQUEST['cityid'];
// Temporary file name stored on the server
$tmpName = $_FILES['img']['tmp_name'];
$sql = "INSERT INTO $t_imgs
SET imgtitle = '$_GET[imgtitle]',
imgfilename = '$tmpName',
imgdesc = '$_GET[imgdesc]',
postername = '$data[postername]',
cityid = '$city',
ip = '$ip',
verified = '1',
enabled = '1',
createdon = NOW(),
expireson = '$expiry_dt',
timestamp = NOW()";
mysql_query($sql) or die($sql.mysql_error());
if (mysql_affected_rows())
{
// Get ID
$sql = "SELECT LAST_INSERT_ID() FROM $t_imgs";
list($imgid) = mysql_fetch_array(mysql_query($sql));
}
}
?>
<h2><?php echo $lang['POST_IMAGE_SUCCESS']; ?></h2>
i am able to store every other value except the image. tried different combination but nothing worked. Guide me...:)
I think there can be issues with mysql statement:
instead $sql = "INSERT INTO $t_imgs SET imgtitle
you should probably use $sql = "INSERT INTO $t_imgs values (imgtitle, ...);
check here:
http://dev.mysql.com/doc/refman/5.5/en/insert.html

Records not getting inserted in ascending order

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);

Categories