I have three buttons on a page and I want to submit that form on the same page, depending to the button press, corresponding query will run. But there are some problem with the script.
<?php
$db = mysql_connect('localhost', 'root', '') or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db('easy_excel', $db) or die(mysql_error($db));
if ($_POST['submit'] =='delete_aabb')
{
$query ='DELETE FROM aabb';
mysql_query($query, $db) or die(mysql_error($db));
echo 'All Data from aabb Deleted succecfully!';
}
elseif ($_POST['submit'] =='delete_bbcc') {
$query ='DELETE FROM bbcc';
mysql_query($query, $db) or die(mysql_error($db));
echo 'All Data from bbcc Deleted succecfully!';
}
elseif ($_POST['submit'] =='show_bbcc') {
$query = 'SELECT
name
FROM bbcc';
$result = mysql_query($query, $db) or die(mysql_error($db));
echo '<table border="1">';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
?>
<html>
<head>
<title>Say My Name</title>
</head>
<body>
<form action="#" method="post">
<table>
<tr>
<input type="submit" name="submit" value="delete_aabb" />
</tr>
<tr>
<input type="submit" name="submit" value="delete_bbcc" /></td>
</tr>
<tr>
<input type="submit" name="submit" value="show_bbcc" /></td>
</tr>
</table>
</form>
</body>
</html>
This script is not running. Please help me.
I advice you to use MySQLi instead of deprecated MySQL. And I think you're referring to the isset() function.
<html>
<head>
<title>Say My Name</title>
</head>
<body>
<?php
/* ESTABLISH CONNECTION USING MYSQLi */
$con=mysqli_connect("localhost","root","","easy_excel");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
if (isset($_POST['delete_aabb'])) /* IF DELETE_AABB IS CLICKED */
{
mysqli_query($con,"DELETE FROM aabb");
echo 'All Data from aabb Deleted succecfully!';
}
else if (isset($_POST['delete_bbcc'])) { /* IF DELETE_BBCC IS CLICKED */
mysqli_query($con,"DELETE FROM bbcc");
echo 'All Data from bbcc Deleted succecfully!';
}
else if (isset($_POST['show_bbcc'])) { /* IF SHOW_BBCC IS CLICKED */
$result=mysqli_query($con,"SELECT name FROM bbcc");
echo '<table border="1">';
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
?>
<form action="" method="POST">
<table>
<tr>
<input type="submit" name="submit" value="delete_aabb" name="delete_aabb"/>
</tr>
<tr>
<input type="submit" name="submit" value="delete_bbcc" name="delete_bbcc"/></td>
</tr>
<tr>
<input type="submit" name="submit" value="show_bbcc" name="show_bbcc"/></td>
</tr>
</table>
</form>
</body>
</html>
Related
I'm trying to develop a small "To Do List" application. The data for the app is stored in a database, and it needs to perform all CRUD operations. As it is right now, Select, Insert, and Delete work just fine. I'm stuck on updating though. The index.php page is shown below:
<?php
session_start();
require_once 'connect.php';
if (isset($_POST['DeleteTask'])) {
$sqldelete = "DELETE FROM Tasks WHERE dbTaskID = :bvTaskID";
$stmtdelete = $db->prepare($sqldelete);
$stmtdelete->bindValue(':bvTaskID', $_POST['taskID']);
$stmtdelete->execute();
echo "<div>Task successfully deleted</div>";
}
if (isset($_POST['theSubmit'])){
echo '<p>New task added</p>';
$formfield['ffTaskName'] = trim($_POST['taskName']);
$formfield['ffTaskDue'] = trim($_POST['taskDue']);
if(empty($formfield['ffTaskName'])){$errormsg .= "<p>Task field is empty.</p>";}
if(empty($formfield['ffTaskDue'])){$errormsg .= "<p>Deadline field is empty.</p>";}
if ($errormsg != "") {
echo "<div class='error'><p>Please fill out all fields before submitting.</p>";
echo $errormsg;
echo "</div>";
} else {
try {
$sqlinsert = 'INSERT INTO Tasks (dbTaskName, dbTaskDue, dbTaskDone)
VALUES (:bvTaskName, :bvTaskDue, :bvTaskDone)';
$stmtinsert = $db->prepare($sqlinsert);
$stmtinsert->bindValue(':bvTaskName', $formfield['ffTaskName']);
$stmtinsert->bindValue(':bvTaskDue', $formfield['ffTaskDue']);
$stmtinsert->bindValue(':bvTaskDone', 0);
$stmtinsert->execute();
echo "<div><p>There are no errors. Thank you.</p></div>";
} catch(PDOException $e){
echo 'ERROR!!!' .$e->getMessage();
exit();
}
}
}
$sqlselect = "SELECT * from Tasks";
$result = $db->prepare($sqlselect);
$result->execute();
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To Do Application</title>
</head>
<body>
<h1><u>To-Do List</u></h1>
<table border>
<tr>
<th>Task</th>
<th>Deadline</th>
<th>Status</th>
<th>Complete</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<?php
while ($row = $result->fetch()) {
if ($row['dbTaskDone'] == 0) {
$status = "Unfinished";
} else {
$status = "Finished";
}
echo '<tr><td>' . $row['dbTaskName']
. '</td><td>' . $row['dbTaskDue']
. '</td><td>' . $status;
/*if ($status == "Unfinished"){
echo '</td><td>';
echo '<form action="'. $_SERVER['PHP_SELF'] . '" method="post">';
echo '<input type="hidden" name="taskID" value"' . $row['dbTaskID'] . '">';
echo '<input type="submit" name="CompleteTask" value="Complete Task">';
echo '</form>';
}*/
echo '</td><td>';
echo '<form action="updateTask.php" method="post">';
echo '<input type="hidden" name="taskID" value="' . $row['dbTaskID'] . '">';
echo '<input type="submit" name="EditTask" id="EditTask" value="Edit Task">';
echo '</form></td><td>';
echo '<form action="'. $_SERVER['PHP_SELF'] . '" method="post">';
echo '<input type="hidden" name="taskID" value="' . $row['dbTaskID'] . '">';
echo '<input type="submit" name="DeleteTask" value="Delete Task">';
echo '</td></tr>';
}
?>
</table>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="toDoForm">
<fieldset><legend>New Task</legend>
<table>
<tr>
<th>Task</th>
<td><input type="text" name="taskName" id="taskName"
value="<?php echo $formfield['ffTaskName']; ?>"></td>
</tr><tr>
<th>Deadline</th>
<td><input type="text" name="taskDue" id="taskDue"
value="<?php echo $formfield['ffTaskDue']; ?>"></td>
</tr>
</table>
<input type="submit" name = "theSubmit" value="Add Task">
</fieldset>
</form>
</body>
</html>
Each record displays an "Edit" button that grabs the PK from the "Tasks" table and sends it to the updateTask.php page:
<?php
require_once 'connect.php';
$errormsg = "";
if (isset($_POST['EditTask']) ) {
$formfield['ffTaskID'] = $_POST['taskID'];
$sqlselect = "SELECT * FROM Tasks WHERE dbTaskId = :bvTaskID";
$result = $db->prepare($sqlselect);
$result->bindValue(':bvTaskID', $formfield['ffTaskID']);
$result->execute();
$row = $result->fetch();
if( isset($_POST['theEdit']) )
{
$formfield['ffTaskID'] = $_POST['taskID'];
$formfield['ffTaskName'] = trim($_POST['taskName']);
$formfield['ffTaskDue'] = trim($_POST['taskDue']);
if(empty($formfield['ffTaskName'])){$errormsg .= "<p>Task field is empty.</p>";}
if(empty($formfield['ffTaskDue'])){$errormsg .= "<p>Deadline field is empty.</p>";}
if ($errormsg != "") {
echo "<div class='error'><p>Please fill out all fields before submitting.</p>";
echo $errormsg;
echo "</div>";
} else {
try
{
$sqlUpdate = "UPDATE Tasks SET dbTaskName = :bvTaskName,
dbTaskDue = :bvTaskDue
WHERE dbTaskID = :bvTaskID";
$stmtUpdate = $db->prepare($sqlUpdate);
$stmtUpdate->bindvalue(':bvTaskName', $formfield['ffTaskName']);
$stmtUpdate->bindvalue(':bvTaskDue', $formfield['ffTaskDue']);
$stmtUpdate->bindvalue(':bvTaskID', $formfield['ffTaskID']);
$stmtUpdate->execute();
}
catch(PDOException $e)
{
echo 'ERROR!!!' .$e->getMessage();
exit();
}
}
}
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To Do Application</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="editForm">
<fieldset><legend>Edit Task</legend>
<table>
<tr>
<th>Task</th>
<td><input type="text" name="taskName" id="taskName"
value="<?php echo $row['dbTaskName'];?>" ></td>
</tr><tr>
<th>Deadline</th>
<td><input type="text" name="taskDue" id="taskDue"
value="<?php echo $row['dbTaskDue']; ?>"></td>
</tr>
<tr>
<th>Submit Changes</th>
<input type="hidden" name="taskID" value="<?php echo $_formfield['ffTaskID']; ?>">
<td><input type="submit" name="theEdit" value="Submit Changes">
</table>
</fieldset>
</form>
</body>
</html>
The Name and Deadline fields populate appropriately based on the PK value passed from the last page. However, whenever I press the "Submit Changes" button, the update doesn't seem to execute. The page just refreshes and I see the table data remains unchanged in the database.
Solved the problem!
There were several issues that I discovered.
1.) In updateTask.php, I had the second if-statement nested within the first one. So it was running the update query as the page loaded, with no change to the data. So the 'theEdit' button did nothing since since it required the previous if statement's condition to run.
2.) The formfield 'ffTaskID' at the bottom of the form on updateTask.php to be passed on the 'theEdit' button press was typed incorrectly.
$_formfield
..should have been..
$formfield
At this point, the update query functions properly.
3.) The issue with the 'Edit' buttons has been fixed. Though I honestly can't say for certain how it was fixed. It may have been linked with the first part of the problem. So when that was fixed, so was this.
Either way, all seems to be functioning as it should. Thanks again to everyone who commented and helped.
Using following code I have fetched Student ID and Student name from mysql table in html table. In third column which is Obtained Marks I am getting student marks through input box. Now I want to insert all three columns (Student ID, Student Name and Obtained Marks) in new table which is testrecord.
<html>
<body>
<?php
$connection = mysqli_connect ('localhost', 'admin', 'password', 'db');
if (!$connection) {
echo 'Not connected to server';
}
$select_db = mysqli_select_db($connection, 'db');
if (!$select_db) {
echo 'Not connected to database';
}
$SelectClass = $_POST ['selectclass'];
$sql= "SELECT * FROM students WHERE class = '$SelectClass'";
$query = mysqli_query($connection, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($connection));
}
mysqli_close($connection);
?>
<body>
<div class="container">
<form class="well form-horizontal" action="insert_marks.php" method="post">
<h1><strong>Please enter marks of each student for subject</strong></h1>
<form action="" method="post">
<table id = "result" class="data-table">
<caption class="title"></caption>
<thead>
<tr>
<th>Sr.No.</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Marks Obtained</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query)) {
$stu = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
echo '<tr>
<td>'.$no.'</td>
<td>'.$row['student_id'].'</td>
<input type="hidden" name="student_id" value='.$row['student_id'].'>
<td>'.$row['student_name'].'</td>
<input type="hidden" name="student_name" value='.$row['student_name'].'>
<td>
<div class="search-block clearfix">
<input name="obtmarks" placeholder="" type="number">
</div>
</td>
</tr>';
$total += $row['stu_id'];
$no++;
}
?>
</tbody>
</table>
<button type="submit" class="btn btn-warning" value="insert" align="right">Update<span class="glyphicon glyphicon-send"></span></button>
</form>
</div>
</body>
</html>
insert_marks.php:
<html>
<body>
<?php
$connection = mysqli_connect ('localhost', 'admin', 'password', 'db');
if (!$connection) {
echo 'Not connected to server';
}
$select_db = mysqli_select_db($connection, 'db');
if (!$select_db) {
echo 'Not connected to database';
}
//***********Form Submit Goes Here***********//
while
if($_POST) {
$student_id = $_POST['student_id'];
$student_name = $_POST['student_name'];
$student_marks = $_POST['obtmarks'];
$sql= "INSERT INTO testrecord (student_id,student_name,obtained_marks) VALUES ('$student_id','$student_name','$student_marks')";
if (mysqli_query($connection, $sql)) {
echo "Marks added successfully.";
echo "<br>";
echo "<br>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
mysqli_close($connection);
?>
</body>
</html>
There are 20 entries in table. After inserting marks for each student in text box, above coding inserts only last record in mysql table 'testrecord'. Can you please correct the insert_marks.php code.
Change on Html table tbody part:
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query)) {
$stu = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
echo '<tr>
<td>'.$no.'</td>
<td>'.$row['student_id'].'</td>
<input type="hidden" name="student_id[]" value='.$row['student_id'].'>
<td>'.$row['student_name'].'</td>
<input type="hidden" name="student_name[]" value='.$row['student_name'].'>
<td>
<div class="search-block clearfix">
<input name="obtmarks[]" placeholder="" type="number">
</div>
</td>
</tr>';
$total += $row['stu_id'];
$no++;
}
?>
</tbody>
in insert_marks.php change while part:
//***********Form Submit Goes Here***********//
while
if($_POST) {
$student_id = $_POST['student_id'];
$student_name = $_POST['student_name'];
$student_marks = $_POST['obtmarks'];
for($i = 0; $i < count($student_id); $i++){
$sql= "INSERT INTO testrecord (student_id,student_name,obtained_marks) VALUES ('$student_id[$i]','$student_name[$i]','$student_marks[$i]')";
if (mysqli_query($connection, $sql)) {
echo "Marks added successfully.";
echo "<br>";
echo "<br>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
}
Try this
<html>
<body>
<?php
$connection = mysqli_connect ('localhost', 'admin', 'password', 'db');
if (!$connection) {
echo 'Not connected to server';
}
$select_db = mysqli_select_db($connection, 'db');
if (!$select_db) {
echo 'Not connected to database';
}
$SelectClass = $_POST ['selectclass'];
$sql= "SELECT * FROM students WHERE class = '$SelectClass'";
$query = mysqli_query($connection, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($connection));
}
mysqli_close($connection);
?>
<body>
<div class="container">
<form class="well form-horizontal" action="insert_marks.php" method="post">
<h1><strong>Please enter marks of each student for subject</strong></h1>
<table id = "result" class="data-table">
<caption class="title"></caption>
<thead>
<tr>
<th>Sr.No.</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Marks Obtained</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query)) {
$stu = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
echo '<tr>
<td>'.$no.'</td>
<td>'.$row['student_id'].'</td>
<input type="hidden" name="student['.$no.'][student_id]" value='.$row['student_id'].'>
<td>'.$row['student_name'].'</td>
<input type="hidden" name="student['.$no.'][student_name]" value='.$row['student_name'].'>
<td>
<div class="search-block clearfix">
<input name="student['.$no.'][obtmarks]" placeholder="" type="number">
</div>
</td>
</tr>';
$total += $row['stu_id'];
$no++;
}
?>
</tbody>
</table>
<button type="submit" class="btn btn-warning" value="insert" align="right">Update<span class="glyphicon glyphicon-send"></span></button>
</form>
</div>
</body>
</html>
insert_marks.php:
<html>
<body>
<?php
$connection = mysqli_connect ('localhost', 'admin', 'password', 'db');
if (!$connection) {
echo 'Not connected to server';
}
$select_db = mysqli_select_db($connection, 'db');
if (!$select_db) {
echo 'Not connected to database';
}
//***********Form Submit Goes Here***********//
if(isset($_POST['student']) && !empty($_POST['student'])) {
$queryStr = '';
$cnt = count($_POST['student']);
foreach ($_POST['student'] as $key => $student) {
$queryStr .= "('".$student['student_id']."','".$student['student_name']."','".$student['obtmarks']."') ";
if (($key + 1) != $cnt) {
$queryStr .= " , ";
}
}
if ($queryStr != '') {
$sql= "INSERT INTO testrecord (student_id,student_name,obtained_marks) VALUES $queryStr";
if (mysqli_query($connection, $sql)) {
echo "Marks added successfully.";
echo "<br>";
echo "<br>";
}
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
}
mysqli_close($connection);
?>
</body>
</html>
My code is: (Edited after a suggestion from an answer)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SomuFinance - Personal Finance Manager</title>
<link rel="stylesheet" type="text/css" href="indexStyle.css">
<script src="scripts/jquery-3.1.0.min.js"></script>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div id="container">
<input type="submit" class="button" name="edit" value="Edit" />
<input type="button" class="button" name="delete" value="Delete" />
<input type="text" id="action" name="action">
<table id="listDB">
<tr>
<th>Select</th>
<th>ID</th>
<th>Category ID</th>
<th>Shop</th>
<th>Item</th>
<th>Quantity</th>
<th>Unit</th>
<th>Price Based On</th>
<th>MRP</th>
<th>Seller's Price</th>
<th>Last Updated On</th>
</tr>
<?php
$dbc = mysqli_connect('localhost','root','atlantis2016','itemDB')
or die("Error Connecting to Database");
if(isset($_POST['submit']))
{
echo "Action Set to ".$_POST['action'];
if($_POST['action']=='confirmDelete')
{
echo "Now Deleting!!";
foreach ($_POST['selected'] as $delete_id)
{
$query = "DELETE FROM grocery WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error querying database.');
}
}
}
$query1 = "SELECT DISTINCT category FROM grocery";
$result1 = mysqli_query($dbc, $query1)
or die("Error Querying Database");
while($row = mysqli_fetch_array($result1))
{
$category = $row['category'];
$query2 = "SELECT * FROM grocery WHERE category='$category' ORDER BY item ASC";
$result2 = mysqli_query($dbc, $query2)
or die("Error Querying Database");
echo '<tr>';
echo '<td class="catHead" colspan=11>'.$category.'</td>';
echo '</tr>';
$catCount=1;
while($inRow = mysqli_fetch_array($result2))
{
$id = $inRow['id'];
$shop = $inRow['shop'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
echo '<tr>';
echo '<td><input type="checkbox" value="' . $id . '" name="selected[]" /></td>';
echo '<td>'.$id.'</td>';
echo '<td>'.$catCount.'</td>';
echo '<td>'.$shop.'</td>';
echo '<td class="leftAligned">'.$item.'</td>';
echo '<td>'.$qnty.'</td>';
echo '<td>'.$unit.'</td>';
echo '<td>'.$price_based_on.'</td>';
echo '<td class="pri">₹'.$mrp.'</td>';
echo '<td class="pri">₹'.$sellers_price.'</td>';
echo '<td>'.$last_updated_on.'</td>';
echo '</tr>';
$catCount++;
}
}
mysqli_close($dbc);
?>
<input type="submit" value="Submit">
</table>
</div>
<div class="dialogBG">
<div id="deleteConfirmDialog" class="dialog">
<div class="closeDialog"></div>
<p>Sure you want to delete the selected Data?</p>
<input type="submit" id="confirmDelete" class="dialogButton" name="edit" value="Delete" />
<input type="button" class="dialogButton cancelButton" name="delete" value="Cancel" />
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(){
if($(this).val()=="Delete")
{
$(".dialogBG").fadeIn(200);
$("#deleteConfirmDialog").show(200);
$("#action").val('confirmDelete');
}
else if($(this).val()=="Edit")
{
}
});
$('#confirmDelete').click(function(){
$(".closeDialog").trigger("click");
});
$('#cancelDelete').click(function(){
});
$(".closeDialog").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
$(".cancelButton").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
$("form").submit(function(e){
alert("Form is being sumbitted!");
});
});
</script>
</body>
</html>
I want the elements for which the checkbox is selected, contained in the php array selected[], to be deleted from the database. Before deletion, I want a confirmation dialog box to open up, which will contain the "submit" button. This will cause the actual deletion. However, for some reason the above code doesn't work. I can't even be sure if the post is being submitted, as the line echo "Action Set to ".$_POST['action']; doesn't return any output. Please help.
I believe this entire section of code is not working (from manual testing).
if(isset($_POST['submit']))
{
echo "PHP Working here!";
echo "Action Set to ".$_POST['action'];
if($_POST['action']=='confirmDelete')
{
echo "Now Deleting!!";
foreach ($_POST['selected'] as $delete_id)
{
$query = "DELETE FROM grocery WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error querying database.');
}
}
}
Any ideas why?
you need to put these inputs inside a form and set an action. like below:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" role="form">
<input></input>
<input></input>
</form>
this will be your code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SomuFinance - Personal Finance Manager</title>
<link rel="stylesheet" type="text/css" href="indexStyle.css">
<script src="scripts/jquery-3.1.0.min.js"></script>
</head>
<body>
<div id="container">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" role="form">
<input type="submit" class="button" name="edit" value="Edit" />
<input type="button" class="button" name="delete" value="Delete" />
<input type="text" id="action" name="action">
<table id="listDB">
<tr>
<th>Select</th>
<th>ID</th>
<th>Category ID</th>
<th>Shop</th>
<th>Item</th>
<th>Quantity</th>
<th>Unit</th>
<th>Price Based On</th>
<th>MRP</th>
<th>Seller's Price</th>
<th>Last Updated On</th>
</tr>
<?php
$dbc = mysqli_connect('localhost','root','atlantis2016','itemDB')
or die("Error Connecting to Database");
if(isset($_POST['submit']))
{
echo "Action Set to ".$_POST['action'];
if($_POST['action']=='confirmDelete')
{
echo "Now Deleting!!";
foreach ($_POST['selected'] as $delete_id)
{
$query = "DELETE FROM grocery WHERE id = $delete_id";
mysqli_query($dbc, $query)
or die('Error querying database.');
}
}
}
$query1 = "SELECT DISTINCT category FROM grocery";
$result1 = mysqli_query($dbc, $query1)
or die("Error Querying Database");
while($row = mysqli_fetch_array($result1))
{
$category = $row['category'];
$query2 = "SELECT * FROM grocery WHERE category='$category' ORDER BY item ASC";
$result2 = mysqli_query($dbc, $query2)
or die("Error Querying Database");
echo '<tr>';
echo '<td class="catHead" colspan=11>'.$category.'</td>';
echo '</tr>';
$catCount=1;
while($inRow = mysqli_fetch_array($result2))
{
$id = $inRow['id'];
$shop = $inRow['shop'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
echo '<tr>';
echo '<td><input type="checkbox" value="' . $id . '" name="selected[]" /></td>';
echo '<td>'.$id.'</td>';
echo '<td>'.$catCount.'</td>';
echo '<td>'.$shop.'</td>';
echo '<td class="leftAligned">'.$item.'</td>';
echo '<td>'.$qnty.'</td>';
echo '<td>'.$unit.'</td>';
echo '<td>'.$price_based_on.'</td>';
echo '<td class="pri">₹'.$mrp.'</td>';
echo '<td class="pri">₹'.$sellers_price.'</td>';
echo '<td>'.$last_updated_on.'</td>';
echo '</tr>';
$catCount++;
}
}
mysqli_close($dbc);
?>
</table>
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(){
if($(this).val()=="Delete")
{
$(".dialogBG").fadeIn(200);
$("#deleteConfirmDialog").show(200);
$("#action").val('confirmDelete');
}
else if($(this).val()=="Edit")
{
}
});
$('#confirmDelete').click(function(){
$(".closeDialog").trigger("click");
});
$('#cancelDelete').click(function(){
});
$(".closeDialog").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
$(".cancelButton").click(function (e){
$(this).parent(".dialog").hide('200').parent(".dialogBG").fadeOut('200');
});
});
</script>
<div class="dialogBG">
<div id="deleteConfirmDialog" class="dialog">
<div class="closeDialog"></div>
<p>Sure you want to delete the selected Data?</p>
<input type="submit" id="confirmDelete" class="dialogButton" name="edit" value="Delete" />
<input type="button" class="dialogButton cancelButton" name="delete" value="Cancel" />
</div>
</div>
</body>
</html>
The solution was simple. if(isset($_POST['confirmDelete'])) needs to be there instead of if(isset($_POST['submit'])) in the problem section in the question as there is no button called "submit" in the entire form.
I want to create a select dropdownlist which retrieves data from a table "teamtable" and displays it on a page where the user enters his choice and the corresponding ID for the choice is submitted in other database "user" where the column is a foreign key.
Tables and their contents-
teamtable-
idTeam(INT)(PK) - 1,2,3
teamName(VARCHAR) - Team-1, Team-2, Team-3
user-
team(INT)(FK)
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var f=document.forms["reg"]["team"].value;
if ((f==null || f==""))
{
alert("All Field must be filled out");
return false;
}
}
</script>
<form name="reg" action="user_exec.php" onsubmit="return validateForm()" method="post">
<table width="274" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<td colspan="2">
<div align="center">
<?php
$remarks=$_GET['remarks'];
if ($remarks==null and $remarks=="")
{
echo 'Register a new user';
}
if ($remarks=='success')
{
echo 'Registration Success';
}
?>
</div></td>
</tr>
<tr>
<td><div align="right">Team:</div></td>
<td>
<?php
$mysqli_hostname = "localhost";
$mysqli_user = "root";
$mysqli_password = "my_pass";
$mysqli_database = "my_db";
$prefix = "";
$bd = mysqli_connect($mysqli_hostname, $mysqli_user, $mysqli_password) or die("Could not connect database");
mysqli_select_db($mysqli_database, $bd) or die("Could not select database");
$sql = "SELECT idTeam,teamName FROM teamtable ";
$result = mysqli_query($sql);
echo "<select name='team'>";
while ($row=mysqli_fetch_array($result))
{
echo "<option value='" . $row['idTeam'] ."'>" . $row['teamName'] ."</option>";
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td><div align="right"></div></td>
<td><input name="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</head>
</html>
<?php
include('connection.php');
$sql = "SELECT idTeam, teamName FROM team";
$result = $conn->query($sql);
echo "<select name='team'>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row['idTeam'] ."'>" . $row['teamName'] ."</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
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);