Why can't my users delete their comment? - php

I have created a website with a comments page for users to delete the comments that they upload. However the delete comment button appears however it doesn't seem to work. Can anyone shed some light on this for me please?
<?php
require_once("checklog.php");
include_once("nihome_start_logged.php");
require_once("nifunctions.php");?>
<div id="navigation">
<ul class="container">
<li><a href='nihome.php'>Home</a></li>
<li> Search for your service</li>
<li><a href='nisalons.php' class='button'>Salons and Reviews</a></li>
<li><a href='nichangepassword.php' class='button'>Change Password</a></li>
<li><a href='nilogout.php' class='button'>Logout</a></li>
</ul>
</div>
<?php
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error($db_server));
$db_status = "not connected";
}else{
//Capture form data, if anything was submitted
if (isset($_GET['salonid']) and ($_GET['salonid'] != '')){
$salonid = clean_string($db_server, $_GET['salonid']);
//code to delete comments
if($db_server){
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, "DELETE FROM comments WHERE username = '$username' and salonid = '$salonid' ");
$message= "<p> Comment deleted </p>";
//If connected, get Salons from database and write out
mysqli_select_db($db_server, $db_database);
$query = "SELECT ID, salon_name, address, postcode, telephone, email, website FROM salon WHERE ID=$salonid";
$result = mysqli_query($db_server, $query);
if (!$result) die("Query failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_result .= "<h2>" . $row[ 'salon_name'] . "</h2>";
$str_result .= "<p>" . $row['address'] . "</p>";
$str_result .= "<p>" . $row['postcode'] . "</p>";
$str_result .= "<p>" . $row['telephone'] . "</p>";
$str_result .= "<p>" . $row['email'] . "</p>";
$str_result .= "<p>" . $row['website'] . "</p>";
}
}
mysqli_free_result($result);
}else{
$str_result = "<h2>No salon selected</h2>";
}
}
echo $str_result;
?>
<?php
if(trim($_POST['submit']) == "Submit comment"){
//Get any submitted comments and insert
$comment = clean_string($db_server, $_POST['comment']);
if ($comment != '') {
$name=$_FILES['photo']['name'];
if ($name == "") $error .= "<p class='error'>You must write a review and upload an image!</p>";
$originalname=$_FILES['photo']['name'];
$type=$_FILES['photo']['type'];
if ($type=="image/jpeg") $type=".jpeg"; //if true change
else if ($type=="image/jpg") $type=".jpg";// if not true check this one
else if ($type=="image/png") $type=".png";
$name=uniqid() . $type;
$path="images/" . $name;
$tempname=$_FILES['photo']['tmp_name'];
$size=$_FILES['photo']['size'];
//Error checking
if ($size >1000000) $error .= "<p class='error'>Your image file is to big, it have to be less than 200 mb</p>";
if ($error=="") {
if (move_uploaded_file($tempname, $path)){
$uploadquery="INSERT INTO comments (comment, imagename, salonID, userID) VALUES ('$comment', '$path', $salonid, ". $_SESSION['userID'].")";
mysqli_query($db_server,$uploadquery) or die ("Insert failed " . mysqli_error($db_server) . " " . $uploadquery);
$message= "<h2>Thanks for your comment!</h2><p>Your upload was succesful</p>";
}
}
}
}
//Print out existing comment
$query = "SELECT * FROM comments JOIN users ON comments.userID = users.ID WHERE salonID=$salonid";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while ($row = mysqli_fetch_array($result)){
if ($_SESSION['username'] == $row['username']){
$deletecomment = "<input class='delete comment' type='submit' id='submit' name='submit' value='Delete comment'/>";
}else{
$deletecomment = " ";
}
$str_comments .= "<p><span class='comments'>" . $row['Username'] ." : " . $row['comment'] . "</span></p>";
$str_comments .="<p><img src='" . $row['imagename'] ."' /></p>";
$str_comments .= $deletecomment ;
}
mysqli_free_result($result);
?>
<div id="form">
<table><form id='review' action='salonpage.php?salonid=<?php echo $salonid; ?>' method='post' enctype='multipart/form-data'>
<th><h2> Do you want to review the service you recieved?</h2></th>
<tr><td><textarea name="comment" rows="6" cols="40">Write something here!</textarea></td></tr>
<tr><td><input type='file' name='photo' accept='image/jpg, image/jpeg, image/png'/></td></tr>
<br/>
<tr><td><input type='submit' id='submit' name='submit' value='Submit comment' /></td></tr>
</form></table>
<?php echo $error;
echo $message;?></div>
<h2> Reviews and comments </h2>
<?php echo $str_comments; ?>
<?php mysqli_close($db_server); ?>
<div id='footer'>
Privacy Statement
Accessibility Statement
</div>
<?php include_once("nihome_end.php"); ?>

From you code, you used form-submit-button to delete the record -- and it's stored in $str_comments.
You need
<form .....>
<?php echo $str_comments ?>
</form>
Because the submit-button needs form to live in.

#1 I suggest you start using classes.
#2 if you're using mysqli(i stands for improved) why are you doing things the "old way"?
#3 a classfull example
$drop = new CLASS_NAME_GOES_HERE;
$drop->drop_comment($id,$un);
class CLASS_NAME_GOES_HERE {
private $con; // only access from this class and its children and dont need $ anymore
function __construct() { // constructor function
$this->con = new mysqli(DB,DB_USER,DB_PASS,DB_NAME) or
die('Cannot connect.');
}
function drop_comment($id,$un) {
$sql= "DELETE FROM upload WHERE id = ? AND username = ?";
if($try = $this->con->prepare($sql)) {
$try->bind_param('ss', $id, $un);
if($try->execute()) return true;
}
}//END FUNCTION
}//end class

Related

how to query a value and add it to the date

I have a problem, you see I borrow a book getting the book_id and the date borrow is set to the date today, but each book has a days_id value that I need to add to the day of the borrow_date now I'm having trouble how can I get that date_id from the book_id I chosen and add it inside my borrow_date so that I can generate my due_date automatically
here is my PHP code
<?php
include 'connect.php';
$librarian_id = $_POST['librarian_id'];
$member_id = $_POST['member_id'];
$book_id = $_POST['book_id'];
$date_borrow = $_POST['date_borrow'];
$status_id = $_POST['status_id'];
$days = "SELECT days_id, book_id FROM book_setup
WHERE book_id = '$book_id' AND days_id = " . $row['book_id'] . " ";
$result = mysqli_query($conn, $days);
$due_date = date('Y-m-d', strtotime($date_borrow. ' + $result days'));
if ($librarian_id == '') {
echo "librarian is empty";
}
else if ($member_id == '') {
echo "member id is empty";
}
else if ($book_id == '') {
echo "book is empty";
}
else if ($date_borrow == '') {
echo "date borrow is empty";
}
else if ($status_id == '') {
echo "status is empty";
}
else if ($due_date == '') {
echo "due date is empty";
}
else {
$sql = " INSERT INTO borrow_book (librarian_id, member_id,
book_id, date_borrow, due_date, status_id)
VALUES
('$librarian_id', '$member_id', '$book_id',
'$date_borrow', '$due_date', '$status_id' ) ";
if ($conn->query($sql) === TRUE)
{
$message = "Borrowing book successful";
echo "<script type='text/javascript'>alert('$message');</script>";
}
else
{
$message = "Borrowing book failed Failed";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
$conn->close();
?>
and this is my HTML code
<?php
include 'php/header.php';
require_once 'php/connect.php';
?>
<form method="POST" action="php/borrow.php">
<h1>Borrow Book</h1>
Transacted by:
<br>
<div>
<select name="librarian_id">
<option>Select Librarian
<?php
$sql = "SELECT * FROM librarian";
$result = mysqli_query($conn, $sql);
while ($row =mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['librarian_id'] ."'>"
. $row['Fname'] . " " . $row['Lname'] . "</option>";
}
?>
</option>
</select><br><br>
</div>
Select Member
<br>
<div>
<select name="member_id">
<option>Select member
<?php
$sql = "SELECT * FROM members";
$result = mysqli_query($conn, $sql);
while ($row =mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['member_id'] ."'>"
. $row['Fname'] . " " . $row['Lname'] . "</option>";
}
?>
</option>
</select><br><br>
</div>
<div>
<select name="book_id">
<option>Select a Book
<?php
$sql = "SELECT book_setup.book_id, book.book_id, book.title FROM book_setup
INNER JOIN book ON book_setup.book_id = book.book_id WHERE book_setup.status_id = '1' ";
$result = mysqli_query($conn, $sql);
while ($row =mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['book_id'] . "'>"
. $row['title'] . "</option>";
}
?>
</option>
</select><br><br>
</div>
Borrow Date:
<br><br>
<input name="date_borrow" value="<?php echo date('Y-m-d'); ?>" readonly>
<br><br>
Status:
<div>
<select name="status_id">
<option>
<?php
$sql = "SELECT * FROM borrower_status";
$result = mysqli_query($conn, $sql);
while ($row =mysqli_fetch_assoc($result)) {
echo "<option value='" . $row['status_id'] ."'>"
. $row['status'] . "</option>";
}
?>
</option>
</select><br><br>
</div>
<br>
<br>
<button class="button" type="submit">Submit</button>
<button type="reset" value="Reset">Reset</button>
</form>
this is my database for borrowing book
and this is where I get the book that is available to borrow
Do this:
$res = mysqli_query($con, " SELECT days_id FROM book_setup WHERE book_id = '$book_id' ");
$days = mysqli_fetch_assoc($res)['days_id'];

Update SQL query with PHP error

Here is the error I get when I submit the updated form: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id='19' LIMIT 1' at line 1
Here is the PHP and HTML for the edit (update) page.
<?php
require_once('../../../private/initialize.php');
if(!isset($_GET['id'])) {
redirect_to(url_for('/staff/subjects/index.php'));
}
$id = $_GET['id'];
if(is_post_request()) {
// Handle form values sent by new.php
$subject = [];
$subject['id'] = $id;
$subject['menu_name'] = $_POST['menu_name'] ?? '';
$subject['description'] = $_POST['description'] ?? '';
$result = update_subject($subject);
if($result === true) {
redirect_to(url_for('/staff/subjects/show.php?id=' . $id));
} else {
$errors = $result;
}
} else {
$subject = find_subject_by_id($id);
}
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows($subject_set);
mysqli_free_result($subject_set);
?>
<?php $page_title = 'Edit Subject'; ?>
<?php include(SHARED_PATH . '/staff_header.php'); ?>
<a class="back-link" href="<?php echo url_for('/staff/subjects/index.php'); ?>">« Back to List</a>
<div class="subject edit">
<h1>Edit Subject</h1>
<?php echo display_errors($errors); ?>
<form action="<?php echo url_for('/staff/subjects/edit.php?id=' . h(u($id))); ?>" method="post">
<dl>
<dt>Subject name</dt>
<dd><input type="text" name="menu_name" value="<?php echo h($subject['menu_name']); ?>"</dd>
</dl>
<dl>
<dt>Description</dt>
<dd>
<textarea name="description" cols="60" rows="10"><?php echo h($subject['description']); ?></textarea>
</dd>
</dl>
<div id="operations">
<input type="submit" value="Edit Subject" />
</div>
</form>
</div>
<?php include(SHARED_PATH . '/staff_footer.php'); ?>
This is my PHP update to update the record.
//UPDATE SUBJECTS
function update_subject($subject) {
global $db;
$errors = validate_subject($subject);
if(!empty($errors)) {
return $errors;
}
$sql = "UPDATE subjects SET ";
$sql .= "menu_name='" . db_escape($db, $subject['menu_name']) . "', ";
$sql .= "description='" . db_escape($db, $subject['description']) . "', ";
$sql .= "WHERE id='" . db_escape($db, $subject['id']) . "' ";
$sql .= "LIMIT 1";
$result = mysqli_query($db, $sql);
// For UPDATE statements, $result is true/false
if($result) {
return true;
} else {
// UPDATE failed
echo mysqli_error($db);
db_disconnect($db);
exit;
}}
You have a comma ( , ) right before the WHERE
$sql .= "description='" . db_escape($db, $subject['description']) . "', ";
$sql .= "WHERE id='" . db_escape($db, $subject['id']) . "' ";
change it to:
$sql .= "description='" . db_escape($db, $subject['description']) . "' ";
Remove the , at the last from this line :
$sql .= "description='" . db_escape($db, $subject['description']) . "', ";
Use this :
$sql .= "description='" . db_escape($db, $subject['description']) . "' ";

How to get different buttons to submit different mySQL queries

I'm trying to create a button in a HTML form that adds a number to the corresponding mySQL location. Basically, a voting option for a post. Right now, the buttons all do the same thing: they submit the original post query from the bottom. How do I make them act individually?
PHP:
if (!$thepipeline) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
if (!empty ($_POST)) {
$squery = "INSERT INTO votes (votes) VALUE (1)";
print $squery;
$votes_result = mysqli_query ($thepipeline, $squery);
}
$query = "SELECT p.post_id, p.member_id, p.content, p.date_created,
SUM(v.votes) AS votes_total
FROM posts p LEFT JOIN
votes v
ON p.post_id = v.post_id
GROUP BY post_id
ORDER BY votes_total;";
echo "<table>\n";
echo '<tr>
<td> USER ID</td>
<td> PROPOSAL</td>
<td> DATE POSTED</td>
<td> SCORE</td>
</tr>';
if ($amorphous_cloud = mysqli_query ($thepipeline,$query)) {
while ($row = mysqli_fetch_assoc ($amorphous_cloud)){
echo '<tr>
<td> ' . $row['member_id'].'</td>
<td> ' . $row['content'].'</td>
<td> ' . $row['date_created'].'</td>
<td> ' . $row['votes_total'].'
<br><form method="POST"><input type="button" name="vote" value="Vote" /></form></td>
</tr>';
}
}
else {
print ":(";
}
echo "</table>\n";
?>
<br>
</div>
<div id="addpost">
<h3>Enter Proposal</h3>
<p>Off-topic posts will be deleted without warning.</p>
<?php
$member_id = $_GET['member_id'];
$content = $_GET['content'];
$link = mysqli_connect ('localhost', '******', '************,', '*************');
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
if (!empty ($_GET)) {
$query = "INSERT INTO posts (member_id, content) VALUES ('".$member_id."', '".$content."')";
print $query;
$member_result = mysqli_query ($link, $query);
}
$user_query = "SELECT member_id, member_name FROM members";
$user_result = mysqli_query ($link, $user_query);
$user_html = "";
while ($row = mysqli_fetch_assoc ($user_result)) {
$user_html = $user_html . "<option value='".$row['member_id']."'>".$row['member_name']."</option>\n";
}
?>
<form method="GET">
<!-- member -->
<p>Member</br>
<select name="member_id" >
<?php echo $user_html; ?>
</select>
</p>
<!-- date -->
<p>Content
</p>
<textarea name="content" cols="40" rows="5"></textarea>
</br>
<input type="submit" />
</form>
</div>
</div>

UPDATE single column in database: PHP&MYSQL

So, I am trying to figure out how do this this and it boggling me. THIS WILL NOT BE USED ONLINE LIVE SO SQL INJECTION I DONT' CARE ABOUT. What am I doing wrong/right?
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_GET['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = $id";
$comment1 = mysql_query($sql);
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
echo $sql;
The main problem is with the statement itself, the connection is fine. I am trying to read $comment, and then update that into a MYSQL table and then have it read back in a different file.
EDIT: Mark up for the form I'm taking $comment from.
<!DOCTYPE html>
<html lang="en">
<LINK href="stylesheet.css" rel="stylesheet" type="text/css">
<script src ="js/validateform.js"></script>
<head>
<meta charset="UTF-8">
<title>UniHelp Home</title>
</head>
<body>
<div id="headeruni">
<h1>Welcome <?php echo $_GET["name"]; ?> to UniHelp!</h1>
</div>
<div id ="infouni">
<h3>Welcome to UniHelp. The social Network getting you connected to other people all over the University for any help you require!</h3>
</div>
<div id ="nameandemail">
<form action="formsend.php" method="post">
First name: <br> <input type="text" name="name"><br>
Email: <br> <input type="text" name="email"><br>
Comment: <br> <input type="text" name="message"><br>
<input type="submit" name="submit">
</form>`enter code here`
</div>
<div id="grabphpdiv">
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$result = mysql_query("SELECT * FROM Dbsaved", $db);
if (!$result) {
die ("Database query failed: " . mysql_error());
}
$comment = $_POST['$comment'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo 'Comment: <br>
<input type=text name=comment><br>
<a href=addcomment.php?id=' . $row[0]. '&comment='. $row['$comment'].'>Comment</a>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
</div>
</body>
<div id="footer">Copyright &copy James Taylor 2016</div>
</html>
I just ran this code:
$comment = "Hello World!";
$id = 1;
$sql = "UPDATE Dbsaved SET comment = '{$comment}' WHERE id = {$id}";
echo $sql;
and saw:
UPDATE Dbsaved SET comment = 'Hello World!' WHERE id = 1
which is a correct SQL statement, so if it is not working, you might want to play with SQL directly to get something working. Hope that helps!
SOLUTION:
$comment = $_GET['$comment'];
$id = $_GET['$id'];
while ($row = mysql_fetch_array($result)) {
echo "<div id='posts'>";;
echo "<h2>";
echo $row[1] . "";
echo "</h2>";
echo "<p>";
//echo $timestamp = date('d-m-y G:i:s ');
echo "<br>";
echo "<br>";
echo $row[2] . "";
echo "</p>";
echo "<p>";
echo $row[3] . "";
echo "</p>";
echo 'Delete';
echo "<br>";
echo "<br>";
echo $row[4] . "";
echo "<br>";
echo 'Comment: <br>
<form action="addcomment.php?id=' . $row[0]. '" method="post">
<input type=text name=comment><br>
<input type=submit name="submit">
</form>';
echo "<p>";
echo $row['comment'] . "";
echo "</p>";
echo "</div>";
echo "<br>";
}
?>
and:
<?php
$db = mysql_connect("localhost", "root", "root");
if (!$db) {
die("Database connect failed: " . mysql_error());
}
$db_select = mysql_select_db("UNii", $db);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$comment = $_POST['comment'];
$id = $_GET['id'];
$sql = "UPDATE Dbsaved SET comment = '$comment' WHERE id = $id ";
$comment1 = mysql_query($sql);
echo $sql;
if (!$comment1) {
die("did not save comment: " . mysql_error());
}
else {
header("location: UniHelpindex.php");
}
It was to do with mainly needing to get the id which was used in $row[0]' in the form created in the while loop. And actually using the correct syntax for the update Dbsaved... bit.

Adding a validation check to a form in a while loop php

I have a form which displays like this:
Event Name : Drop down menu
I am trying to add a check that ensures that each event produced by the while loop has a student assigned to it - by selecting from the drop down menu.
I have attempted adding a check for this but its not making a difference - it loads form action page 'savecompetitors'.
I have got this for php so far:
<?php
session_start();
require_once 'db/connect.php';
require_once 'db/checkuserloggedin.php';
include 'db/header.php';
echo $_SESSION['Username'] . ' logged in successfully';
echo '<h3> Entry form </h3>';
//Query to display all events
if ($event_result = $con->query("SELECT Name FROM event")) {
echo "<form method =\"POST\" action=\"savecompetitors.php\">";
echo '<table>';
while ($row = $event_result->fetch_assoc()) {
echo '<tr>';
echo '<td>';
echo $row['Name'] . ' ';
echo '</td>';
if ($student_result = $con->query("SELECT Student.Form, Teacher.Form, Forename, Surname, Student_ID " .
"FROM student, teacher " .
"WHERE Student.Form = Teacher.Form AND Teacher.Username = '" . $_SESSION['Username'] . "'")
) {
if ($student_result->num_rows) {
echo '<td>';
echo "<select name ='" . $row['Name'] . "'>";
while ($row1 = $student_result->fetch_assoc()) {
echo '<option value="" style="display:none;"></option>';
echo "<option value ='" . $row1['Student_ID'] . "'>" . $row1['Forename'] . ' ' . $row1['Surname'] . "</option>";
if (isset($_POST['submit'])) {
if (empty($_POST['Student_ID'])) {
$error = 'A student must be selected for every event';
}
}
}
echo "</select>";
echo '</td>';
echo '</tr>';
}
}
}
echo '</table>';
echo '<input type="submit" name="submit" value ="Submit" >';
echo '<input type="reset" value ="Reset">';
echo '<span class="error"><?php echo $error;?></span>';
echo '<span class="error"><?php echo $success;?></span>';
echo "</form>";
} else {
echo 'No student records available';
}
savecompetitors php:
<?php
require_once 'db/connect.php';
$error = '';
$success = '';
$event_result = $con->query("SELECT Event_ID, Name from event");
while ($row = $event_result->fetch_assoc()) {
$eventname = str_replace(' ', '_', $row['Name']);
print_r($row);
$con->query("INSERT INTO competitors (Event_ID, Student_ID) VALUES (" . $row['Event_ID'] . ", " . $_POST[$eventname] . ") ");
$success = 'Entry form has been successfully saved and students are entered as competitors for their submitted events';
}

Categories