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

$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>";
}
}
}
?>

Related

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

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>

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.

Storing database value into variable

My table category has these columns:
idcategory
categorySubject
users_idusers
I have a form with a simple radio buttons and a textbox.
I have a select all statement for category and need to get the idcategory stored into a variable ($getCatId) so I can use this statement:
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
What is the best way to get and store categoryid?
if($_SERVER['REQUEST_METHOD'] != 'POST') //show form if not posted
{
$sql = "SELECT * FROM category;";
$result = mysqli_query($conn,$sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class= 'choice'><input type='radio' name='category' value='". $row['idcategory'] . "'>" . $row['categorySubject'] ."</div></br>";
}
echo 'Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false)
{
echo 'You must be signed in to contribute';
}
else{
$sql="INSERT INTO topic(subject, topicDate, users_idusers, category_idcategory, category_users_idusers) VALUES('($_POST[topic])', '$date', '$_SESSION[userid]', '$getCatId', '$_SESSION[userid]');";
$result = mysqli_query($conn,$sql);
echo "Added!";
If I understand this question correctly, you'll have your $getCatId (id of the category) in $_POST['category'] (after sending form) in your case
The first thing you should do is protect yourself from SQL injection by parameterizing your queries before old Bobby Tables comes to pay you a visit.
You might also look into using PDO as I've demonstrated below because it's a consistent API that works with a lot of different database management systems, so this leads to wonderfully portable code for you. Here's an annotated working example on Github:
<?php
// returns an intance of PDO
// https://github.com/jpuck/qdbp
$pdo = require __DIR__.'/mei_DV59j8_A.pdo.php';
// dummy signin
session_start();
$_SESSION['signedIn'] = true;
$_SESSION['userid'] = 42;
//show form if not posted
if($_SERVER['REQUEST_METHOD'] != 'POST'){
$sql = "SELECT * FROM category;";
// run query
$result = $pdo->query($sql);
?>
<form method="post" action="createTopic.php">
Choose a category:
</br>
</br>
<?php
// get results
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "
<div class= 'choice'>
<input type='radio' name='category' value='$row[idcategory]'/>
$row[categorySubject]
</div>
</br>
";
}
echo '
Topic: <input type="text" name="topic" minlength="3" required>
</br></br>
<input type="submit" value="Add Topic" required>
</form>
';
}
if ($_POST){
if(!isset($_SESSION['signedIn']) && $_SESSION['signedIn'] == false){
echo 'You must be signed in to contribute';
} else {
// simulate your date input
$date = date("Y-m-d");
// bind parameters
$sql = "
INSERT INTO topic (
subject, topicDate, users_idusers, category_idcategory, category_users_idusers
) VALUES(
:subject, :topicDate, :users_idusers, :category_idcategory, :category_users_idusers
);
";
// prepare and execute
$statement = $pdo->prepare($sql);
$statement->execute([
'subject' => "($_POST[topic])",
'topicDate' => $date,
'users_idusers' => $_SESSION['userid'],
// to answer your question, here's your variable
'category_idcategory' => $_POST['category'],
'category_users_idusers' => $_SESSION['userid'],
]);
echo "Added!";
}
}

Update and delete for specific record

I have written code to retrieve all the images from database for a specific city, and I want to be able to delete a specific image or to change the caption.
The problem is:
the code always work on the last image only!
I hope you guys will be able to help me with this problem.
Retrieve code:
<?php
$City_name=$_REQUEST['id'];
$Image_query = "SELECT * FROM image where City_name ='".$City_name."' ";
$Image_result = mysqli_query($dbcon,$Image_query);
echo "<table>";
while ($row = mysqli_fetch_array($Image_result))
{
$image_id = $row['Image_id'];
$image = $row['Image_url'];
$Caption = $row['Caption'];
echo "<tr style='float:right;'>";
echo "<td>"; ?> <img src="<?php echo $image ; ?>"/> <br>
<input type="text" name="caption" value="<?php echo $Caption ;?>" />
<br> <input name="delete" type="submit" value="Delete picture" />
<br> <input name="Update_caption" type="submit" value="change caption" />
<?php echo "</td>";
echo "<td>"; ?> <input class="input-image" type="hidden" name="id" value="<?php echo $image_id ;?>" />
<?php echo "</td>";
} /* End of while loop */
echo "</tr>";
echo"</table>";
?>
Update code :
if (isset($_POST['Update_caption'])) {
$ImageID = $_POST['id'];
$ImageCaption = $_POST['caption'];
$sql = mysqli_query ($dbcon,"UPDATE `image` SET `Caption`='".$ImageCaption."' WHERE `Image_id`='".$ImageID."' ");
if ($sql) {
echo "done";
} else { echo "error"; }
}
Delete code :
if (isset($_POST['delete'])) {
$ImageID = $_POST['id'];
$sql = mysqli_query ($dbcon,"DELETE FROM `image` where `Image_id` = '".$ImageID."' ");
if ($sql) {
echo "done";
} else { echo "error"; }
}
$_POST['id'] (sql injection alert!) contains the contents of the input element that has a name attribute id.
You are echoing out your input elements in a loop, all with the same name so the last one will overwrite all the previous ones.
You should use an array like for example:
<input class="input-image" type="hidden" name="id[<?php echo $image_id ;?>]" value="<?php echo $image_id ;?>" />
So that your $_POST['id'] is an array containing all elements.
The same applies to other input elements like the caption.
An alternative, especially for your delete option, would be to wrap every image in its own form. But keep in mind that you will need valid html for that to work, you can't have a form that opens in a row element and spans different columns.
And note that you should really use a prepared statement to close the sql injection hole you have now.

Categories