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.
Related
I have a problem that is giving me a headache. I'm fairly new to PHP and MySQL interacting, and coding in general (about 3 months since I first dived into it), so I'm still learning the ropes, so to speak.
The thing is, I have a page that receives data through $_POST from another. All is fine for well. The page receives the data, which is an ID number, and echoes the item's characteristics available in the database corresponding to that ID.
This part of the code works just fine.
$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
echo "Nome: "."<span style='color: red;'>".$row["nome"].
"</span>".
"<br>"."Preço: "."<span style='color: red;'>".
"R$".$row["preco"]."</span>"."<br><br>".$row["status"];
}
}
What I want, is to turn the values echoed into variables, so that I can set them as default value in another form and send that one to another page. Apparently, $row['nome'], for example, isn't available for re-use outside of the instance above.
<form method="post" action="?p=venda">
<input type="text" name="nome" value="<?php echo $row["nome"]; ?>">
<input type="text" name="preco" value="<?php echo $row["preco"]; ?>">
<input type="submit" name="change" value="Efetuar">
</form>
I know this code is prone to SQL injection, but I'm not looking into it right now. This will be a sort of offline program to help me with organizing some of my stuff, so, for now, I don't have to worry about security (not that I'll keep ignoring these issues).
Thanks in advance.
Assign $row to a variable and treat it as an array() outside the while loop.
$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$array = $row; // assign $row a variable.
echo "Nome: "."<span style='color: red;'>".$row["nome"].
"</span>".
"<br>"."Preço: "."<span style='color: red;'>".
"R$".$row["preco"]."</span>"."<br><br>".$row["status"];
}
}
// example
echo($array['nome']);
OK I'll tell you this, its actually unnecessary to sanitize every post. Its only necessary if your authenticated users are web users and there is a blank that they type code in.
In closed production environments, where your users are, you can safe guard the environment in several ways, but this is off topic here.
anyways, you have a DB chart that has a an Id column, the item name, and I am guessing stock or production status.
your display, I don't use spans, but I'll show you how I do it with tables.
So lets make your query for your colums: nome, preco, status
Here are the two methods, the first one is called looped result method which is mostly used for more than one row in the db table:
<?php
//load it in a variable and trim the outside spaces away if you are entering this from a blank form
$id=trim($_POST[id]);
///this should look familiar to you
$sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
///but I use the shorthand method here to get my results.
$result = $conn->query($sql);
///Now we loop and shift colum information into variables
/// in a incremental loop, the colums are numbered starting with 0
echo "<table align=center bgcolor=fff2e2 border=1>\n";
while ($data = $result->fetch_row()) {
////I print my table header, and start the data row, if I want it as several ids I will reset here too (which I will do here if you want to play with this)
echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
echo '<tr>';
for ($m=0; $m<$result->field_count; $m++) {
if ($m==0){
$nome='';
$nome=$data[$m];
echo '<td bgcolor="#ff0000">'.$nome.'</td>';
} else if ($m==1){
$preco='';
$preco=$data[$m];
echo '<td bgcolor="#ff0000">'.$preco.'</td>';
}else if ($m==2){
$status='';
$status=$data[$m];
echo '<td bgcolor="#ffffff">'.$status.'</td>';
}
}
//////now if I was building a query chart with submit to another I would put my form and my hidden inputs here before i close the table row with /tr, and my submit button would be my first cell value
echo "</tr>";
}
echo "</table>";
You could do the regular colum /row method since it is one ID, which would look like this I used the span format here so you can get the idea of how html is typically expressed in php:
$id=trim($_POST[id]);
$sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$nome=stripslashes($row['nome']);
$preco=stripslashes($row['preco']);
$status=stripslashes($row['status']);
echo 'Nome: <span style="color: red;">'.$nome.'</span><br>Preço: <span style="color: red;">'.$preco.'</span><br><br>'.$status;
///notice my quote usage above
here is my table example if I was going to list the whole db table in a scrollable list, and submit it to a file called detail.php
<?php
$sql = "SELECT nome, preco, status FROM produtos";
$result = $conn->query($sql);
echo "<table align=center bgcolor=e3fab5 ><td>";
echo '<div style="width: 500px; height: 450px; overflow: auto; border 5px dashed black; background color: #ccc;">';
echo "<table align=center bgcolor=fff2e2 border=1>\n";
while ($data = $result->fetch_row()) {
echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
echo '<tr>';
for ($m=0; $m<$result->field_count; $m++) {
if ($m==0){
$nome='';
$nome=$data[$m];
echo '<td bgcolor="#ff0000"><form action="detail.php" method="post"><input type="submit" name="id" value="'.$nome.'"></td>';
} else if ($m==1){
$preco='';
$preco=$data[$m];
echo '<td bgcolor="#ff0000">'.$preco.'<input type="hidden" name="preco" value="'.$preco.'"></td>';
}else if ($m==2){
$status='';
$status=$data[$m];
echo '<td bgcolor="#ffffff">'.$status.'<input type="hidden" name="status" value="'.$status.'"></td>';
}
}
echo "</form></tr>";
}
echo "</table>";
echo "</div></table>";
?>
I'm making a form that brings questions and answers from the database, i have several questions, but i want to answer one question on each page and then go to the next question. How can i make that possible? i need some tips.
My code for bringing the questions and answers looks like this:
echo "<form method='post'>";
$sql= "SELECT pid, qid, question_link FROM question ORDER BY qid ASC LIMIT 1";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$pid1= $row['pid'];
$qid1= $row['qid'];
echo $row['question_link']."<br>";
}
}
$sql1= "SELECT pid, qid, aid, answer, points FROM answer_det WHERE pid=$pid1 AND qid=$qid1";
$result1 = $mysqli->query($sql1);
if ($result1->num_rows > 0) {
while($row = $result1->fetch_array()) {
$answer= $row['answer'];
$aid= $row['aid'];
echo "<input type='radio' name='answers' value='".$answer."'/>".$answer."<br>";
}
}
echo "<input type='submit' value='Submit'></form>";
Should i make another PHP page that saves the data into the database and shows the next question? or is there any function that can make that?
depends on the case. If you want the user to stop on the way and maybe come back next time and finish it up, then DB is a good option. else you can use session to store their progress.
<?php
session_start();
if(isset($_POST['name'])){
//store answers in session
$new = (!empty($_SESSION['session_name']))? $_SESSION['session_name'].'|'.$_POST['name'] : $_POST['name'];
//split session into an array
$_SESSION['session_name'] = $new;
}
else if(isset($_POST['clear'])){
if(!empty($_SESSION['session_name'])){
unset($_SESSION['session_name']);
echo "cleared";
}
else
echo "Nothing to Clear";
}
if(!empty($_SESSION['session_name'])){
var_dump($_SESSION['session_name']);
}
//finish the procees here befor storing into database;
//use foreach to itterate btw arrays and match anwers
//$_SESSION['session_name'] = explode('|', $_SESSION['session_name']);
//answer table $answers = array('a','b','c','d','e');
/* foreach($_SESSION['session_name'] as $key => $ans){
if($ans == $answer[$key]){
//right procesesor
}
else{
//wrong procesesor
}
} */
//handle the right and wrong process get to total score the store in db
?>
<form method="post" action="index.php">
<input name="name" type="text" placeholder="">
<input type="submit" value="submit">
</form>
<form method="post" action="index.php">
<input type="submit" name="clear" value="clear">
</form>
SIMPLE BASIC demo of how session can get the job done without querying the db each time.
First of all this is my first question on here, and altohugh I have searched the site none of the answers I've seen resolve my current problem.
I am a PHP novice and am currently working on an end project for a course. The object is to make a rudimentary blog where users can post, delete and edit their news, admins can edit or delete everything etc. I am mostly doing fine, but am having a bit of trouble with the editing feature.
The following code displays all blog posts, their authors and dates of posting. If the currently logged in person is the author of a post or a admin, they have the option of deleting or editing each individual post. A small form appears that contains the title and post text. When the user types something else in clicking on the edit button should change the values in the database to the new values the user specified. The problem is that whenever i click on the edit button in the current setup, nothing happens. If i move the if statement outside of the other if statement, the posts do update, but become blank in the database.
Running print_r($_POST) after the fact shows that the array it builds has correct names and updated values, but still they aren't updated in the database. Here is the code, the pertinent part starts at the last if statement( I know, it isn't injection proof, will get to that as soon as it works):
$query = "SELECT id, title, body, pub_date, user_id FROM posts ORDER BY id desc";
$query_fetch = mysql_query($query);
while ($blog_post = mysql_fetch_assoc($query_fetch)) {
$author_id = $blog_post["user_id"];
$post_id = $blog_post["id"];
$post_id2 = $blog_post["id"] . 2;
$title = $blog_post['title'];
$body = $blog_post['body'];
$query = "SELECT username FROM users WHERE id = '$author_id'";
$query_run = mysql_query($query);
$author = mysql_fetch_assoc($query_run);
echo "<h2>" . censor($blog_post["title"]) . "</h2>" . "<br> <p> Autor: " . $author["username"] . "</p><br><p>Objavljeno: " . $blog_post["pub_date"];
if ($_SESSION['admin'] == 1 or $_SESSION['username'] == $author["username"]) {
echo "<form action='' method='POST'><input type='submit' name= '$post_id' value= 'Obriši objavu'></form>";
echo "<form action='' method='POST'><input type='submit' name= '$post_id2' value= 'Uredi objavu'></form>";
}
echo "<p>" . censor($blog_post["body"]) . "</p>";
if (isset($_POST["$post_id"])) {
$del_post = "DELETE FROM posts WHERE id = '$post_id'";
mysql_query($del_post);
}
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
}
}
Any help would be appreciated.
This last piece of code
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
}
gets activated when post_id2 is sent, but generates a form where post_id2 is not contained anymore. So when you submit that form, the IF is not entered.
You can modify it like this:
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
}
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
In general I think you would find it easier to use forms differently, specifically by using some sort of action tag:
input type="hidden" name="command" value="edit"
input type="hidden" name="post" value="{$post_id}"
This way you could run one single query immediately, without the need for browsing all the posts in a cycle.
One other useful possibility is to split your code between different PHP files, and keeping common code in one include:
<?php // this is delete.php
include "common.php";
$post_id = my_get_var('post_id');
my_sql_command("DELETE FROM posts WHERE...");
used from
<form action="delete.php" method="post" ...>
As you can see this allows for different ways of retrieving post_id (centrally defined in a single function my_get_var in common.php) and the central definition of SQL functions. How this function interfaces to MySQL can then be updated, specifically passing from mysql_ functions (which are deprecated, and soon will no longer be available) to e.g. PDO.
It also allows you to test a single command independently, by directly entering delete.php in the browser (you need for my_get_var to accept both POST and GET variables to do this).
Details
You want to inspect and/or modify a collection of posts. You then require initially at least the following operations: list, edit, and delete.
Only the first works against all posts.
So you could have a list.php file running the SELECT. Also, it is only in this SELECT that you need information about the user, so your query could become:
$query = "SELECT posts.id, title, body, pub_date, user_id, username FROM posts JOIN users ON (posts.user_id = users.id) ORDER BY posts.id desc";
In the display cycle we would display this information:
$query_fetch = mysql_query($query);
// This file will receive requests to edit or delete
// We can use a single form.
echo '<form action="manage.php">';
while ($post = mysql_fetch_assoc($query_fetch)) {
echo "<h2>" . censor($post["title"]) . "</h2>" . "<br> <p> Autor: " . $post["username"] . "</p><br><p>Objavljeno: " . $post["pub_date"];
if ((1 == $_SESSION['admin']) or ($_SESSION['username'] == $post["username"]) {
echo "<input type=\"submit\" name=\"Obriši objavu\" value=\"{$post['id']}\" />";
echo "<input type=\"submit\" name=\"Uredi objavu\" value=\"{$post['id']}\" />";
}
echo "<p>" . censor($blog_post["body"]) . "</p>";
}
echo "</form>";
This way you need only one form, and it will submit one field with a name describing the action to be taken, and the post on which to do it.
The file manage.php will then receive this information -- and can also be used to update it:
foreach(array(
"delete" => "Obriši objavu", // from list.php
"edit" => "Uredi objavu", // " "
"update" => "update" // from this file itself (see below)
)
as $test_todo => $var) {
if (array_key_exists($var, $_POST)) {
$id = $_POST[$var];
$todo = $test_todo;
}
}
if (isset($id)) {
switch($todo) {
case "delete":
mysql_query("DELETE FROM posts WHERE id = '{$id}'");
break;
case "edit":
// Get this post.
$query = "SELECT posts.id, title, body, pub_date, user_id, username FROM posts JOIN users ON (posts.user_id = users.id) WHERE posts.id = '{$id}';";
echo '<form action="manage.php" method= "POST">';
// This is how we tell this file what to do, and to what.
echo "<input type=\"hidden\" name=\"update\" value=\"{$id}\">";
// run query, fetch the one record, display info...
echo "</form>";
break;
case "update":
// Build the update query from $_POST.
mysql_query("UPDATE posts SET ...");
}
At first check that your query is correct. Then try to hard-code your query. Also test your query in phpMyAdmin Also you can try to remove the '' from your number variables on every query.
Please, can you give us your error?
There is a possibility also that your database has already been updated. So double check it.
This is how I usually debug. echo the query. Run it in PHPmyadmin, and see the error.
so, in your case.
echo "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
echo that and you will have the query that the script will be trying to run.
Try running it in phpmyadmin and check what the error is.
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>