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);
Related
Look like everything is working fine with this code but in fact fails to update the database, Data are displayed correctly while fetching data but when i press update Button the data disappear but no update has been executed. It look fine to me but seems i am wrong.
This is a project for my professor so i don't care for the SQL injection and others.
<html>
<head>
<link rel="stylesheet" type="text/css" href="btnstyle.css">
<title>Managament System</title>
</head>
<body>
<h1>TU Chemnitz Student managament system</h1>
<br>
ADD Person
Edit Person
Manage Boards
Manage Departments
Search N&S
Triple Search
Membership
<br>
<br>
<?php
// set database server access variables:
$host = "localhost";
$user = "";
$pass = "";
$db = "";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$querys = "SELECT * FROM tblperson";
// execute query
$result = mysql_query($querys) or die ("Error in query: $query. ".mysql_error());
echo "<table border=1 align=center>
<tr>
<th>Personal ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Deparment</th>
<th>Board</th>
<th>Marticulation Number</th>
<th>Reg Date</th>
<th>Action</th>
</tr>";
while($row = mysql_fetch_array($result)) {
?>
<?php
echo '<tr>';
echo '<td>'. $row['personid'].'</td>';
echo '<td>'. $row['personname'].'</td>';
echo '<td>'. $row['personsurname'].'</td>';
echo '<td>'. $row['persondepartment'].'</td>';
echo '<td>'. $row['personboard'].'</td>';
echo '<td>'. $row['martinumber'].'</td>';
echo '<td>'. $row['personregdate'].'</td>';
echo '<td>'.' EDIT '.'</td>';
}
?>
</body>
</html>
and this is the edit file which seems to problematic.
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid'];
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
<form action="edit20.php" method="POST">
<table border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="newpersonname" value="<?php echo $row[1];?>" maxlength="30" size="13"></td>
</tr>
<tr>
<td>Last Name</td>
<td> <input type="text" name="personsurname" value="<?php echo $row[2];?>" maxlength="30" size="30"></td>
</tr>
<tr>
<td>Department</td>
<td>
<select name='persondepartment'>
<option>Production</option>
<option>Sales</option>
</select>
</td>
</tr>
<tr>
<td>Board</td>
<td>
<select name='personboard'>
<option>Evaluation</option>
<option>Executive</option>
<option>Research</option>
</select>
</td>
</tr>
<tr>
<td>Marticulation Number</td>
<td> <input type="text" name="martinumber" maxlength="60" size="30"></td>
</tr>
<tr>
<td>Date of Registration</td>
<td><input type="date" name="personregdate" maxlength="7" size="7"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value=" Update"></td>
</tr>
</table>
</form>
You are looking for personid when the Update button is pressed on the form in edit20.php but that value has never been set so it will be empty and the update will fail.
After
<form action="edit20.php" method="POST">
add:
<input type="hidden" name="personid" value="<?php echo $personid; ?>">
On edit page seem your confusing the same variable with different values. If you state $personid variable to contain the edit value from get, then just re-use the variable don't assign new value. On this line you assign new value :
$personid = $_POST['personid'];
Don't assign new value since it has the initial value already to use just set the variable global for usage
$personid = $_GET['edit'];
Or else create a hidden element and pass edit value into it.
Please add name attribute for your update button
<td colspan="2"><input type="submit" name="update" value=" Update"></td>
and chk whether the update button set or reset as in the place of
if(isset($_POST['newpersonname'])) // change text 'newpersonname' as 'update'
You use a variable that doesn't excist:
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid']; // this doesn't excist
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
$personid = $_POST['personid']; doesn't excist in your code. Its simply a piece of code you put in there to probably proces, but forgot to define the variable in the code. Place the following in your form.
<input type="hidden" name="personid" value="<?php echo $_GET['edit']; ?>">
You only use this just once because you send the form back after proces to your home, hence it wont be used anymore. You can also use the avariable you defined as $personid; on that position.
If that fails, something maybe wrong in your query. Try to echo out the query (remove qucikly the meta command) by simply just do echo $sql after you do the sql query. 9 out of 10 times, it's a typo.
I am trying to edit data into the database I don't know why I cant do. I have tried something till now. maybe someone can have a look please. I am trying to built a update where i can change name, surname blah blah blah, but i cant config even just for a name first..
Home file
Managament System
<body>
<h1>TU Chemnitz Student managament system</h1>
<br>
ADD Person
Edit Person
Manage Boards
Manage Departments
Search N&S
Triple Search
Membership
<br>
<br>
<?php
include_once('coneksioni.php');
// create query
$querys = "SELECT * FROM tblperson";
// execute query
$result = mysql_query($querys) or die ("Error in query: $query. ".mysql_error());
$res = mysql_query("SELECT * FROM tblperson");
echo "<table border=1 align=center>
<tr>
<th>Personal ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Deparment</th>
<th>Board</th>
<th>Marticulation Number</th>
<th>Reg Date</th>
<th>Action</th>
</tr>";
while($row = mysql_fetch_array($res)) {
?>
<tr>
<td><?=$row['personid']?></td>
<td><?=$row['personname']?></td>
<td><?=$row['personsurname']?></td>
<td><?=$row['persondepartment']?></td>
<td><?=$row['personboard']?></td>
<td><?=$row['martinumber']?></td>
<td><?=$row['personregdate']?></td>
<td>
edit |
del
</td>
</tr>
<?php
}
?>
</body>
</html>
and edit20.php
<?php
include_once('coneksioni.php');
if( isset($_GET['edit']) )
{
$personid = $_GET['edit'];
$res= mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row= mysql_fetch_array($res);
}
if( isset($_POST['personname']) )
{
$personname = $_POST['personname'];
$personid = $_POST['personid'];
$sql = "UPDATE tblperson SET personname='$personname' WHERE personid='$personid'";
$res = mysql_query($sql)
or die("Could not update".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
<form action="edit20.php" method="POST">
Name: <input type="text" name="personname" value="<?php echo $row[1]; ?>"><br />
<input type="hidden" name="personid" value="<?php echo $row[0]; ?>">
<input type="submit" value=" Update "/>
</form>
and in the database primary key in my table is personid name field personname (not Primary key).
Please use Prepared Statement for reduce the risk of SQL Injection
check the coneksioni.php
$conn = new mysqli(HOST, USER, PASS, DBNAME);
the edit.php
require_once ('coneksioni.php');
$edit_person = $conn->prepare("
UPDATE tblperson SET
personname = ? WHERE personid = ?
");
$edit_person->bind_param(
"si",
$personname, $personid
);
if(isset($_POST['personname']) && isset($_POST['personid']) ) {
$personname = $_POST['personname'];
$personid = $_POST['personid'];
if (!$edit_person->execute()) {
// action if failed
} else {
// action if success
}
$edit_person->close();
}
the form.html
<form action="edit.php" method="POST">
Name: <input type="text" name="personname" value="<?php echo $row[1]; ?>"><br />
<input type="hidden" name="personid" value="<?php echo $row[0]; ?>">
<input type="submit" value=" Update "/>
</form>
Cheers
Situation: List of question will be read from the database and display inside a table. I can add new row or remove row that I wanted. The data that will be submitted will be store using an array. Update and insert are works perfectly as shown below.
Problems: If user delete some rows on the table, how can I delete those data inside the database.
Sorry for bad grammar/english. Thanks for helping!
Html code:
<table class="msgBox" id="simulator2">
<tr>
<th></th>
<th class="msgSubject">QUESTION</th>
</tr>
<?php
$qry="SELECT ques_item, ques_id FROM log_question WHERE eva_id = '$action'";
$result=mysqli_query($con, $qry);
$count=mysqli_num_rows($result);
$i=1;
while($rows=mysqli_fetch_array($result)){
$eQuesID = $rows['ques_id'];
$eQues = $rows['ques_item'];
?>
<tr class="table-row">
<td><input type="checkbox" name="chk" /></td>
<td class="dataBox"><input type="text" name="eQues[]" value="<?php echo $eQues; ?>" /><input type="hidden" name="eQuesID[]" value="<?php echo $eQuesID; ?>" /></td>
</tr>
<?php $i++;
} $tempCount = $i-1;
?>
</table>
<br />
<center>
<input type="button" value="Add Row" onclick="addRow('simulator2')" />
<input type="button" value="Delete Row" onclick="deleteRow('simulator2')" />
</center>
Php code:
$a = 0;
foreach (array_combine($eQues, $eQuesID) as $eQuest => $eQuestID){
if ($a < $tempCount){ // Update Question
$sql="UPDATE log_question SET ques_item='$eQuest' WHERE ques_id='$eQuestID'";
$test=mysqli_query($con, $sql);
//Check whether the query was successful or not
if(!$test) {
echo("Error description: " . mysqli_error($con));
exit();
}
} else { //Insert New Question
$newsql="INSERT INTO log_question VALUES('', '$eID', '$eQuest')";
$newtest=mysqli_query($con, $newsql);
//Check whether the query was successful or not
if(!$newtest){
echo("Error description: " . mysqli_error($con));
exit();
}
} $a++;
}
I'm creating a form where it allows a user to enter in the number of product rows they would like to have in the form. Then with the corresponding rows, you can select the Product with the Product_ID & Product_Name from a Drop Down List. With the selected item, it should pull the Product_Cost from the table and populate the Unit Price textbox. I can't seem to get the textbox to populate with the correct data. My if statement if (isset($_POST['product' . $i])){ doesn't seem to be working properly, it runs as if the statement were false. I'm trying to say "If a select box has an option selected, take the option selected and find it's corresponding row in the database and take the price found in that row for that product and populate the unit price textbox."
<? require_once("connect_to_DB.php"); //inserts contents of this file here ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Order Form</title>
<meta charset="utf-8">
</head>
<body>
<?
connectDB();
$sql = "SELECT * FROM product";
$sql2 = "SELECT DISTINCT emp_id, emp_fname, emp_lname FROM employee";
$sql3 = "SELECT DISTINCT status_id FROM salesorder ORDER BY status_id asc";
$sql4 = "SELECT * FROM salesorder ORDER BY order_id desc";
$result = mysqli_query($db, $sql) or die("SQL error: " . mysqli_error());
$result2 = mysqli_query($db, $sql2) or die("SQL error: " . mysqli_error());
$result3 = mysqli_query($db, $sql3) or die("SQL error: " . mysqli_error());
$result4 = mysqli_query($db, $sql4) or die("SQL error: " . mysqli_error());
//This is for the options in the product list box
$options = '<option value="selectProduct">Select Product</option>';
while($row = mysqli_fetch_array($result,MYSQLI_NUM)){
$options .= '<option value="' . $row[0] . '">' . $row[0] . ' - ' . $row[2] . '</option>';
}
$row2 = mysqli_fetch_array($result2);
$row3 = mysqli_fetch_array($result3);
$row4 = mysqli_fetch_array($result4);
?>
<div id="order-wrap">
<form method="post" action="example.php">
<table class="orderInfo"><br>
<tr>
<th class="textCol">Product Rows:</th>
<td class="inputCol"><input type="text" name="rows"></td>
<td><input class="update" type="submit" name="update" value="Update"></td>
<td class="inputCol"></td>
</tr>
</table>
</form><!-- Order Rows -->
<form class="orderform" action ="order-report.php" METHOD = "post">
<h2>Order Form</h2>
</table>
<!-- Where the product rows input show go ??? -->
<table class="bottomTable">
<tr>
<th class="textCol">Product</th>
<th class="textCol">Quantity</th>
<th class="textCol">Unit Price</th>
<th class="textCol">Total Price</th>
</tr>
<?
if (isset($_POST['update']))
{
//Execute this code if the update button is clicked.
$num = $_POST['rows'];
for ($i=0; $i<$num; $i++) { ?>
<tr>
<td class="inputCol2">
<select name="'product<?= $i ?>'">
<?
echo $options;
?>
</select>
</td>
<td class="inputCol2"><input type="text" name="'quantity<?= $i ?>'" ></td>
<? if (isset($_POST['product' . $i])){ ?>
<td class="inputCol2"><input type="text" name="'unit<?= $i ?>'" value="<?= $row[3] ?>" placeholder="$" ></td>
<? } else { ?>
<td class="inputCol2"><input type="text" name="'unit<?= $i ?>'" value="" placeholder="$"></td>
<? } ?>
<td class="inputCol2"><input type="text" name="'total<?= $i ?>'" placeholder="$"></td>
</tr>
<? } ?>
<tr>
<td class="textCol"></td>
<td class="textCol"></td>
<td class="textCol">Total Order:</td>
<td class="inputCol2"><input type="text" name="totalfinal" placeholder="$"></td>
</tr>
</table>
<input class="submit" type="submit" value="Submit" name="orderSubmit"/>
</form>
<? } else {?>
<tr>
<td class="textCol"></td>
<td class="textCol"></td>
<td class="textCol">Total Order:</td>
<td class="inputCol2">$<input type="text" name="totalfinal"></td>
</tr>
</table>
<input class="submit" type="submit" value="Submit" name="orderSubmit"/>
</form>
<? } ?>
<?
mysqli_free_result($result);
mysqli_free_result($result2);
mysqli_free_result($result3);
mysqli_free_result($result4);
mysqli_close($db);
?>
</div>
</body>
There appear to be some syntax errors in there, for instance:
<select name="'product<?= $i ?>'">
<?
echo $options;
?>
</select>
There seems to be several instances where this type of quotation marks are used - I think they ought to be more like:
<select name="product<?= $i ?>">
<?
echo $options;
?>
</select>
Also, in a few places you are not using the correct opening tag for the php blocks though someone might point out different. Generally they ought to be:
<?php
/* statements */
?>
or
<?="print out this string";?>
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.