Need to set variables to "Null" after POST action (PHP function) - php

I have a comments section in a website that uses a "setComments" function to enter data into a SQL DB. This works great, but I found that if I refresh the page, the comment is re-entered into the DB and displayed as multiple comments using a "getComments" function.
I know I need to drop the values of the comment variables but tried a few places in the code and no joy.
This is the form to enter the comment:
<?php
echo "<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='pid' value='$post_id'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<label>Add Comment</label>
<textarea name='message'class='form-control' width='50' cols='40'
rows='3'></textarea><br>
<button type = 'submit' name ='commentSubmit' class='btn btn-
primary'>Submit<span class='glyphicon glyphicon-chevron-right'></span>
</button>
</form>";
getComments($conn)
?>
<?php
function setComments($conn){
if (isset($_POST ['commentSubmit'])) {
$uid=$_POST['uid'];
$pid=$_POST['pid'];
$date=$_POST['date'];
$message=$_POST['message'];
$sql = "INSERT INTO comments (uid, pid, date, message)
VALUES('$uid','$pid', '$date', '$message')";
$result = $conn->query($sql);
}
}
function getComments($conn) {
if (isset($_GET['post'])) {
$pid = $_GET['post'];
$sql = "SELECT * FROM comments WHERE pid=$pid";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
if (mysqli_num_rows($result) > 0) {
while($row = $result->fetch_assoc()){
echo "<div class='comment-box'>";
echo $row['uid']."<br>";
echo $row['date']."<br>";
echo $row['message'];
echo "</div>";
}
}
else {
echo "Be the first to comment";
}
}
}
Comments are entered into sql DB fine, but variables not discarded once complete so they are re-entered into DB and displayed again on page refresh (page containing the comment form also displays the comments.

I ended up using the following script in the page - it seems to work fine:
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>

Related

Value not saving after form is submitted

I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>

How to know which form was validated in loop-generated forms

This is the code I wrote to generate as many forms as there is entries in a table.
I'd like to know which Submit button (i.e. of which exact form) was clicked to then execute some SQL actions.
Thank you for your help!
<?php
require_once 'header.php';
if (!$loggedin) die();
$result = queryMysql("SELECT * FROM audit_requests");
$num_rows = $result->num_rows;
echo "<div class='main'><h3>$num_rows audit requests found!</h3>";
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
$requester = stripslashes($row['user']);
$audit_request_id = stripslashes($row['audit_request_id']);
echo <<<_END
<form method='post' action='audit_listings.php' enctype='multipart/form-data'>
<span class='text'><br>Audit request number</span>
<input disabled type='text' maxlength='10' name='audit_request_id' value='$audit_request_id'>
<span class='text'><br>Auditee name</span>
<input disabled type='text' maxlength='16' name='user' value='$requester'>
_END;
if (getCategory($user) == 'Auditor')
{
echo "<input type='submit' value='Apply for this audit request'>";
}
echo <<<_END
</form></div><br>
_END;
}
if (isset($_POST['audit_request_id']))
{
$audit_request_id = stripslashes('audit_request_id');
queryMysql("INSERT INTO audit_plan SELECT * FROM audit_requests WHERE audit_request_id='$audit_request_id'");
queryMysql("UPDATE audit_plan SET applicant='$user' WHERE audit_request_id='$audit_request_id'");
queryMysql("INSERT INTO messages VALUES('', 'TrustusChain', '$org_name', '$address', '', '$city'");
}
?>
You could add a hidden field to the form. Like:
echo "<input type=\"hidden\" value=\"form_xxx\">";
You can generate random id's to the form like
<form method="post" onsubmit="return myfunc(this.id)" id="From_php">
in javascript
<script>
function myfunc(id){
//do anything with id of form
}
</script>
You can pass ajax requests to server accordingly.

i am making an comment section in php under my file upload

$query_file="SELECT * FROM files";
$result_file = mysql_query($query_file);
if ($result_file) {
while ($row= mysql_fetch_array($result_file))
{
if($row[file_type] == "image"){
echo" <image src=".$row['file_location']."width=340 height=240>";
echo "</image><br>";
echo "</br>";
echo $row['file_description'];
echo "</br>";
}
if (isset($_POST['post_comment']) and !empty($_POST['write_comment'])) {
$comment_description = trim(htmlentities(strip_tags(mysql_real_escape_string($_POST['write_comment'])))); {
if (!$file_id=mysql_query("SELECT file_id FROM files WHERE file_id='$id' ")) {
echo 'Invalid file ID';
} else {
$query=mysql_query("INSERT INTO comments VALUES ('','$user','$fileid',NOW(),'$comment_description')");
}
}
}
echo "
<div style='float: left; width: 100%;''>
<form action='' method='post'>
<textarea name='write_comment' rows='3' cols='50' style='float: left;'></textarea>
<input type='submit' name='post_comment' id='' value='Comment' style='height: 40kpx; float: left;''d>
</form>
</div>
";
}
}
else{
echo mysql_error();
}
this is my code for making comment section but it is not aking the particular fileid which i have uploaded
how should i correct it
and my sql table for commment...
comments_id,comment_by,comment_on,comment_date,comment_description
and my files table
(id, file_title, file_description, file_keywords, privacy, uploaded_by, date_uploaded, md5, views, file_id, file_md5, file_location, file_type)
Due to the nature of the original code and the lack of clarity on what the actual question is the following may or may not be what you were trying to do.
There were many errors in the original code - some of them PHP, the others basic HTML faults. I tried to identify and fix them though I make no guarantees they are all fixed.
The form that allows the user to add a comment has a hidden field that contains the ID for the image. That ID is POSTed along with the comment and is inserted using the code at the top ~ but again - where is $user defined?
The code here is vulnerable to sql injection but as you have stated you are going to change this to mysqli then that is irrelevant perhaps.
<?php
/*
This handles the insertion of the comment
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['write_comment'], $_POST['post_comment'], $_POST['file_id'] ) ){
$fileid=$_POST['file_id'];
$comment=$_POST['write_comment'];
$user='GERONIMO'; /* WHERE IS $user DEFINED????? */
$query=mysql_query( "INSERT INTO comments VALUES ( '', '$user', '$fileid', NOW(), '$comment_description' )" );
}
?>
<?php
/*
This is to display the image and
the form so that a user can add a
comment
*/
$sql='SELECT * FROM files';
$result = mysql_query( $sql );
if ( $result ) {
while( $row= mysql_fetch_array( $result ) ) {
if( $row['file_type'] == "image" ){
echo "
<div style='float:left; width:100%;'>
<img src='{$row['file_location']}' width=340 height=240 />
<p>
{$row['file_description']}
</p>
<form method='post'>
<textarea name='write_comment' rows='3' cols='50' style='float:left;'></textarea>
<input type='hidden' name='file_id' value='{$row['file_id']}' />
<input type='submit' name='post_comment' value='Comment' style='height:40px; float:left;'>
</form>
</div>";
}
}
}
?>

How do I get a "blob" image to post in a comment section

First off, I am VERY new to PHP coding. I've been more than a few days getting everything to work that is working and have been watching hours of video. Yet, for the life of me, I cannot get this to "completely" function.
When I click my upload button, the author, date_time group, and the comment work fine. They are posting to the database and posting to the "GET" section when I click upload. The thumbnail on the other hand just gives the broken path image. I'm sure it's something I'm not defining correctly, but I am completely lost. I have posted my comment box form source code, connection, and functions. My database is in commentsection/comments/image. The "image" column of the database type is set to BLOB.
Please help...
SOURCE CODE:
<?php
echo "<form method='POST' enctype='multipart/form-data 'action='".setComments($conn)."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<label>Upload Image</label><br>
<input type='file' name='image' id='image'><br>,<br>
<textarea name='message'></textarea><br><br>
<button type='submit' name='commentSubmit'>Upload</button>
</form>";
getComments($conn);
?>
CONNECTION:
$conn = mysqli_connect('localhost','root','', 'commentsection');
if (!$conn) {
die("Connection failed:".mysqli_connect_error());
}
FUNCTIONS:
<?php
function setComments($conn) {
if (isset($_POST['commentSubmit'])) {
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$image = $_POST['image'];
$sql = "INSERT INTO comments (uid, date, image, message) values ('$uid', '$date','$image', '$message')";
$result = mysqli_query($conn, $sql);
}
}
function getComments($conn) {
$sql = "SELECT * FROM comments ORDER BY date DESC LIMIT 10";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)){
echo "<div class='commentbox'><p>";
echo $row['uid'];
echo $row['date']."<br>";
echo "<div class='thumbnail'>";
echo "<img src='".$row['image']."'>";
echo "</div>";
echo nl2br($row['message']);
echo "<p></div>"."<br>";
}
}

Ajax favorite/unfavorite button

I'm trying to implement some Ajax on a favourite/unfavourite button. The idea behind it is that when you click it a star changes to yellow and when you click it again, it changes back to grey and so on. It adds and deletes data from a DB.
before I had it like this
<?php
include("classes/event.class.php");
$m = new Event();
$arrayAllEvents = $m->getNonFavo();
$arrayFavorites = $m->getFavo();
$db = new db();
while ($row = mysqli_fetch_assoc($arrayFavorites))
{
$unfavoriteID = $row['f_id'];
$uid = $_SESSION['u_id'];
}
if(isset($_POST['favorite_row']))
{
$uid = $_SESSION['u_id'];
$Fid = $_POST['id_to_be_favo'];
if(!mysqli_query($db->conn, "INSERT INTO favorites (u_id, n_id, f_boolean) VALUES
('". $db->conn->real_escape_string($uid) ."' ,
'". $db->conn->real_escape_string($Fid) ."' ,
'". $db->conn->real_escape_string("1") ."')"))
{
echo mysqli_error($db->conn);
}
}
if(isset($_POST['Unfavorite_row']))
{
$unFid = $_POST['id_to_be_unfavo'];
if(!mysqli_query($db->conn, "DELETE FROM favorites WHERE f_id ='".$unFid."'"))
{
echo mysqli_error($db);
}
}
?>
And the field was a php echo form
<?php
echo "<form method='post'>
<input type ='hidden' name='id_to_be_favo'
value='".$a['n_id']."' />
<input type='submit' class='favoriteFalse' id='FavoBtn' name='favorite_row' value='favorite' />
</form>
<div class='clearfix'> </div>";
?>
I'm trying to change the form to a button and use jQuery/Ajax to switch it.
I've been trying some different solutions I've found online, but none of them seem to work.
What would be the best way to implement this?
Kind regards
<input type='button' class='favorite' id='<?php echo $a['n_id']; ?>' value='favorite' />
<div class='clearfix'> </div>";
using
$(function() {
$(".favorite").on("click".function() {
$.post("whatever.php", {"favorite_row":this.id}, function(data) {
$("#star").html('<img/>',{"src":data.fave==yes"?"true.png":"false.png"});
});
});
Now return {"fave":"yes"} if favorited

Categories