Submitting multiple form row into table using sql loop - php

i have collected multiple rows from a student table. and its listing them just fine.
<?php
$sql = "SELECT * FROM `students` WHERE `class`='$class' && `academicyear`='$academicyear'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo #++$n ; ?> </td>
<td><?php echo $row["studentid"]?> <input type="text" name="studentid" value="<?php echo $row["studentid"]?>" style="visibility: hidden; width: 10px;"></td>
<td><?php echo $row["fname"]?> &nbsp <?php echo $row["sname"]?> <input type="text" name="name" value="<?php echo $row["fname"]?> <?php echo $row["sname"]?>" style="visibility: hidden; width: 10px;"></td>
<td style="display: none; width: 10px;"><input type="text" name="class" value=" <?php echo $class; ?>"> </td>
<td style="display: none; width: 10px;"><input type="text" name="academicyear" value=" <?php echo $academicyear; ?>"></td>
<td style="display: none; width: 10px;"><input type="text" name="rowcount" value=" <?php echo $rowcount; ?>"> </td>
</tr>
<?php
}
} else {
echo "";
}
mysqli_close($conn);
?>
my difficulty is how to submit this multiple rows into another table called classlist
<?php
// Receiving variables
#$pfw_ip= $_SERVER['REMOTE_ADDR'];
#$example1_length = addslashes($_POST['example1_length']);
#$studentid = addslashes($_POST['studentid']);
#$name = addslashes($_POST['name']);
#$class = addslashes($_POST['class']);
#$academicyear = addslashes($_POST['academicyear']);
#$rowcount = addslashes($_POST['rowcount']);
// Validation
//saving record to MySQL database
#$pfw_host = "localhost";
#$pfw_user = "root";
#$pfw_pw = "";
#$pfw_db = "myschool";
$pfw_link = mysql_connect($pfw_host, $pfw_user, $pfw_pw);
if (!$pfw_link) {
die('Could not connect: ' . mysql_error());
}
$pfw_db_selected = mysql_select_db($pfw_db, $pfw_link);
if (!$pfw_db_selected) {
die ('Can not use $pfw_db : ' . mysql_error());
}
$i=0;
while ($i<= $rowcount) {
#$pfw_strQuery = "INSERT INTO `classlist`(`studentid`,`name`,`class`,`academicyear`) VALUES (\"$studentid\",\"$name\",\"$class\",\"$academicyear\")" ;
$rowcount = $rowcount - 1;
}
//insert new record
$pfw_result = mysql_query($pfw_strQuery);
if (!$pfw_result) {
die('Invalid query: ' . mysql_error());
}
mysql_close($pfw_link);
header('location:classlist.php');
?>
i only get the last row data submitted into the classlist table then an error appear -- invalid query, duplicate query.
please help.

You must use single quotes to wrap strings in SQL
#$pfw_strQuery = "INSERT INTO `classlist`(`studentid`,`name`,`class`,`academicyear`) VALUES ('$studentid','$name','$class','$academicyear')" ;

Related

how to solve Undefined offset: error in php

I have a html code where I create a table and two radio button on each row. for giving different name to radio button on each row I used while loop and I++ way.
that is
<form action = "submit_varification.php" method = "POST" onclick = "return validate()">
<div style="position: absolute; left: 50px; top: 90px;">
<label class="right"><font color="white">Date:</font></label>
<input type="text" id = "frmDate" /><br>
<p id="date"></p>
</div>
<div style="position: absolute; left: 250px; top: 91px;">
<label class="right"><font color="white">V-ID:</font></label>
<input type="text" id = "myText" name = "reviewer" value = ""/><br>
</div>
<div style="position: absolute; left: 900px; top: 91px;">
<button type="button" name="show" id="show" onclick = "" >History</button>
</div>
<div style="position: absolute; left: 900px;">
<input type="submit" name="test" id="test" value="Submit" /><br/>
</div>
<script>
var date = new Date();
document.getElementById("frmDate").value = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
</script>
</body>
<table style="position: absolute; width:95%; left: 20px; top: 150px;" id = "table1">
<?php
$myDate = date('m/d/Y');
?>
<tr>
<th>Date</th>
<th>Time</th>
<th>Alias</th>
<th>Machine_Name</th>
<th>Build_Name</th>
<th>Build_version</th>
<th>WinDBG</th>
<th>.Net_Framework</th>
<th>Status</th>
</tr>
<?php
//get records from database
$sql3 = "SELECT * FROM data WHERE `Date` = '".$myDate."' ORDER BY id DESC";
$query = $conn->query($sql3);
if($query->num_rows > 0){
$i = 0 ;
while($row = $query->fetch_assoc()){ ?>
<tr>
<td><?php echo $row['Date']; ?></td>
<td><?php echo $row['Time']; ?></td>
<td><?php echo $row['Alias']; ?></td>
<td><?php echo $row['Machine_Name']; ?></td>
<td><?php echo $row['Build_Name']; ?></td>
<td><?php echo $row['Build_Version']; ?></td>
<td><?php echo $row['WinDBG']; ?></td>
<td><?php echo $row['.NET_Framework']; ?></td>
<td style='white-space: nowrap'><form><label class = "ready"><input type="radio" name="[<?php $i ?>]" value = "Ready">Ready</label><label class = "notready"><input type="radio" name="[<?php $i ?>]" value = "Not Ready" >Not Ready</label></form></td>
</tr>
<?php $i++ ; } } ?>
</table>
</form>
and I want to store the value of each row to a database. so I used POST method on the form. and I am trying to take the value of radio button to database but I am facing a error like
Notice: Undefined offset: 0 in C:\wamp64\www\submit_varification.php on line 33
Notice: Undefined offset: 1 in C:\wamp64\www\submit_varification.php on line 33
Notice: Undefined offset: 2 in C:\wamp64\www\submit_varification.php on line 33
and the PHP code:
$query = $conn->query($sql4);
if($query->num_rows > 0){
$i = 0 ;
while($row = $query->fetch_assoc()){
//...insert into your DB.
$row1 = $row["Date"];
$row2 = $row["Time"];
$row3 = $row["Alias"];
$row4 = $row["Machine_Name"];
$row5 = $row["Build_Name"];
$row6 = $row['Build_Version'];
$row7 = $row["WinDBG"];
$row8 = $row[".NET_Framework"];
$status = $_POST["$i"]; // this is the error
$sql5 = "INSERT INTO history (`Date`, `Time`, `Alias`, `Machine_Name`, `Build_Name`, `Build_version`, `WinDBG`, `.NET_Framework`, `Status`, `Reviewed_By`)
VALUES ('".$row1."','".$row2."','".$row3."','".$row4."','".$row5."','".$row6."','".$row7."','".$row8."', '".$status."', '".$reviewer."') ";
if ($conn->query($sql5) === TRUE) {
//echo "New record created successfully";
//echo nl2br("\n");
echo "";
} else {
echo "Error: " . $sql5 . "<br>" . $conn->error;
}
$i++ ;
}
}
is anyone have any solution for this ?
Dump the array that populates $i for each loop. I would wager the array does not have the array key that the name="[<?php $i ?>]" is expecting.
Can you remove the brackets in the name attribute and see if its working correct. Below is the code:
<td style='white-space: nowrap'>
<form><label class = "ready">
<input type="radio" name="<?php $i ?>" value = "Ready">Ready</label>
<label class = "notready"><input type="radio" name="<?php $i ?>" value = "Not Ready" >Not Ready</label>
</form>
Plus it would be better if you have some static text appended to the name column and in server side, you can loop it:
<td style='white-space: nowrap'>
<form><label class = "ready">
<input type="radio" name="status_<?php $i ?>" value = "Ready">Ready</label>
<label class = "notready"><input type="radio" name="status_<?php $i ?>" value = "Not Ready" >Not Ready</label>
</form>
Let me know if this helps..
You make nested forms. replace the line
<td style='white-space: nowrap'><form><label class = "ready"><input type="radio" name="[<?php $i ?>]" value = "Ready">Ready</label><label class = "notready"><input type="radio" name="[<?php $i ?>]" value = "Not Ready" >Not Ready</label></form></td>
with this:
<td style='white-space: nowrap'><label class = "ready"><input type="radio" name="<?php $i ?>" value = "Ready">Ready</label><label class = "notready"><input type="radio" name="<?php $i ?>" value = "Not Ready" >Not Ready</label></td>
Also remove the brackets, like gopal panadi mentioned.
Furthermore I am not sure if you can have input tags inside labels. shouldn't they be next to each other?
Edit: after that if it fails, dump the $_POST array and see how/if the radio values are in $_POST. var_dump($_POST);die();

How can i use values returned from a PHP function in querying and displaying data from a table?

Am attempting to display test results of multiple students in a class. To do this, am using a function find_student_by_year($year) to get a list of all the students which includes the student id. The id is then used in an sql statement to query the result for the specific student id. My code isn't throwing errors but no data is displayed even though the table actually has data. Unfortunately, my research has shown nothing similar so no link is added to my post. See code am working with below
Function
function find_student_by_year($year) {
global $connection;
$query = "select * from students where entry_year = {$year} order by s_fname asc";
$found_students = mysqli_query($connection, $query);
confirm_query($found_students);
return $found_students;
}
PHP and HTML (mixed) code
<tbody>
<?php
$staff_id = 27;
$subject_id = 2;
//Actually getting this value from $_GET but am hard coding it here
$year = 4;
if (isset($year)) {
$student_year = find_student_by_year($year);
} else {
$student_year = null;
}
if (isset($student_year)) {
while ($year_group = mysqli_fetch_assoc($student_year)) {
?>
<tr>
<td><input name="student_id[]" value="<?php echo htmlentities($year_group["student_id"]) ?>" readonly></td>
<td><?php echo $year_group["s_fname"] . " " . $year_group["s_mname"] . " " . $year_group["s_lname"]; ?></td>
<?php
$result = mysqli_query($connection, "select * from results where student_id = {$year_group['student_id']} and subject_id = {$subject_id}");
while($result_record = mysqli_fetch_assoc($result)) {
?>
<td style="width: 15%"><input type="text" name="test1[]" class="form-control" style="text-align: center"
value="<?php if ($result_record['test1'] !== ' ') { echo $result_record['test1']; } else {echo ' ';} ?>">
</td>
<td style="width: 15%"><input type="text" name="test2[]" class="form-control" style="text-align: center"
value="<?php if ($result_record['test2'] !== ' ') { echo $result_record['test2']; } else {echo ' ';} ?>">
</td>
<td style="width: 15%"><input type="text" name="test3[]" class="form-control" style="text-align: center"
value="<?php if ($result_record['test3'] !== ' ') { echo $result_record['test3']; } else {echo ' ';} ?>">
</td>
<td style="width: 15%"><input type="text" class="form-control" style="text-align: center"
value="<?php echo htmlentities($result_record['final']); ?>" readonly>
</td>
</tr>
<?php } } } ?>
</tbody>
See database table and display screenshot
Created a view using a join statement on students and records table using the student_id column. Then queried the view and displayed each student's result using the student_id. See code extract below
<?php
$subject_id = 2;
if (isset($_GET["year"])) {
$result = mysqli_query($connection, "select * from fullresult where year = {$_GET["year"]} and subject_id = {$subject_id}");
while($student_result = mysqli_fetch_assoc($result)) {
?>
<tr>
<td style="display: none"><input name="student_id[]" value="<?php echo htmlentities($student_result["student_id"]) ?>"></td>
<td><?php echo $student_result["firstname"] . " " . $student_result["middlename"] . " " . $student_result["lastname"]; ?></td>
<td style="width: 15%; text-align: center">
<?php
if ($student_result['test1'] !== ' ') {
echo $student_result['test1']; } else {
echo '<input type="text" name="test1[]" class="form-control" style="text-align: center" value="">';
}
?>
</td>
<td style="width: 15%; text-align: center">
<?php
if ($student_result['test2'] !== ' ') {
echo $student_result['test2']; } else {
echo '<input type="text" name="test2[]" class="form-control" style="text-align: center" value="">';
}
?>
</td>
<td style="width: 15%; text-align: center">
<?php
if ($student_result['test3'] !== ' ') {
echo $student_result['test3']; } else {
echo '<input type="text" name="test3[]" class="form-control" style="text-align: center" value="">';
}
?>
</td>
<td style="width: 15%; text-align: center"><?php echo htmlentities($student_result['total']); ?></td>
</tr>
<?php
}
}
?>
What happen if you try this code instead:
function find_student_by_year($year) {
global $connection;
$query = "select * from students where entry_year = '$year' order by
s_fname asc";
$found_students = mysqli_query($connection, $query);
confirm_query($found_students);
return $found_students;
}

Why is that My PHP records not being INSERTED

Good Day!
Guys can you help me to check why my is it that i cannot insert records using chekbox option on table..
Please Help..
Here's My Code...
--ADDING Subject Load for Teacher HTML Form-- (studsub.php)
<form action="setsubject.php" method="post">
<?php
include('../connect.php');
$id=$_GET['id'];
$result = mysql_query("SELECT * FROM student WHERE id='$id'");
while($row = mysql_fetch_array($result))
{
//$course=$row['course'];
//$year=$row['yearlevel'];
//$section=$row['section'];
$idnumber=$row['idnumber'];
echo '<br/>';
echo $row['lname'].", ".$row['fname'];
?>
<input type="hidden" name="studidnum" value="<?php echo $rows['idnumber']?>">
<?php }
?>
<br/><br/>
<label for="filter">Filter</label> <input type="text" name="filter" value="" id="filter" />
<table cellpadding="1" cellspacing="1" id="resultTable">
<thead>
<tr>
<th style="border-left: 1px solid #C1DAD7"><label>Assign</label></th>
<th style="border-left: 1px solid #C1DAD7"> Subject ID </th>
<th>Title</th>
<th>Units</th>
</tr>
</thead>
<tbody>
<?php
include('../connect.php');
$result = mysql_query("SELECT * FROM tbl_cur_sub where status='1' ");
while($row = mysql_fetch_array($result))
{
echo '<tr class="record">';
echo ' <td>' . '<input type="checkbox" name="subject[]" value="'.$rows['code'].'" />' . '</td> ' ;
echo '<td style="border-left: 1px solid #C1DAD7">'.$row['code'].'</td>';
echo '<td><div align="left">'.$row['subject'].'</div></td>';
echo '<td><div align="left">'.$row['units'].'</div></td>';
echo '</tr>';
}
?>
</tbody>
</table>
<br/>
Course<br>
<select name="course" class="ed">
<?php
include('../connect.php');
$results = mysql_query("SELECT * FROM course");
while($rows = mysql_fetch_array($results))
{
echo '<option>'.$rows['coursecode'].'</option>';
}
?>
</select>
<select name="yearlevel" class="ed">
<?php
include('../connect.php');
$results = mysql_query("SELECT * FROM tbl_yrlevel");
while($rows = mysql_fetch_array($results))
{
echo '<option>'.$rows['yearlevel'].'</option>';
}
?>
</select>
<select name="section" class="ed">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
<br>
<br>
<input type="submit" value="Assign" id="button1">
</form>
--The Submission Page -- (setsubject.php)
<?php
include('../connect.php');
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$course = clean($_POST['course']);
$section = clean($_POST['section']);
$yearlevel = clean($_POST['yearlevel']);
$studidnum=$_POST['studidnum'];
$subject=$_POST['subject'];
$N = count($subject);
for($i=0; $i < $N; $i++)
{
mysql_query("INSERT INTO studentsubject (student, subject, section, course, level) VALUES ('$studidnum', '$subject[$i]','$section','$course', '$level')");
}
header("location: student.php");
mysql_close($con);
?>
--My Database--
TABLE: studentsubject
FIELDS: student, subject, section, course, level
Thanks IN advance for the Help..
TRY
mysql_query("SELECT * FROM tbl_cur_sub where status=1 ");
change the mysql statement...you need to differ the variable and string in the query
$result = mysql_query("SELECT * FROM student WHERE id='".$id."'");

My PHP Form will not refresh properly

So when I hit submit on the form that is displayed, the page (if working properly) should refresh, and the ELSE statement should be displayed instead, but I have 2 problems
The else statement is not displayed until I manually refresh the page
The Pub Score is not updated until the page is manually refreshed either, I think my code placement might be what's causing it, but I tried to put my form as far down as I could, I'm out of ideas, any help would be great thanks.
<?php
require_once('header.php');
require_once('connectdb.php');
require_once('sessioncheck.php');
if (isset($_SESSION['user_id'])) {
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_DATA);
$user_name = mysqli_real_escape_string($dbc, trim($_GET['username']));
$query = "SELECT * FROM blah WHERE username = '$user_name'";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
if (mysqli_num_rows($data) != 0) {
if ($row['havemic'] == 1) {
$micstatus = "Yes";
} else {
$micstatus = "No";
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title><?php echo $user_name . ' profile' ?></title>
</head>
<body>
<?php
$commenduser = $user_name;
$query = "SELECT * FROM blah where commenduser = '$commenduser'";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
$lowerusername = strtolower($username);
$loweruser_name = strtolower($user_name);
if (mysqli_num_rows($data) == 0) {
if (isset($_POST['submit'])) {
$commendplayer = mysqli_real_escape_string($dbc, trim($_POST['commendplayer']));
$commend = mysqli_real_escape_string($dbc, trim($_POST['commend']));
$comment = mysqli_real_escape_string($dbc, trim($_POST['comment']));
if (empty($comment)) {
echo '<p class="error">Please fillout a comment before submitting</p>';
} else {
$query = "INSERT INTO commend (commendby, commenduser, comment) VALUES ('$username', '$user_name', '$comment')";
mysqli_query($dbc, $query);
if ($commend == true) {
$query = "UPDATE blah SET points=points+1 WHERE username='$user_name'";
mysqli_query($dbc, $query);
echo '<p class="success">Your commendation has been submitted with + 1 account points.</p>';
} else {
echo '<p class="success">Your commendation has been submitted with no affect on the users account points.</p>';
}
}
}
} else {
echo '<p class="success">You have already submitted a commendation for this player.</p>';
}
?>
<div id="accsettings">
<table cellpadding="5">
<tr><td><label for="username" class="reglabel">Username: </label></td>
<td><label for="username" class="reglabel"><?php echo $row['username']; ?></label></td></tr>
<tr><td><label class="reglabel">Pub Score: </label></td><td><label class="reglabel">
/*This value 'points' should be updated to the new value after form submit */
/*As well the ELSE statement near the bottom should be displayed*/
<?php echo $row['points'] ?></label></td></tr>
<tr><td><label for="steamname" class="reglabel">Steam Name: </label></td>
<td><label for="steamname" id="acclink"><?php echo '' . $row['steamname'] . ''; ?></label>
<tr><td><label for="favchar" class="reglabel">Prefered Hero: </label></td>
<td><label for="favchar" class="reglabel"><?php echo $row['favchar']; ?></label></td></tr>
<tr><td><label for="language" class="reglabel">Spoken Language: </label></td>
<td><label for="language" class="reglabel"><?php echo $row['language']; ?></label></td></tr>
<tr><td><label for="playernote" class="reglabel">Player Note: </label></td>
<td><label for="playernote" class="reglabel"><?php echo $row['note']; ?></label></td></tr>
<tr><td><label for="micstatus" class="reglabel">Has a Mic and VO-IP?</label></td>
<td><label for="micstatus" class="reglabel"><?php echo $micstatus; ?></label></td></tr>
<tr><td colspan="2">Players Comments</td></tr>
<?php
if ($row['commendby'] != $username && $lowerusername != $loweruser_name) {
?>
<tr><td><br></td></tr>
<tr><td colspan="2"><p class="success">Player Commendations/Comments</p></td></tr>
<tr><td><br></td></tr>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] . '?username=' . $user_name; ?>">
<tr><td><label for="comment">Leave a comment</label></td>
<td><input type="text" name="comment" class="regtext" /></td></td>
<tr><td colspan="2"><label for="commend" class="right">Commend Player?</label><input type="checkbox" class="right" name="commend" value="yes" /></td></tr>
<tr><td colspan="2"><input id ="submit" type="submit" class="button1" name="submit" value="Submit" /></td></tr>
</form>
<?php
} else {
/*This is what should be being displayed after the form is submitted. But it is not.*/
$query = "SELECT * FROM blah where commenduser = '$commenduser'";
$data = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($data)) {
echo '<tr><td><br></td></tr>';
echo '<tr><td><br></td></tr>';
echo '<tr><td><label class="reglabel" for="commendedbyy">Comment From: ' . $row['commendby'] . '</label></td>';
echo '<td><label class="reglabel">' . $row['comment'];
echo '<input type="hidden" name="submit" />';
echo '</form>';
}
}
?>
</table>
<?php
} else {
echo '<p class="error">' . $user_name . ' is not a registered account.</p>';
}
}
else {
echo '<p class="error">You must Log In to view this profile.</p>';
}
?>
</div>
</body>
</html>
<?php
require_once('footer.php');
?>
The $row is first grabbed from the database and then the database is updated.
You can do one of three things, the last being the simplest:
You can refactor the code to change the order
Reload the data using another query after the update
Once you update the points then update the array (i.e. do $row['points'] = $row['points'] + 1;)

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