So I have a page with a postback form where users can delete records (which appear as checkboxes) from a database. When you click 'Submit', on the same page a confirmation message is displayed "Successfully deleted the record".
The problem is that the checkbox remains there. Only after you refresh the page, the checkbox disappears. How can I remove it right after the user clicks "Submit"?
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<?php
//Connect to the database
require_once("dboconn.php");
$conn=ConnectionFactory::connect();
$query = "SELECT * FROM programmer";
$resultset = $conn->query($query);
while ($row = $resultset->fetch())
{
echo "<p class='col'>";
echo "<input type='checkbox' name='programmers[]' id='programmer".$row['programmer_id']."' value='".$row['programmer_id']."'>";
echo "<a href='' class='help tip-below' data-tip='".projects($row['programmer_id'])."'><label for='programmer".$row['programmer_id']."'> ".$row['programmer_name']." ".$row['programmer_surname']."</label></a>";
echo "</p>";
}?>
<input type="submit" value="Delete Programmer(s)" class="sub-del submit-btn">
</form>
<?php
if (isset($_POST['programmers'])){
require_once("dboconn.php");
$conn=ConnectionFactory::connect();
$query="DELETE FROM programmer WHERE programmer_id=:programmer_id";
$query2="DELETE FROM project WHERE programmer_id=:programmer_id";
$query3="SELECT programmer_name, programmer_surname FROM programmer WHERE programmer_id=:programmer_id";
$pr_stmt=$conn->prepare($query);
$pr_stmt2=$conn->prepare($query2);
$pr_stmt3=$conn->prepare($query3);
$affected_rows=0;
$notWorking=false; // set this variable to check if a programmer is working or not on any project
$surnameDeletedProgs=array();
$nameDeletedProgs=array();
foreach($_POST['programmers'] as $programmer_id){
$pr_stmt->bindValue(':programmer_id',$programmer_id);
$pr_stmt2->bindValue(':programmer_id',$programmer_id);
$pr_stmt3->bindValue(':programmer_id',$programmer_id);
$pr_stmt3->execute();
//Get the names and surnames of the programmers who were deleted from the database and store them in arrays
$result=$pr_stmt3->fetch();
array_push($nameDeletedProgs,$result['programmer_name']);
array_push($surnameDeletedProgs,$result['programmer_surname']);
//Delete the programmer from the database
$affected_rows+=$pr_stmt->execute();
//If they were working on a project, delete the project also from the 'project' table
if(projects($programmer_id)!="Working on no projects at the moment"){
$pr_stmt2->execute();
echo "Also deleted the project they were working on";
}
else $notWorking=true;
}
//If they are not working on any project display this particular message
if ($notWorking){
echo "Hopefully, they were not working on any project at the moment so we just ";
}
//if there were no checkboxes selectes, display a message to tell people to select at least one programmer
if ($affected_rows==0){
echo "No programmers to delete. Please select at least one.";
exit;
}
//display how many programmers were deleted from the 'programmers' table and also what are their names
else{
echo "deleted ".$affected_rows." programmer(s)";
echo ". Successfully deleted:<ul>";
for($i=0;$i<count($nameDeletedProgs);$i++){
echo "<li>".$nameDeletedProgs[$i]." ".$surnameDeletedProgs[$i]."</li>";
}
echo "</ul>";
}
$conn=NULL;
}
Thanks a lot for your help!
Raluca
Currently, when you hit submit, you build the HTML output with the old data, then update the database. You need to first update the database and then get the data to build the UI. Your updated code should look like this:
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<?php
//Connect to the database
require_once("dboconn.php");
$conn=ConnectionFactory::connect();
if (isset($_POST['programmers'])){
require_once("dboconn.php");
$conn=ConnectionFactory::connect();
$query="DELETE FROM programmer WHERE programmer_id=:programmer_id";
$query2="DELETE FROM project WHERE programmer_id=:programmer_id";
$query3="SELECT programmer_name, programmer_surname FROM programmer WHERE programmer_id=:programmer_id";
$pr_stmt=$conn->prepare($query);
$pr_stmt2=$conn->prepare($query2);
$pr_stmt3=$conn->prepare($query3);
$affected_rows=0;
$notWorking=false; // set this variable to check if a programmer is working or not on any project
$surnameDeletedProgs=array();
$nameDeletedProgs=array();
foreach($_POST['programmers'] as $programmer_id){
$pr_stmt->bindValue(':programmer_id',$programmer_id);
$pr_stmt2->bindValue(':programmer_id',$programmer_id);
$pr_stmt3->bindValue(':programmer_id',$programmer_id);
$pr_stmt3->execute();
//Get the names and surnames of the programmers who were deleted from the database and store them in arrays
$result=$pr_stmt3->fetch();
array_push($nameDeletedProgs,$result['programmer_name']);
array_push($surnameDeletedProgs,$result['programmer_surname']);
//Delete the programmer from the database
$affected_rows+=$pr_stmt->execute();
//If they were working on a project, delete the project also from the 'project' table
if(projects($programmer_id)!="Working on no projects at the moment"){
$pr_stmt2->execute();
echo "Also deleted the project they were working on";
}
else $notWorking=true;
}
//If they are not working on any project display this particular message
if ($notWorking){
echo "Hopefully, they were not working on any project at the moment so we just ";
}
//if there were no checkboxes selectes, display a message to tell people to select at least one programmer
if ($affected_rows==0){
echo "No programmers to delete. Please select at least one.";
exit;
}
//display how many programmers were deleted from the 'programmers' table and also what are their names
else{
echo "deleted ".$affected_rows." programmer(s)";
echo ". Successfully deleted:<ul>";
for($i=0;$i<count($nameDeletedProgs);$i++){
echo "<li>".$nameDeletedProgs[$i]." ".$surnameDeletedProgs[$i]."</li>";
}
echo "</ul>";
}
}
$query = "SELECT * FROM programmer";
$resultset = $conn->query($query);
while ($row = $resultset->fetch())
{
echo "<p class='col'>";
echo "<input type='checkbox' name='programmers[]' id='programmer".$row['programmer_id']."' value='".$row['programmer_id']."'>";
echo "<a href='' class='help tip-below' data-tip='".projects($row['programmer_id'])."'><label for='programmer".$row['programmer_id']."'> ".$row['programmer_name']." ".$row['programmer_surname']."</label></a>";
echo "</p>";
}
?>
<input type="submit" value="Delete Programmer(s)" class="sub-del submit-btn">
</form>
Related
I have a site where an admin can enter exam marks for papers which are part of an exam.
I am on the final part of actually giving a user their mark. But I just can't seem to do it.
So far what I have done is:
Allow the admin to view all of the exams, click on a specific exam and view the papers for that exam, then click on a paper and view all of the people who took that paper.
Then, click on a user and enter their marks and feedback. This is the part which I cannot do. I have pasted my code below along with what I am trying to do but it just is not working, any help would be great!
So, along with their mark and feedback I am also inserting into the marks table the, paperID and the examID.
CODE:
<?php
$epsID = $_GET['epsID'];
$sql = "SELECT * FROM ExamPaperStudent WHERE epsID = '$epsID'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$epID = $row ['epID'];
$sID = $row ['sID'];
echo "<p><form>";
echo "<b>Mark: <input type=text name=mark></b><br>";
echo "<b>Feedback: <input type=text name=feedback></b><br>";
echo $epID;
echo $sID;
echo "</form>";
echo "<a href='insertmark.php?epsID=". $row['epsID']."'>Add Data</a>";
}
?>
INSERTMARK.php code: (At this form I already know the exam/paper ID, which I also am trying to insert (along with marks/feedback).
CODE:
$mark = $_POST["mark"];
$feedback = $_POST["feedback"];
if(isset($_REQUEST['submit']))
{
$sql = mysql_query("insert INTO exammarks (mark, feedback, epID, atID) values ('$mark', '$feedback', '$epID', '$sID')");
$result = mysql_query($result);
}
epsID = exampaperstudent
epID = exampaper
sID = student
your form is wrong .
change this
echo "<p><form>";
to
echo "<p><form action='INSERTMARK.php' method='POST' name='myform'>";
OMG everything is wrong inside your inputs. i just give one and you correct the others
echo "<b>Mark: <input type='text' name='mark'></b><br>";
^----^------^----^---//use single quotes around here
didnt you miss submit button ?
how would i go about refreshing a page after i have submitted a form and done some php stuff with it. Heres my form and the php so far.
<form class="removeform"action='peteadd.php'method='post' enctype='multipart/form-
data' name='image_remove_form' >
<?php
include '../inc/connect.php';
$q = "SELECT * FROM gallerythumbs WHERE gallery = 1";
if($r = mysql_query($q)){
while($row=mysql_fetch_array($r)){
echo "<div class='thumb'>",
"<input type='checkbox' name='remove[{$row['id']}]'>",
"<label for='Remove'><span class='text'>Remove</span></label>",
"<br />",
"<img class='thumbnail' src='{$row['filename']}'
alt='{$row['description']}' />",
"</div>";
}
}
else{
echo mysql_error();
}
?>
<input type='submit' name='submit' value='Remove' />
</form>
</div>
<?php
include '../inc/connect.php';
//if delete was checked, delete entries from both tables
if(isset($_POST['remove'])){
$chk = (array) $_POST['remove'];
$p = implode(',',array_keys($chk));
$t = mysql_query("SELECT * FROM galleryimages WHERE id IN ($p)");
$r = mysql_query("SELECT * FROM gallerythumbs WHERE id IN ($p)");
$url=mysql_fetch_array($t);
$image=$url['filename'];
$url2=mysql_fetch_array($r);
$image2=$url2['filename'];
if ($t){
unlink($image);
unlink($image2);
$q = mysql_query("DELETE FROM galleryimages WHERE id IN ($p)");
$s = mysql_query("DELETE FROM gallerythumbs WHERE id IN ($p)");
}
else{
echo "<span class='text'>
There has been a problem, go back and try again.
<br />
<a href='peteadd.php'>Back</a>
</span>";
}
}
else{
echo "<span class='title'>
There are no images in the gallery
<br />
<a href='peteadd.php'>Add Images</a>
</span>";
}
?>
This for display some thumbnails that are saved in mysql with a remove checkbox above them. When I check them then submit the form the are deleted from the direcotries and the mysql tables ok, but how can I refresh the page so the deletion is obvious?
Thanks for looking
what you are describing sounds like you are displaying your page and within it you run some additional code - like deletion - so when you post your form you end up with images being pull from database and then removed
you should run your logic first and only then display page - that way you will be first deleting your records and then when it came to get data from database it will get right data (without records already deleted)
any other soultion will be nothing but hacky way to bypass problem that souldn't exist in the first place :)
You cannot directly refresh a page with PHP, but you can echo out a refresh tag like this
echo '<meta http-equiv="refresh" content="0">'
, or you can do it with javascript, like
location.reload(true);
I am facing problem deleting the correct files. I am displaying the list of files uploaded by the user sorted by the time of upload (last upload first). If there's a list of 3-4 files, no matter which file I click to delete, the first file in the list gets deleted, the file last uploaded that is. Here is my page displaying the files a particular user has uploaded.
<?php
$uid=$faculty_data['faculty_id']; //Assigns logged in id to a variable
$query="SELECT * FROM uploads ORDER BY datetime DESC"; //Sorts by date time
$result=mysql_query($query);
while($row=mysql_fetch_assoc($result))
{
if($uid==$row['faculty_id']) //Checks if the logged in id matches with id in DB
{
echo '<form action="delete.php" method="POST">';
echo "<strong>File: </strong>";
$url=$row['link'];
$new="http://tofsis.com/fileshare/".$url;
echo "<a href='$new'>$new</a><br/>";
echo "<strong>On: </strong>".$row['datetime'];
echo '<br><input type="submit" name="delete" class="btn btn" value="Delete File"/>';
echo '<hr>';
echo '</form>';
}
}
?>
And this is my delete page:
<?php
$uid=$faculty_data['faculty_id'];
$query="SELECT * FROM uploads ORDER BY datetime DESC";
$result=mysql_query($query);
if(isset($_POST['delete']))
{
while($row=mysql_fetch_assoc($result))
{
if($uid==$row['faculty_id'])
{
$url=$row['link'];
$new="http://tofsis.com/fileshare/".$url;
$query="DELETE FROM uploads WHERE link = '$url'";
$result=mysql_query($query);
unlink($url);
}
}
header('Location: my_uploads.php');
exit();
}
else {
echo '<script type="text/javascript">alert("Oops something went wrong!")</script>';
header('Location: my_uploads.php');
exit();
}
?>
Can anyone please tell me where I am going wrong so that I can get my problem fixed?
A couple of changes should be make:
<?php
$uid=$faculty_data['faculty_id']; //Assigns logged in id to a variable
$query="SELECT * FROM uploads ORDER BY datetime DESC"; //Sorts by date time
$result=mysql_query($query);
while($row=mysql_fetch_assoc($result))
{
if($uid==$row['faculty_id']) //Checks if the logged in id matches with id in DB
{
$file_id = $row['id'];
echo '<form action="delete.php" method="POST">';
echo "<strong>File: </strong>";
$url=$row['link'];
$new="http://tofsis.com/fileshare/".$url;
echo "<a href='$new'>$new</a><br/>";
echo "<input type='hidden' value='$url' id='file_path' name='file_path' />";
echo "<input type='hidden' value='$file_id' id='id_file' name='id_file' />"; // new line
echo "<strong>On: </strong>".$row['datetime'];
echo '<br><input type="submit" name="delete" class="btn btn" value="Delete File"/>';
echo '<hr>';
echo '</form>';
}
}
?>
On the delete page, this:
<?php
$file_id=$_POST['id_file'];
$file_path = $_POST['file_path'];
$query="DELETE FROM uploads WHERE id = $file_id";
$result=mysql_query($query);
unlink($file_path); //this should works on deleting the file
?>
That should do the trick ;)
Add another hidden input that stores the File ID and Get it in your delete script and use it
You create a separate POST form for each available file but none of this forms contain any information about what file they refer to. I guess that $_POST contains nothing but a delete key with Delete File as value.
In your delete page, you read data from a variable that does not exist:
$uid=$faculty_data['faculty_id']
... and then you retrieve all files from the database to compare their ID against $uid. I guess you are removing all rows when the ID is zero.
To do:
Enable full error reporting. That's something you need to fix before you go further; it's impossible to code without the aid of error messages. Here's a brief explanation.
Add a hidden field to the form with the corresponding ID.
Read form data from $_POST, not from an arbitrary variable.
Learn some basic SQL, such as the WHERE clause, so you can do something like:
DELETE FROM uploads
WHERE faculty_id=333
Learn about SQL injection. Use a library that provides prepared statements.
I creating a simple site with PHP where the users can submit blogs and other users (who are logged in) can post comments on them. I have made a link called "comments" below each blog that when clicked will show / hide all the comments relevant to the specific blog (also if the user is logged in, it will show a form field in which they can submit new comments). So basically each blog will have multiple comments. I have done two different codes for this but they both have the same problem that each comment appears twice (everything else works fine). Could anyone point out why?
mysql_select_db ("ooze");
$result = mysql_query ("select * from blog") or die(mysql_error());
$i = 1;
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>";
$i++;
$a = $row["ID"];
$result2 = mysql_query ("select * from blog, blogcomment where $a=blogID") or die(mysql_error());
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username]</p><p>said:</p> <p>$sub[comment]</p>";
}
if ( isset ($_SESSION["gatekeeper"]))
{
echo '<form method="post" name="result_'.$row["ID"].'" action="postcomment.php"><input name="ID" type = "hidden" value = "'.$row["ID"].'" /><input name="comment" id="comment" type="text" style="margin-left:20px;"/><input type="submit" value="Add comment" /></form>';
}
else
{
echo '<p class="third">Signup to post a comment</p>';
}
echo "</div>";
}
mysql_close($conn);
//second version of inner loop://
if ( isset ($_SESSION["gatekeeper"]))
{
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username] said:</p> <p>$sub[comment]</p>";
}
echo '<form method="post" name="result_'.$row["ID"].'" action="postcomment.php"><input name="ID" type = "hidden" value = "'.$row["ID"].'" /><input name="comment" id="comment" type="text" style="margin-left:20px;"/><input type="submit" value="Add comment" /></form>';
}
else
{
while($sub = mysql_fetch_array($result2))
{
echo "<p class='third' >$sub[commentdate] • $sub[username] said:</p> <p>$sub[comment]</p>";
}
echo '<p class="third">Signup to post a comment</p>';
}
echo "</div>";
}
mysql_close($conn);
Your problem lies in this query from the first example.
$result2 = mysql_query ("select * from blog, blogcomment where $a=blogID")
You have already queried the blog table so there is no need to query it again. Simply changing this to
$result2 = mysql_query ("select * from blogcomment where $a=blogID")
should solve the problem.
However there are many things you need to think about.
Why are you re-inventing the wheel? There are plenty of good blog applications out there. You'd be better off using one of them.
It's not recommended to use the mysql_ family of functions any more. Go away and learn mysqli_ or better still PDO.
You should learn about separation of concerns. At the very least you should make sure your data access/business logic is separate from your display logic. MVC is very common in PHP.
You should also learn about JOINs. Even in this simple inline script you have a query within a loop which is not very efficient. You can combine your queries into one (as you've tried with the inner query). The difference is the one query should be outside your main loop.
I am using PHP 5 to create a query page for a MySQL database with 2 tables "students" and "teachers". I have created a combo box which can allow users to view and select the 2 tables from the combo box via a "submit" button after selecting from the combo box.
However the problem with the script is that I want to verify if the "submit" button works which I created a "echo.php" to echo out the value of the combo box and submit button. Overall the idea is to do a query like these steps:
1) User selects value from combo box "teacher" or "student".
2) User clicks submit button.
3) After clicking submit button, user is redirected to "echo.php"
4) "echo.php" should output/echo out either "teacher" or "student".
The codes for script:
<?php
include "db_connect.php";
{
?>
<td valign=top><strong>Name:</strong></td>
<td>
<?php
echo "<form name = \"queryEquipTypeForm\" method = \"post\" action
=\"select_table.php\">";
echo '<select name=\"table\">';
echo "<option size =30 selected>Select</option>";
$result = mysql_query("show tables");
if(!$result) trigger_error("Query Failed: ". mysql_error($db), E_USER_ERROR);
if(mysql_num_rows($result))
{
while($table_array = mysql_fetch_array($result))
{
echo "<option>$table_array[0]</option>";
}
echo '</select>';
echo '</form>';
if(!$_POST['submit'])
{
?>
<form method="post" action="select_table.php">
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
else
{
echo '<script type="text/javascript">
alert("Redirecting you to echo.php page");
window.location="echo.php"</script>';
}
}
else
{
echo "<option>No Names Present</option>";
}
}
?>
</td>
The codes for "echo.php" :
<?php
include "select_table.php";
echo "data is : ".$_POST['table'];
?>
The output of echo.php would be exactly the same as "select_table.php" with the cobo box and the "data is: " without the "teachers" or "student" word as its being redirected to echo.php.
I'm not quite sure what exactly what you want to do, but as michaeltwofish already pointed out, redirecting to another page using javascript will make you lose the post data. Also you seem to echo two <form> elements when the select_table.php is called without post data, one with only a submit button, while your first form is missing the button.
Normally, you would want your php script to either output the form with the combobox where the user can select the table, or, if there was post data (meaning that the user selected a value), the results of the selection, kinda like the following:
<?php
if(isset($_POST['table'])) {
print "Selected element: " . $_POST['table'];
} else {
echo '<form method="post" action="select_table.php">';
echo '<select name="table">';
// here should be your SQL query and the combobox options generation
echo '</select>';
echo '<input type="submit" />';
echo '</form>';
}
?>
When the form is submitted, you redirect to echo.php, but that means you lose the POST data. You need to think carefully about the flow of your application, because what you have seems a bit confused.