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);
Related
The context is: e-commerce, the problem stands in adding items to the cart.
I created a while loop to iterate through each item my query returns and each item has a button that redirects to a "info on the item" page. My problem is that since there's a loop, the values to submit (e.g. the ID of the item) is overloaded and every button submits the values of the last item.
I can pass all the IDs of all the plants but i have no idea how to, in the "item detail" page, to show the correct item among the array.
lista-piante.php: (summarized)
<?php session_start();
// connect to the database
$connessione = new mysqli('localhost', 'root', 'root', 'mio');
//query
$user_check_query = "SELECT Pianta.NOME as nome, PIANTA.ID as pid, Item.PREZZO as prezzo, Item.ID as id
FROM Item, Pianta WHERE Pianta.ID = Item.PIANTA";
$result = mysqli_query($connessione, $user_check_query);
if($result->num_rows > 0) {
echo"<h3>Lista delle nostre piante</h3>";
echo"<ul class=\"plant-flex\">";
// loop through records
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo"<form method='get' action='../html/details-pianta.php'>";
echo"<li>";
echo"<div class='plant-preview'>";
echo"<div class='plant-preview-description'>";
//dichiarazione variabili (per leggibilità)
$nome= $row['nome'];
$pid = $row['pid'];
// PRINT NAME
echo"<div class='plant-preview-description-name'>";
echo "<p class='bold'>" . $nome . "</p>";
echo "<input type='hidden' name='name' value='$nome' />";
echo"</div>";
echo "<input type='hidden' name='pid[]' value='$pid' />";
echo"<div>";
echo"<button type=\"submit\" class=\"btn\" name=\"details_plant\">Dettagli" . $item . "</button>";
echo"</div>";
echo"</li>";
echo"<form/>";
}
$result->free();
}
echo "<ul/>";
$connessione->close();
details-pianta.php: (summarized, it will contain the style of the page)
<?php session_start();?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="it" lang="it">
<head> <!-- meta tag and other stuff --> </head>
<body>
<div>
<?PHP include('../php/dettagli-pianta.php'); ?>
</div>
</div>
</body>
</html>
dettagli-pianta.php: (summarized, it should contain the info of each item)
<?php
session_start();
// connect to the database
$connessione = new mysqli('localhost', 'root', 'root', 'mio');
$pid = mysqli_real_escape_string($connessione, $_GET['pid']);
//but pID is either the last item's id, or an array with all items' ids, so i can't chose the only one i want
//the URL shows always more pIDs (from the lista-piante.php get form)
$user_check_query = "SELECT * FROM Pianta, item WHERE Pianta.ID = '$pid' ";
$result = mysqli_query($connessione, $user_check_query);
if($result->num_rows > 0) {
echo"<h3>Dettagli della pianta</h3>";
echo"<ul>";
//loop thought query records
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo"<form method='post' action='../php/add-carrello.php'>";
echo"<li>";
echo"<div>";
//dichiarazione variabili (per leggibilità)
$nome =$row['NOME'];
//$genere= $row['GENERE'];
//$specie= $row['SPECIE'];
//etc etc
// PRINT NAME
echo"<div>";
echo "<p class='bold'>" . $nome . "</p>";
echo"</div>";
//echo"<div>";
//echo "<p class='bold'>" . $specie. "</p>";
//echo"</div>";
//echo "<input type='hidden' name='pid' value='$pid' />";
echo"<div>";
echo"<button type=\"submit\" class=\"btn\" name=\"add-carrello\"> Aggiungi al carrello</button>";
echo"</div>";
echo"</li>";
}
$result->free();
}
echo "<ul/>";
$connessione->close();
There is an error with form closing, but... I have a feeling you are complicating it for yourself by using all those forms/buttons.
I would clean up the code and get rid of the form/button scheme altogether, and use simple a href links with ?id=$pid
Something like this (shortened, if needed post a comment and I can expand):
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo "<li>";
echo "<div class='plant-preview'>";
echo "<div class='plant-preview-description'>";
//dichiarazione variabili (per leggibilità)
$nome = $row['nome'];
$pid = $row['pid'];
// PRINT NAME
echo "<div class='plant-preview-description-name'>";
echo "<p class='bold'>" . $nome . "</p>";
echo "</div>";
echo "<div>";
echo "<a href ='../html/details-pianta.php?pid=$pid'>Dettagli " . $nome . "</a>";
echo "</div>";
echo "</li>";
}
You can use CSS later to make your a-href link look like a button, add image, or play with it any way you like.
Then in the product details page (dettagli-pianta.php) use your product id pretty much same as you already do:
$pid = $_GET['pid']
...
$user_check_query = "SELECT * FROM Pianta WHERE Pianta.ID = '$pid' ";
Here is one Stack Overflow that talks about using link instead form:
How send parameter to a url without using form in php?
Edit (mistakes found, more suggestions, in case you still want to keep forms/buttons):
you did not close ?> in your examples, but ok, probably just copy/paste here
you have $item variable that isn't defined, and not pulled from SELECT query, so I can only assume that is supposed to be $nome (or you deleted something to make it shorter in question and forgot about it)
you also probably wanted a space like this (note space after Dettagli)
echo "<button type='submit' class='btn' name='details_plant'>Dettagli " . $nome . "</button>";
not sure why you keep files in folders "../html/" and "../php/" when both are with extensions .php, could be confusing for others later working on your code, or ... maybe it's just me
you have <?php session_start();?> then under it you include a file that also has <?php session_start();?> ... no need for one of them. Since "details-pianta.php" is in folder "html" I guess you can remove it from there, as you don't need session just to include another PHP file
in form you submit name='pid[]' when you should just use name='pid' (no brackets), like this:
echo "<input type='hidden' name='pid' value='$pid' />";
in "dettagli-pianta.php" you have a select like this: $user_check_query = "SELECT * FROM Pianta, item WHERE Pianta.ID = '$pid' "; where you name two tables but don't join them, and I can only assume it should be $user_check_query = "SELECT * FROM Pianta WHERE Pianta.ID = '$pid' ";
be careful of uppercase/lowercase in database and column names, try to standardize
in one line you echo with mixed quotes something like echo "<bla name='bla'>" and in next you escape quotes like echo "<bla name=\"bla\">" ... make it easy on yourself and - standardize. Unless absolutely necessary, first way (mixing single and double quotes) is preferable, and only when you have something really complicated to echo like mix of HTML+JavaScript, then resort to escaping quotes
And finally, but actually a direct answer to your issue - you closed your form in the wrong way (yeah, had to look real hard to see it):
echo"<form/>";
You need to have (space is optional, reads better):
echo "</form>";
Non the less, as others too have already commented, using forms just to get buttons is an overkill. Try using simple links (<a href> elements) and style them with CSS to your liking, making them look like buttons...
And last, but... I believe it to be important... Try not to mix Italian and English in code (including database structure). It is obvious you are just learning but havin database called "mio" with table "pianti" and column "prezzo" ... then use something like "item". Also, names of files like "details-pianta", then you have another file "detaggli_pianta", and in button name you use "details_plant", it is huge mashup of two languages. you seem to be fluent English speaker judging from your question, so - why not use English everywhere in code? Name your database "my_first_web_store", name your table "plants", name your column "price", name your PHP files "plant_details" (or details_plant, whatever), use comments in English in your code (nobody but you and other developers see that). You will be thankful later when your plant-selling company expands worldwide, and when you will have multi-language webshop, and maybe 3 more developers working from India and US, all working on same project... :)
Have fun learning!
This is my first php project. I have created a website where users can upload their picture and then view the pictures of other users, one person at a time (similar to the old hotornot.com). The code below works as follows:
I create an array (called $allusers) containing all members except for the user who is currently logged in ($user).
I create an array (called $usersiviewed) of all members who $user has previously either liked (stored in the likeprofile table) or disliked (stored in the dislikeprofile table). The first column of likeprofile and dislikeprofile has the name of users who did the liking/disliking, second column contains the name of the member they liked/disliked.
I use the array_diff to strip out $usersiviewed from $allusers. This is the list of users who $user can view (ie, people they have not already liked or disliked in the past).
Now the problem is when I click the like button, it updates the likeprofile table with the name of the NEXT person in the array (i.e., not the person who's picture I am currently looking at but person who's picture appears next). Additionally, if I refresh the current page, the person who's profile appears on the current page automatically gets 'liked' by me. I would really appreciate any advice on this.
<?php
// viewprofiles.php
include_once("header.php");
echo $user.' is currently logged in<br><br>';
echo <<<_END
<form method="post" action="viewprofiles.php"><pre>
<input type="submit" name ="choice" value="LIKE" />
<input type="submit" name ="choice" value="NEXT PROFILE" />
</pre></form>
_END;
$allusers = array();
//Create the $allusers array, comprised of all users except me
$result = queryMysql("SELECT * FROM members");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;
$allusers[$j] = $row[0];
}
//Create the $i_like_these_users array, comprised of all users i liked
$result = queryMysql("SELECT * FROM likeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_like_these_users[$j] = $row[1];
}
//Create the $i_dislike_these_users array, comprised of all users i disliked
$result = queryMysql("SELECT * FROM dislikeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_dislike_these_users[$j] = $row[1];
}
//Create the $usersiviewed array, comprised of all users i have either liked or disliked
if (is_array($i_like_these_users) && is_array($i_dislike_these_users))
{
$usersiviewed = array_merge($i_like_these_users,$i_dislike_these_users);
}
elseif(is_array($i_like_these_users))
{
$usersiviewed = $i_like_these_users;
}
else
{
$usersiviewed = $i_dislike_these_users;
}
// this removes from the array $allusers (i.e., profiles i can view) all $usersviewed (i.e., all the profiles i have already either liked/disliked)
if (is_array($usersiviewed))
{
$peopleicanview = array_diff($allusers, $usersiviewed);
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
else {
$peopleicanview = $allusers;
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
$current_user_profile = $peopleicanview[0];
echo 'check out '.$current_user_profile.'s picture <br />';
if (file_exists("$current_user_profile.jpg"))
{echo "<img src='$current_user_profile.jpg' align='left' />";}
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['choice']) && $_POST['choice'] == 'LIKE')
{
$ilike = $current_user_profile;
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$ilike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['choice']) && $_POST['choice'] == 'NEXT PROFILE')
{
$idontlike = $current_user_profile;
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$idontlike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
?>
Because when you refresh page it sends previus value of
Form again...and problem when u like a user it being liked next user.. There there is something in yor for loop while fetching row ...insted of for loop try once while loop ...i hope it will solve ur problem
You are calculating the $iLike variable with the currently loaded user and then updating the database with that user.
You should probably change your application logic a bit:
pass the user ID of the user you liked or did not like as a POST parameter in addition to the like/didn't like variable
move the form processing logic to the top of your page (or better yet separate out your form processing from HTML display)
Also, it's best not to use the mysql_* extensions in PHP. Use mysqli or PDO.
Try to make two different forms. One with "LIKE", another with "NEXT" to avoid liking from the same form
When you submit your form - your page refreshes, so in string $current_user_profile = $peopleicanview[0]; array $peopleicanview doesn't have user from previuos page (before submitting) you have to attach it, e.g. in hidden field
<form method="post" action="viewprofiles.php">
<input type="hidden" name="current_user" value="$current_user_profile" />
<input type="submit" name ="choice" value="like" />
</form>
<form method="post" action="viewprofiles.php">
<input type="submit" name ="go" value="next" />
</form>
and INSERT it later
"INSERT INTO likeprofile VALUES" . "('$user', '".$_POST['current_user']."')"
ps remove <pre> from your form
Lets start by simplifying and organizing the code.
<?php
// viewprofiles.php
include_once("header.php");
//if form is sent, process the vote.
//Do this first so that the user voted on wont be in results later(view same user again)
//use the user from hidden form field, see below
$userToVoteOn = isset($_POST['user-to-vote-on']) ? $_POST['user-to-vote-on'] : '';
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['like']))
{
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['dislike']))
{
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
//now we can create array of available users.
$currentProfileUser = array();
//Create the $currentProfileUser array,contains data for next user.
//join the 2 other tables here to save php processing later.
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
and `user` <> '$user'
LIMIT 1");
//no need for a counter or loop, you only need the first result.
if(mysql_num_rows > 0)
{
$row = mysql_fetch_assoc($result);
$current_user_profile = $row['user'];
}
else
$current_user_profile = false;
echo $user.' is currently logged in<br><br>';
//make sure you have a user
if($current_user_profile !== false): ?>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="like" value="LIKE" />
</form>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="dislike" value="NEXT PROFILE" />
</form>
check out <?=$current_user_profile?>'s picture <br />
<?php if (file_exists("$current_user_profile.jpg")): ?>
<img src='<?=$current_user_profile.jpg?>' align='left' />
<?php endif; //end check if image exists ?>
<?php else: //no users found ?>
Sorry, there are no new users to view
<?php endif; //end check if users exists. ?>
You'll notice I changed the code a lot. The order you were checking the vote was the main reason for the issue. But over complicating the code makes it very difficult to see what's happening and why. Make an effort to organize your code in the order you expect them to run rather a vote is cast or not, I also made an effort to separate the markup from the logic. This makes for less of a mess of code to dig through when looking for the bug.
I also used sub queries in the original query to avoid a bunch of unnecessary php code. You could easily have used JOIN with the same outcome, but I think this is a clearer representation of what's happening. Also please use mysqli instead of the deprecaded mysql in the future, and be aware of SQL injection attacks and makes use of real_escape_string at the very least.
Hope it works out for you. Also I didn't test this code. Might be a few errors.
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>
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.