MYSQL and PHP Loop Failure - php

What problem i am having right now, is that there is a while loop to post my topics retrieved from MySQL. Works perfectly fine, until I get into inputting data. I have recently created a comment system, where for each topic there will be a comment box to submit. The problem is the while loop runs it over and over again, so when i type a comment for one topic, it posts to all of them.
Here is my code:
//MYSQLI LOGIN DETAILS
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
//MYSQLI CREATE CONNECTION
$constatus = new mysqli($servername, $username, $password, $dbname);
//MYSQLI CHECK CONNECTION
if ($constatus->connect_error) {
die("Connection failed: " . $constatus->connect_error);
}
//MYSQLI COUNT COLUMNS
$sql = "SELECT NEWSID, AUTHOR, ADMINSTS, DATE, HEADING, ARTICLE FROM news ORDER BY NEWSID DESC";
$result = $constatus->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo
"<div class=newsboard_topic>" .
"<div class=newsboard_authordate>" . $row["AUTHOR"];
if ($row["ADMINSTS"] == admin) {
echo
"<div class=newsboard_adminfx>
Admin
</div>";
} else if ($row["ADMINSTS"] == sadmin) {
echo
"<div class=newsboard_sadminfx>
Super Admin
</div>";
}
if ($_SESSION['adminsts'] == 'admin' || $_SESSION['adminsts'] == 'sadmin') {
echo "<span class=newsboard_adminactions> <img src='/image/remove.png' style='width:20px; height:20px;'> </span>";
}
echo
"<span class=date>" . $row["DATE"] .
"</span></div>
<h1>" . $row["HEADING"].
"</h1><p class=newsboard_topic_article>" .
$row["ARTICLE"] .
"</p>";
$sqlcomments = "SELECT newscomments.USERID, newscomments.COMMENT, userdata.FIRSTNAME, userdata.LASTNAME, userdata.ADMINSTATUS FROM newscomments JOIN userdata ON newscomments.USERID=userdata.ID WHERE NEWSID=$row[NEWSID] ORDER BY COMMENTID DESC";
$resultcomments = $constatus->query($sqlcomments);
echo "<div class=newsboard_comments>
Comments
<br>";
while($rowcomments = $resultcomments->fetch_assoc()) {
echo $rowcomments["FIRSTNAME"] . " " . $rowcomments["LASTNAME"] . " " . $rowcomments["COMMENT"] . "<br>";
}
if (isset($_SESSION['loggedon']) && $_SESSION['loggedon'] == true) {
echo '
<form method="post">
<input class=postheadline type="text" name="comment" />
<input class=submit type="submit" id="submit" name="submit" value="Comment"/>
</form>';
if (isset($_POST[submit])) {
if (!empty($_POST[comment])) {
$sqlcommentpost = "INSERT INTO newscomments (NEWSID, USERID, COMMENT) VALUES ('$row[NEWSID]', '$_SESSION[profileid]', '$_POST[comment]')";
if ($constatus->query($sqlcommentpost) === TRUE) {
echo "Posted Successfully!";
break;
} else {
echo "Fatal Error. Please try again";
break;
}
}
}
}
echo "</div></div>"; /*Ends newsboard_topic Div & newsboard_comments Div*/
}
} else {
echo "0 results";
}
Live example is online at www.geovillageva.com however you cannot see comments as it is for registered members only because it will have a name for posters.

Lets include the news id also in the form. You can have a hidden input field for this. Then use this news id $_POST[nid] while inserting.
if (isset($_SESSION['loggedon']) && $_SESSION['loggedon'] == true) {
echo '
<form method="post">
<input class=postheadline type="text" name="comment" />
<input type="hidden" name="nid" value="'.$row[NEWSID].'" />
<input class=submit type="submit" id="submit" name="submit" value="Comment"/>
</form>';
if (isset($_POST[submit])) {
if (!empty($_POST[comment])) {
$sqlcommentpost = "INSERT INTO newscomments (NEWSID, USERID, COMMENT) VALUES ('$_POST[nid]', '$_SESSION[profileid]', '$_POST[comment]')";
if ($constatus->query($sqlcommentpost) === TRUE) {
echo "Posted Successfully!";
break;
} else {
echo "Fatal Error. Please try again";
break;
}
}
}
}

So, your input block
if (isset($_SESSION['loggedon']) && $_SESSION['loggedon'] == true) {
echo '
<form method="post">
<input class=postheadline type="text" name="comment" />
<input class=submit type="submit" id="submit" name="submit" value="Comment"/>
</form>';
if (isset($_POST[submit])) {
if (!empty($_POST[comment])) {
$sqlcommentpost = "INSERT INTO newscomments (NEWSID, USERID, COMMENT) VALUES ('$row[NEWSID]', '$_SESSION[profileid]', '$_POST[comment]')";
if ($constatus->query($sqlcommentpost) === TRUE) {
echo "Posted Successfully!";
break;
} else {
echo "Fatal Error. Please try again";
break;
}
}
}
}
needs to go by itself before the display loop. On the query inserting using $row[NEWSID], you need to use $_POST['newsid'] instead (and you may need to add that to your form to be posted along with the comments).
Please note that you need to beef up the security on this considerably or you will be hacked.

You can try a .reset() on your form after the submission was successful(before the break).

Related

Comment delete button not working

I have a problem with my comments. I can insert them in the database my friend made and echo them in the right pages, but the delete part isn't working.
People with an account can delete their own comments, and admins can delete any comment. But when i click on the delete button of a comment, i doesn't do anything and when i click again it deletes every comment in that page, can someone help? When I click a delete button, i want to delete that specific comment only, not all of them. Also, the key in the database is the date the comment was posted.
Here's comments.php
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="/cssfolder/comments.css">
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Open+Sans%22%3E">
<head>
<title>Page Title</title>
</head>
<body>
<div class="comment">
<form method="post" action="">
<textarea name='message' class="area" id='message' placeholder="Leave a comment"></textarea><br/>
<br>
<input type="submit" class="commentbutton" name="comment" value="Comment">
<br>
</form>
</div>
<div class="commentcontainer">
<?php
date_default_timezone_set('America/Curacao');
$db = new PDO('mysql:host=localhost;dbname=id1552202_accounts', 'id1552202_thecouch', 'Fargo123');
$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$link = parse_url($url)['path'];
$path = ltrim($link, '/');
try {
$zoekfilm = $db->prepare("SELECT film_id FROM Reviews WHERE path = :path");
$zoekfilm->bindParam("path", $path);
$zoekfilm->execute();
$film = $zoekfilm->fetch();
} catch(PDOException $b){
die("Error!: " . $b->getMessage());
}
$hoeveel = $db->prepare("SELECT * FROM comments WHERE film_id = :id ");
$hoeveel->bindParam("id", $film[0]);
$hoeveel->execute();
$count = $hoeveel->rowCount();
echo "<br><b>" . $count . " Comments</b><br><br>";
if(isset($_POST['comment'])){
if(empty($_POST['message'])){
echo "There's no message";
echo "<br>";
echo "<br>";
} else {
if(isset($_SESSION['loggeduser'])){
$message = $_POST['message'];
$datum = date('YmdHis');
$username = $_SESSION['loggeduser'][0];
$nospam = $db->prepare(" SELECT comment FROM comments WHERE comment = :message AND film_id = :id");
$nospam->bindParam("message", $message);
$nospam->bindParam("id", $film[0]);
$nospam->execute();
if($nospam->rowCount() === 1){
echo "No spam please";
} else {
try{
$addcomment = $db->prepare("INSERT INTO comments(Usernames, film_id, comment, date) VALUES (:username, :id , :comment, :datum )");
$addcomment->bindParam("username", $username);
$addcomment->bindParam("id", $film[0]);
$addcomment->bindParam("comment", $message);
$addcomment->bindParam("datum", $datum);
$addcomment->execute();
} catch(PDOException $c){
die("Error!: " . $c->getMessage());
}
}
} else {
header("Location: /signin.php");
}
}
}
try {
$showcomments = $db->prepare("SELECT * FROM comments WHERE film_id = :id ORDER BY date DESC");
$showcomments->bindParam("id", $film[0]);
$showcomments->execute();
while($result = $showcomments->fetch(PDO::FETCH_ASSOC)){
if(isset($_SESSION['admin'])){
echo '<div class="commentdiv">';
echo '<p><b>'.$result['Usernames'].'</b></p>';
echo '<p class="tijd"><i><small>'. $result['date'] .'</small></i></p>';
echo '<p> '.$result['comment'].'</p>';
echo '<br>';
echo '<form method="post" action="">';
echo '<input type="submit" value="Delete Comment" name="delete" class="commentbutton" style="width:200px;">';
echo $result['date'];
echo '<br>';
echo '</form>';
$delete = $result['date'];
if(isset($_POST['delete'])){
$verwijderen = $db->prepare(" DELETE FROM comments WHERE comments.date = :datum LIMIT 1");
$verwijderen->bindParam("datum", $delete);
$verwijderen->execute();
}
echo '</div>';
} else if(isset($_SESSION['loggeduser'][0])) {
echo '<div class="commentdiv">';
echo '<p><b>'.$result['Usernames'].'</b></p>';
echo '<p class="tijd"><i><small>'. $result['date'] .'</small></i></p>';
echo '<p> '.$result['comment'].'</p>';
echo '<br>';
echo '<form method="post" action="">';
echo '<input type="submit" value="Delete Comment" name="delete" class="commentbutton" style="width:200px;">';
echo '<br>';
echo '</form>';
echo '</div>';
$delete = $result['date'];
if(isset($_POST['delete'])){
$verwijderen = $db->prepare(" DELETE FROM comments WHERE comments.date = :datum ");
$verwijderen->bindParam("datum", $delete);
$verwijderen->execute();
}
} else {
echo '<div class="commentdiv">';
echo '<p><b>'.$result['Usernames'].'</b></p>';
echo '<p class="tijd"><i><small>'. $result['date'] .'</small></i></p>';
echo '<p> '.$result['comment'].'</p>';
echo '</div>';
}
}
} catch(PDOException $a){
die("Error!: " . $a->getMessage());
}
?>
</div>
</body>
</html>
The query deletes all the comments of the page because it's in the while loop and you don't give a unique ID to be sure you delete the right comment from the DB. So the query is repeated as long as the page has comments deleting all the comments for the given date.
The solution could be :
Add a primary key to the comments table if it hasn't one yet,
Add the value of the primary key to value attribute of the delete button,
Put the delete query after the while loop,
Use the primary key you fetched from the delete button to delete the right comment,
Fix your code indentation (the most important).
The code would look like this :
// ...
echo '<button type="submit" value="'.$result['id_comment'].'" name="delete" class="commentbutton" style="width:200px;">'.$result['date'].'</button>';
// Then outside of the loop :
if (isset($_POST['delete']) && !empty['delete']) {
$verwijderen = $db->prepare("DELETE FROM comments WHERE id_comment = :id_comment");
$verwijderen->bindParam("id_comment", $_POST['delete']); // note that the $_POST['delete'] value is now the id of the comment.
$verwijderen->execute();
}
This must give you the idea. Good luck. ; )

Change Color for checkin form

I want to create a form that displays records from my database
name, email, phone number and situation , and after selecting I want to change the background color of the situtaton itdepends the value ?
<form method="post">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="submit">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ID = isset($_POST['ID']) ? $_POST['ID'] : false;
$connect = mysql_connect('localhost', 'root', '','seminar');
mysql_select_db ('seminar');
$sql = "SELECT `name`, `del_company`, `phone`, `email`, ,`situation` FROM `dele` WHERE ID = $ID";
$res = mysql_query($sql);
if(! $ID ) {
die("Could not get data:" . mysql_error());
} while($row = mysql_fetch_array($res)) {
while($row = mysql_fetch_array($res)) {
echo "<br><p><b>Surname: </b></b></b>", $row['name'], "</p>";
echo "<br><p><b>company: </b></b>", $row['del_company'], "</p>";
echo "<br><p><b>phone: </b></b></b></b>", $row['phone'], "</p>";
echo "<br><p><b>email: </b></b></b></b></b>", $row['email'], "</p>";
echo "<br><p><b>expert: </b><br>", $row['situation'], "</p>";
}
}
else {
echo "<p>Enter a valid ID above</p>";
}
mysql_close($connect);
?>
Change this line
echo "<br><p><b>expert: </b><br>", $row['situation'], "</p>";
to something like this:
echo "<br><p class=".$cssClass."><b>expert: </b><br>", $row['situation'], "</p>";
Before all this you need to create some logic that says if situation is whatever, then $cssClass = whatever. Then add in some CSS for each of the classes.
Something like this:
if ($row['situation'] == "horse") {$cssClass == "blue-color"};
elseif ($row['situation'] == "cow") {$cssClass == "red-color"};
else {$cssClass == "yellow-color"};
Then just define your CSS:
.blue-color{
background-color:blue;
}
ETC.

Delete li entry in database with PHP

I am working on a website where the user can enter the money he owes a friend. On one page the user can see all the entrys he made so far and should be able to delete them aswell. All entrys are inserted in a DB. For this overview page I use following structure:
<ul class="list-group">
<?php
$isEmpty = true;
while ($data = mysql_fetch_array($res)) {
if ($data['isDebt'] == 0) {
$isEmpty = false; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
<li class="list-group-item" name="Debt_ID" value="<?php echo $data['Debt_ID'] ?>"><span class="badge"><?php echo $data['value']; ?></span><?php echo $data['name']; ?>
<button name="delete" type="submit" id="delete" class="btn btn-xs btn-danger pull-right">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
</button>
</li>
</form>
<?php }
}
if ($isEmpty) { ?>
<li class="list-group-item">No debt!</li>
<?php
} ?>
</ul>
One debt entry has the following values:
Debt_ID (numeric)
Name (like "pizza from jack")
Value (the price. for example "10")
The button for each li element should delete the entry in the DB via Debt_ID. I've used the following SQL statement so far:
DELETE FROM Debt WHERE Debt_ID='$debt_ID';
In PHP it looked like this:
if (isset($_GET['delete'])) {
$debt_ID = trim($_POST['Debt_ID']);
$res = mysql_query("DELETE FROM Debt WHERE Debt_ID='$debt_ID';");
if ($res) {
$errTyp = "success";
$errMSG = "Successfully deleted";
} else {
$errTyp = "danger";
$errMSG = "Error occured";
}
}
My problem right now is that I am not able to get the Debt_ID which I've entered with PHP in the li element. Does anyone know a better approach or what I am doing wrong?
I am developping with Cloud9 so I could invite someone if interested.
When you load all the debts, you can do that with a select statement and loop through the result set. In the loop you can put the id in hidden inputs in each li element:
$sql = "SELECT debt_id, name, value FROM debts WHERE user_id = " . $user_id;
$result = $conn -> query($sql);
if ($result -> num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<li>
<span>' . $row["name"] . '</span>
<span>' . $row["value"] . '</span>
<input type="hidden" value="' . $row['debt_id'] . ' name="id-to-delete">
</li>';
}
} else {
echo "no results";
}
The delete.php file should contain:
<?php
if (isset($_POST['id-to-delete'])) {
$idToDelete = $_POST['id-to-delete'];
// sql to delete a record
$sql = 'DELETE FROM debts WHERE debt_id=' . $idToDelete;
if ($conn->query($sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
?>
After the form element simply add
<input type="hidden" name="Debt_ID" value="<?php echo $data['Debt_ID'] ?>">
Then remove the same information from the li element.
When submitting a form, input elements with a name attribute are what gets passed along to the next page.

How to get ID of a query asked long ago and post it to another table?

I have a table in data base with columns like ID,question,date. and an php page (1.php)which outputs question and date from db table and takes answer in textarea. when clicked submit, it redirects to another php page (2.php) where i m supposed to store the typed answer into another table in db.
here, my problem is how can i add question_ID to the second table in db along with answer.
1.PHP script as follows::
<div class="name">
<?php
$sql = "SELECT * FROM input";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$index = 0;
while($row = $result->fetch_assoc()) {
$index++;
?>
<div id="q">
<?php echo $row["question"]; ?> </B>
<?php
echo '<button class="add" id="add_'.$index.'"><B>Add Answer</B></button>';
echo '<form style="display:none;" name="answer_'.$index.'" method="post" action="output.php">'; // I dont think openning form from row to row would be nice!
echo '<textarea type="text" class="addtext" name="addtext" required id="addtext_'.$index.'" placeholder="Please type your answer here.." ></textarea>';
echo '<button onClick="addsubmit('.$index.');" type="submit" id="addsubmit_'.$index.'" class="addsubmit"><B>Submit</B></button>';
echo '</form>';
?>
<small><p><?php echo $row["date"]; ?></p></small>
2.PHP script as follows::
<?php include('1.php'); ?>
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "******";
$dbname = "the_database";
$addtext = $_POST['addtext'];
$date = date_default_timezone_set('Asia/Kolkata');
$date = date('d/m/Y H:i:s');
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO output (answer, date)
VALUES ('$addtext', '$date')";
if ($conn->query($sql) === TRUE) {
echo '<script language="javascript">';
echo 'alert("Your Answer has been Succesfully posted")';
echo '</script>';
echo '';
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Answer and date saved in db table successfully but got stuck in getting question_ID...
Any help is greatly Appreciated.
Add the hidden field:
on 1.php
echo '<form style="display:none;" name="answer_'.$index.'" method="post" action="output.php">'; // I dont think openning form from row to row would be nice!
echo '<input type="hidden" name="questionid" value="<?php echo $row[ID]?>"/>'
echo '<textarea type="text" class="addtext" name="addtext" required id="addtext_'.$index.'" placeholder="Please type your answer here.." ></textarea>';
echo '<button onClick="addsubmit('.$index.');" type="submit" id="addsubmit_'.$index.'" class="addsubmit"><B>Submit</B></button>';
echo '</form>';
on page 2.php
$qid = $_POST['questionid']; //get the question id and insert in the table

PHP MySQL Delete record only if it exist

Having a bit of trouble, I have created a form to deleted a record from a linked MySQL database using PHP that works, but I am having an problem with how to make an error display if a uadnumber value for example already exists.
<form name="deleterecord" action="indexdelete.php" method="post">
UAD Username: <br/><input type="text" name="uadnumber" /><br/>
<input type="submit" onclick="return deletedatabase();" value="Delete" />
</form>
<?php
// find the values from the form
$uadnumber = $_POST['uadnumber'] ;
?>
<?php
$con=mysqli_connect($db_hostname,$db_username,$db_password,$db_database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$retval = mysqli_query($con,"DELETE FROM users WHERE uadnumber='$uadnumber'");
if(!$retval<0)
{
die('Could not delete data: ' . mysql_error());
}
echo "Deleted all linked data from user $uadnumber successfully"."<br><br>";
echo "<hr>";
echo "Below is the remaining users within the database";
mysqli_close($con);
?>
if (isset($_POST["uadnumber"])) {
$uadnumber = (int)$_POST["uadnumber"];
$db = new mysqli($db_hostname,$db_username,$db_password,$db_database);
if ($db->query("SELECT uadnumber FROM users WHERE uadnumber='".$uadnumber."'")->num_rows > 0) {
if ($db->query("DELETE FROM users WHERE uadnumber='".$uadnumber."'")->affected_rows > 0) {
echo 'Desired rows have been removed.';
} else {
echo 'No rows have been removed.';
}
} else {
echo 'There are no rows identified by given value.';
}
}

Categories