How to insert value in dynamic radio button into database? - php

Please help me..I have problem on inserting value in radio button into database. My code is dynamic radio button per row. How can I insert the value into the database? Help me. Im new in PHP programming. Need expert help here. tq
<?php
session_start();
$sql = new mysqli('localhost', 'root', '', 'cpsdatabase');
// Create an array to catch any errors in the registration form.
$errors = array();
if (!empty($_POST) && empty($errors))
{
$query = "INSERT INTO answer (id, staff_id, module_id, question_id, ans)
VALUES(?,?,?,?,?)";
$success = $sql->prepare($query);
//bind parameters for markers, where (s = string, i = integer, d = double, b = blob)
$success->bind_param('issss', $id, $staff_id, $module_id, $question_id, $ans);
if($success->execute()){
echo '<script type="text/javascript">alert("Soalan berjaya disimpan.");</script>';
}
else{
$errors['registration'] = "Tidak Berjatya";
}
$success->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="usersurvey.php" method="post">
<?php
$con=mysqli_connect("localhost","root","","cpsdatabase");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sectionid = $_SESSION['section_id'];
$result = mysqli_query($con,"SELECT * FROM question WHERE section_id='$sectionid' AND module_id='1'");
?>
<table border='3' width=900 cellpadding=3 cellspacing=1 align=center >
<tr>
<th><font size=4>Soalan</font></th>
<th><font size=4>1</font></th>
<th><font size=4>2</font></th>
<th><font size=4>3</font></th>
<th><font size=4>4</font></th>
<th><font size=4>5</font></th>
</tr>
<?php for ($i = 0; $row = mysqli_fetch_array($result); $i++) : ?>
<tr>
<td><?=$row["question_name"];?><input type="hidden" name="question_name[]" value="<?=$row["question_name"];?>"> </div></td>
<input type="hidden" name="staff_id" id="staff_id"></td>
<input type="hidden" name="module_id" id="module_id"></td>
<input type="hidden" name="question_id" id="question_id"></td>
<td><input type="radio" name="ans[<?php echo $i; ?>]" value="1"></td>
<td><input type="radio" name="ans[<?php echo $i; ?>]" value="2"></td>
<td><input type="radio" name="ans[<?php echo $i; ?>]" value="3"></td>
<td><input type="radio" name="ans[<?php echo $i; ?>]" value="4"></td>
<td><input type="radio" name="ans[<?php echo $i; ?>]" value="5"></td>
<tr>
<?php endfor; ?>
</table>
<input type="submit" name="submit" value="Submit" /><center>
</form>
<br><br>
</tr></td>
</table></center>
</body>
</html>

After pressing the submit button the values of your radio buttons will be passed to your usersurvey.php. Use the $_POST[ParameterName] to get the values from your post.
if (!empty($_POST) && empty($errors))
{
$id = $_POST['radiobuttonvalue1'];
$staff_id = $_POST['radiobuttonvalue2'];
$module_id = $_POST['radiobuttonvalue3'];
$question_id = $_POST['radiobuttonvalue4'];
$ans = $_POST['radiobuttonvalue5'];

Related

Insert data from while loop into a table with php

I'm creating a form using HTML and PHP. I have created a form which I want to submit and save that data in database.
I'm trying to submit a form with data that comes from a while loop. All input values are getting generated by while loop.
The code looks like this.
<table width="1348" border="0" class="table table-striped" >
<tr>
<td width="106"> </td>
<td width="332"><strong>Product Code</strong></td>
<td width="375"><strong>Product Name</strong></td>
<td width="211"><strong>QTY</strong></td>
</tr>
<?php
$i = 0;
$rowset = mysql_query("select * from product_detail where productID='".$data['productCode']."'");
while($stuff = mysql_fetch_array($rowset)){
?>
<tr>
<td><input type="text" name="code[<?php echo $i?>]" value="<?php enter code hereecho $stuff['code'];?>"/></td>
<td><input type="text" name="name[<?php echo $i?>]" value="<?php echo $stuff['name'];?>" size="50"/></td>
<td><input type="text" name="qty[<?php echo $i?>]" value="<?php echo $stuff['qty'];?>" size="10"/></td>
</tr>
<?php $i++; }?>
<tr id="last">
</table>
<input type="submit" name="save id="save" class="btn btn-primary btn-lg"/>
This is the code to add the data to database.
$code=$_POST['code'.$i];
$name=$_POST['name'.$i];
$qty=$_POST['qty'.$i];
$query = mysqli_query($con,"insert into stock(productCode, productName, qty) values ('".$code."', '".$name."','".$qty."')") or die(mysqli_error($con));
First, use prepared statement with bind_param as your script is totally exposed to sql injection.
Second, you can add input type hidden for the number of rows
<form action="" method="POST">
<table width="1348" border="0" class="table table-striped" >
<tr>
<td width="106"> </td>
<td width="332"><strong>Product Code</strong></td>
<td width="375"><strong>Product Name</strong></td>
<td width="211"><strong>QTY</strong></td>
</tr>
<?php
$data['productCode'] = "1"; // sample data
$stmt = $con->prepare("SELECT * FROM product_detail WHERE productID = ?");
$stmt->bind_param("i", $data['productCode']);
$stmt->execute();
$result = $stmt->get_result();
$i = 0;
while($stuff = $result->fetch_assoc()) {
?>
<tr>
<td></td>
<td><input type="text" name="code[<?php echo $i; ?>]" value="<?php echo $stuff['code'];?>"/></td>
<td><input type="text" name="name[<?php echo $i; ?>]" value="<?php echo $stuff['name']; ?>" size="50" /></td>
<td><input type="text" name="qty[<?php echo $i; ?>]" value="<?php echo $stuff['qty']; ?>" size="10" /></td>
</tr>
<?php
$i++;
}
?>
<input type="hidden" name="count" value="<?php echo $i; ?>" />
<tr id="last">
</table>
<input type="submit" name="save" id="save" class="btn btn-primary btn-lg"/>
</form>
post count with the form
<?php
if (isset($_POST['save'])) {
$count = $_POST['count'];
for ($i = 0; $i < $count; $i++) {
$code = $_POST['code'][$i]; // check empty and check if interger
$name = $_POST['name'][$i]; // check empty and strip tags
$qty = $_POST['qty'][$i]; // check empty and check if interger
$stmt = $con->prepare("INSERT INTO stock (productCode, productName, qty) VALUES (?, ?, ?)");
$stmt->bind_param("iss",$code,$name,$qty);
$stmt->execute();
}
}
?>
You may also want to check if post values are empty with other necessary validation before insert
Since the table is dynamically filled, you need to use an array as the name attribute
<table>
<tr>
<th>Name</th>
<th>Present</th>
<th>Excused</th>
<th>Unexcused</th>
<th>Ext</th>
</tr>
<?php
$query = "select * from TbCard";
$sql = mysqli_query($connect, $query);
$count = 0;
while ($data = mysqli_fetch_array($sql)) {
?>
<tr>
<td>
<input name="tableRow[<?php echo $count; ?>]['dataName']" id='name' type='text' value="<?php echo $data['Name'];?>" readonly style='border:none;width:350px'></input>
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Present"> Present
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Excused"> Excused
</td>
<td>
<input name="tableRow[<?php echo $count; ?>]['status']" type="radio" value="Unexcused"> Unexcused
</td>
</tr>;
<?php
$count++;
}
?>
</table>
The php would be something like this, assuming that the data has values in it:
$tableRow = $_POST['tableRow'];
foreach($tableRow as $row){
/* here insert data from post */
echo $row['dataName'].' '.$row['status'].'<br/>';
}
To see the content of the array, use print_r($tableRow)
in this case i use a name tableRow

The checkbox's do not hold all value when I select more then one checked

I want insert employee attendance. when I checked more then one checkbox it take two checkbox value 1 and other checkbox value 0 .so how can i solve this please help me. this is my form code
<form action="coll.php" method="post" name="create_grading" id="create_grading">
<table width="30%" border="0" cellpadding="2" cellspacing="3" class="mainTable">
<tr>
<th><input type="checkbox" id="selectall" /></th>
<th>name</th>
</tr>
<?php
$sql = "select * from employee";
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query)) {
?>
<tr>
<td><input type="hidden" name="eid[]" value="<?php echo $row['eid']; ?>"/>
<input name="status[]" class="case" type="checkbox" value="1" /><input name="status[]" class="case" type="hidden" value="0" /></td>
<td align="center"><?php echo $row['employee_name'] ?></td>
</tr>
<?php }; ?>
<tr>
<td></td>
<td><input type="submit" name="Submit" id="Submit" value="Submit" /></td>
</tr>
</table>
</form>
this is my insert code
$host = "localhost";
$user = "root";
$pass = "";
$db = "multiple_row_insert";
$con = mysqli_connect($host, $user, $pass, $db);
if (isset($_POST['Submit'])) {
$eid = $_POST['eid'];
$count = count($eid);
for ($i = 0; $i < $count; $i++) {
$status = $_POST['status'][$i];
$eid2 = $_POST['eid'][$i];
$query = "INSERT INTO time(eid,status) VALUES ('$eid2','$status')";
$query = mysqli_query($con, $query);
}
}
if(isset($_POST['checkbox']))
//then is checked...
else
//is not checked
So basically you only need 1 checkbox, you can change the name of your inputs. And then in your backend use something like:
$_POST['status_'.$i]
On each case and detect if its checked with the "isset" for this $_POST.
Edited:
Your code should look something like this (not tested, sorry if there is any syntax error, you can fix them anyways):
$host = "localhost";
$user = "root";
$pass = "";
$db = "multiple_row_insert";
$con = mysqli_connect($host, $user, $pass, $db);
if (isset($_POST['Submit'])) {
$eid = $_POST['eid'];
$count = count($eid);
for ($i = 0; $i < $count; $i++) {
$status = 0;
if(isset($_POST['status_'.$i])) //check if checkbox is setted (value 1 / checked)
$status = 1;
$eid2 = $_POST['eid'][$i];
$query = "INSERT INTO time(eid,status) VALUES ('$eid2','$status')";
$query = mysqli_query($con, $query);
}
}
And your frontend code:
<form action="coll.php" method="post" name="create_grading" id="create_grading">
<table width="30%" border="0" cellpadding="2" cellspacing="3" class="mainTable">
<tr>
<th><input type="checkbox" id="selectall" /></th>
<th>name</th>
</tr>
<?php
$sql = "select * from employee";
$query = mysqli_query($con, $sql);
$i = 0;
while ($row = mysqli_fetch_array($query)) {
?>
<tr>
<td><input type="hidden" name="eid[]" value="<?php echo $row['eid']; ?>"/>
<input name="status_<?php echo $i; ?>" class="case" type="checkbox" value="0" /></td>
<td align="center"><?php echo $row['employee_name']; ?></td>
</tr>
<?php $i++; } ?>
<tr>
<td></td>
<td><input type="submit" name="Submit" id="Submit" value="Submit" /></td>
</tr>
</table>
</form>

Dynamic insertion of data into database

I have tried out some code for dynamic insertion of data using array but the issue am facing is in a single row same data is been inserted and even if check box are left un-checked data value is inserted ignoring the checked value inside a "while-loop"..I am new to this array concept please help me out.
.php
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<div class="col-md-12">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
echo '
<tr>
<td align="left">' . $row['via'] . '<input type="hidden" name="type[]" value="' . $row['via'] . '"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>';
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
DB.php
<?php
session_start();
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(isset($_POST["submit"]) && isset($_POST["type"])){
//receiving post parameters
$types = $_POST["type"];
if(sizeof($types) > 0 ){
foreach($types as $type){
// create a new user profile
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$type."','".$type."','".$type."','".$type."', NOW())";
if(mysqli_query($con,$sql)){
header('Location: macro_ppl.php');
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}
}
}
?>
First of all checkbox values will not be present in the post if they are not set.
Second of all you add many results cause you call insert sql in the loop.
You can use:
var_dump($_POST['type']);
so you will see how the structure actually look like.
There are many ways to make this work one could be:
//setting the variables first
$ppl = 0;
$macro = 0;
$micro = 0;
$nano = 0;
//then run the loop to set them
foreach($types as $type){
if(in_array($type,['ppl','macro','micro','nano'])) //just to be sure nobody pass something else so we will not override other variables
$$type = 1;
}
//then write the query
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$ppl."','".$macro."','".$micro."','".$nano."', NOW())";
You are doing it wrong, just submit a form with data array
Form
<form id="form" name ="form" method = "POST" action="someForm.php">
<tr>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
</form>
someForm.php
if (isset($_POST['type'])) {
foreach ($_POST['type'] as $myType) {
echo $myType
}
}
Your Form
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
?>
<tr>
<td align="left"><?php echo $row['via'] ?><input type="hidden" name="type[]" value="<?php echo $row['via'] ?>"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
<?php
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
In PHP file
if (isset($_POST['submit'])) {
if(isset($_POST['type'])) {
foreach ($_POST['type'] as $value) {
echo $value;
/*add this in the query, this will return the value of checkbox which are checked*/
}
}
}

Php form update in update the form

I am running while loop and fetch 3 records from database. and then update it on same page. Every record have submit button. But after edit when i submit the form it catchs the values of last record only and update other rows with the last record values. Please if somebody help me out i'll be very thankful. Remember it catches the exact (id) but the other parameters are only of last row.
<form method="post" action="">
<table width="700" border="1">
<tr><th><?php echo $_SESSION['teamtwo']; ?></th></tr>
<tr>
<th>Player Name</th>
<th>Runs</th>
<th>Edit</th>
<th>Save</th>
</tr>
<?php
$team = new DBConnection();
$condition = "WHERE teamname = '".$_SESSION['teamtwo']."' and datecreated = CURDATE()";
$sel_player = $team->SelectRecord(array("*"),"`match`","$condition");
//$sel_player = mysql_query("SELECT * FROM `match` WHERE teamname = '$team1' and datecreated = CURDATE()") or die(mysql_error());
while($get_player = mysql_fetch_array($sel_player))
{
$totalruns = $get_player['runs_bat'];
$totalballs = $get_player['ball_bat'];
#$strike = $totalruns / $totalballs * 100;
?>
<tr>
<td><input type="text" name="player_name" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
<td><button>Edit</button></td>
<td><input type="submit" value="Save" name="team" /></td>
</tr>
<?php
} ?>
</table>
</form>
<?php } ?>
</div>
</div>
</body>
</html>
<?php
if(isset($_POST['team'])){
$runs = $_POST['runs'];
$balls = $_POST['ball'];
$object = new DBConnection();
$arr_Field=array("runs_bat","ball_bat","player_status","how_out","opposite_bowl","opposite_player","sr","overs","bowl_ball","runs_ball","extra","madien");
$arr_Values=array("$runs","$balls","$status","$how_out","$opposite_bowler","$opposite_player","$sr","$over","$bowls","$score","$extra","$madien");
$condition = "WHERE id = '".$_REQUEST['player']."'";
//echo $_REQUEST['player'];
//echo $runs.$balls;
$object->UpdateRecord("`match`",$arr_Field,$arr_Values,"$condition") or die(mysql_error());
//header("Location:extra.php?update");
}
the problem is you are having one form and when you submit the form it will submit the last rows values because you are having same name for all 3 rows inside 1 form.
Solution:-
Create form element inside the while loop and close it inside the while loop itself . Like this you will have 3 forms each for 3 rows.
Code Example:-
while($get_player = mysql_fetch_array($sel_player))
{
$totalruns = $get_player['runs_bat'];
$totalballs = $get_player['ball_bat'];
#$strike = $totalruns / $totalballs * 100;
?>
<form>
<tr>
<td><input type="text" name="player_name" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
<td><button>Edit</button></td>
<td><input type="submit" value="Save" name="team" /></td>
</tr>
</form>
<?php
} ?>
1.
you need to make input array in while because name attribute is overwriting in loop
<td><input type="text" name="player_name[<?php echo $get_player['id']?>]" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs[<?php echo $get_player['id']?>]" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
2.
you have all text boxes mean if press submit button of one row, then also you will get all textboxes as php side so make hidden variable in form to get which button clicked
//write javascript in your page
<script>
function setPlayerId(id) {
document.getElementById('playerid').value=id;
}
</script>
//take hidden field into form
<input type='hidden' name='playerid' value='0'>
//write down onlick button event
<input type="submit" value="Save" name="team" onClick="setPlayerId('<?php <?php echo $get_player['id']?>?>')"/>
3.
Now in php you will get that as below
echo $_POST['player_name'][$_POST['playerid']];
// same way you can do your insert or update.
this code must work
<form method="post" action="">
<table width="700" border="1">
<tr><th><?php echo $_SESSION['teamtwo']; ?></th></tr>
<tr>
<th>Player Name</th>
<th>Runs</th>
<th>Edit</th>
<th>Save</th>
</tr>
<?php
$team = new DBConnection();
$condition = "WHERE teamname = '".$_SESSION['teamtwo']."' and datecreated = CURDATE()";
$sel_player = $team->SelectRecord(array("*"),"`match`","$condition");
//$sel_player = mysql_query("SELECT * FROM `match` WHERE teamname = '$team1' and datecreated = CURDATE()") or die(mysql_error());
while($get_player = mysql_fetch_array($sel_player))
{
$totalruns = $get_player['runs_bat'];
$totalballs = $get_player['ball_bat'];
#$strike = $totalruns / $totalballs * 100;
?>
<tr>
<td><input type="text" name="player_name" value="<?php echo $get_player['player_name']; ?>" disabled="disabled" /></td>
<td><input type="text" name="runs<?=$get_player['id']?>" value="<?php echo $get_player['runs_bat']; ?>" size="1" /></td>
// you didnt write this i added
<input type="text" name="ball<?=$get_player['id']?>" value="<?php echo $get_player['ball_bat']; ?>" size="1" />
<td><button>Edit</button></td>
<td><input type="submit" value="Save" name="team" /></td>
</tr>
<?php
} ?>
</table>
</form>
<?php } ?>
</div>
</div>
</body>
</html>
<?php
if(isset($_POST['team'])){
$runsname = 'runs'.$_GET['player'];
$ballsname = 'ball'.$_GET['player'];
$runs = $_POST[$runsname];
$balls = $_POST[$ballsname];
$object = new DBConnection();
$arr_Field=array("runs_bat","ball_bat","player_status","how_out","opposite_bowl","opposite_player","sr","overs","bowl_ball","runs_ball","extra","madien");
$arr_Values=array("$runs","$balls","$status","$how_out","$opposite_bowler","$opposite_player","$sr","$over","$bowls","$score","$extra","$madien");
$condition = "WHERE id = '".$_REQUEST['player']."'";
//echo $_REQUEST['player'];
//echo $runs.$balls;
$object->UpdateRecord("`match`",$arr_Field,$arr_Values,"$condition") or die(mysql_error());
//header("Location:extra.php?update");
}

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