Почему мои пользователи не могут удалить свой комментарий?
Я создал сайт со страницей комментариев для пользователей, чтобы удалить комментарии, которые они загружают. Однако кнопка удаления комментария появляется, однако она не работает. Кто-нибудь может пролить свет на это для меня, пожалуйста?
<?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><a href="nihome.php#content"> Search for your service</a></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'>
<a href="privacy.php">Privacy Statement</a>
<a href="accessibility.php">Accessibility Statement</a>
</div>
<?php include_once("nihome_end.php"); ?>
2 ответа
Из своего кода вы использовали кнопку отправки формы для удаления записи - и она сохраняется в $str_comments
,
Тебе нужно
<form .....>
<?php echo $str_comments ?>
</form>
Потому что для отправки кнопки нужна форма, чтобы жить в.
#1 Я предлагаю вам начать использовать классы.
# 2, если вы используете mysqli(я расшифровываю), почему вы делаете вещи "по-старому"?
# 3 классный пример
$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