Delete li entry in database with PHP - 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.

Related

Undefined array key, cant understand why the php file seems to not get the value in the html form

This is just for a school project and it feels like such a simple problem but every time i google what seems to be the problem i just cant understand most of the answers
<form action="bookResults.php" method="get">
<h4>Book Search</h4>
<label for="searchType">Search Type:</label>
<select name="searchType" id="searchType">
<option value="title">Title</option>
<option value="author">Author</option>
<option value="isbn">ISBN</option>
</select><br>
<label for="searchTerm">Search Term:</label>
<input type="text" name="searchTerm"><br>
<a class="btn btn-primary" href="bookResults.php" role="button">Submit</a>
</form>
this is the form in html
<?php
if (!isset($_GET['searchType'])) {
$searchType = $_GET['searchType'];
if (!isset($_GET['searchTerm'])) {
$searchTerm = $_GET['searchTerm'];
echo $searchType;
echo $searchTerm;
if(!$searchType || $searchTerm){
echo 'You have not entered search details. Please go back and try again';
}else{
$mysqli = new mysqli('127.0.0.1:3306','zero','1234','mp7');
if ($searchType == 'title') {
$query = "select * from book where title like '%".$searchTerm."%'";
$result = $mysqli->query($query);
$resultCount = $result->num_rows;
echo "<p>Result for ".$searchType." : ".$searchTerm." </p>";
echo "<p>Number of books found: ".$resultCount."</p>";
for($ctr = 0;$ctr<$resultCount;$ctr++){
$row = $result -> fetch_assoc();
echo "<div class='card col-4'>";
echo " <div class='card-body'>";
echo " <h6>".$row['title']."</h6>";
echo " <p>By ".$row['author_name']."<br/>";
echo " ".$row['isbn']."</p>";
echo " </div>";
echo "</div>";
}
}
and this is my incomplete php code, the goal is to let the user choose with a dropdown menu between 3 categories in my book table in my database. its either they search by Author, title or isbn. But i cant even get to that part without getting this "undefined array key" error in the first few lines
EDIT: The next project i was supposed to work on involved prepared statements, the school just wanted us to use manual insertions i guess
You don't use an anchor to submit a form. You have to use a submit button. So change
<a class="btn btn-primary" href="bookResults.php" role="button">Submit</a>
to
<button class="btn btn-primary" type="submit" role="button">Submit</button>
When you use the anchor, none of the form fields are added to the URL.
You also have some problems in your PHP logic.
You can combine the tests for whether the parameters are set and properly filled in by using !empty(). You can test both parameters at once, rather than using nested if statements.
Your code is also wide open to SQL injection. You should use a prepared statement with parameters rather than substituting the variable into the SQL.
<?php
if (!empty($_GET['searchType']) && !empty($_GET['searchTerm'])) {
$searchType = $_GET['searchType'];
$searchTerm = $_GET['searchTerm'];
echo $searchType;
echo $searchTerm;
$mysqli = new mysqli('127.0.0.1:3306','zero','1234','mp7');
if ($searchType == 'title') {
$query = "select * from book where title like CONCAT('%', ?, '%')";
$statement = $mysqli->prepare($query);
$statement->bind_param("s", $searchTerm);
$statement->execute();
$result = $statement->get_result();
$resultCount = $result->num_rows;
echo "<p>Result for ".$searchType." : ".$searchTerm." </p>";
echo "<p>Number of books found: ".$resultCount."</p>";
for($ctr = 0;$ctr<$resultCount;$ctr++){
$row = $result -> fetch_assoc();
echo "<div class='card col-4'>";
echo " <div class='card-body'>";
echo " <h6>".$row['title']."</h6>";
echo " <p>By ".$row['author_name']."<br/>";
echo " ".$row['isbn']."</p>";
echo " </div>";
echo "</div>";
}
}
} else {
echo 'You have not entered search details. Please go back and try again';
}

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. ; )

html form post is not sending variable data

After clicking "delete" (submit): I can tell that it processes the form because I get the error "You forgot to select a vendor to delete.".
The form itself is generated using PHP. When I check the HTML output, I see that the values are there. But when it gets to POST, nothing carries over. I'm testing and using a local host, so other than the existing action link, I'm not sure what else I can modify.
I have the exact same code in another delete form and it works fine. I literally copied the other form to create this one and just changed the SQL/Variable names.
PHP Code:
#delete vendor
require('includes/mysqli_connect.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); //array to collect errors
//check to ensure fields are filled out
if (!empty($_POST['vendor'])) {
$vendor = trim($_POST['vendor']);
}
else {
$errors[] = "<p>You forgot to select a vendor to delete</p>";
}
if (empty($errors)) {
//insert information into appt table
$query = "UPDATE vendors_t SET active = 0 WHERE vendorID = $vendor;";
$result = mysqli_query($dbc, $query);
if($result){
echo '<div class="alert alert-success" role="alert">';
echo '<h2>Thank you!</h2>';
echo '<p> Your request to delete vendorID ' . $customerID . 'has been completed </p></div>';
} else {
echo "Error updating record: " . mysqli_error($dbc);
}
} else{
echo '<div class="alert alert-danger" role="alert"><br>';
echo '<h2>Errors Detected</h2>';
echo '<p>The following errors occured:<br/>';
foreach ($errors as $msg) {
echo "$msg<br/>\n";
}
echo '</p><p>Please try again. </p></div>';
}
}
HTML Code
<div class="container standout" >
<div class="col-lg-12">
<h2>Delete a vendor</h2>
<p> Please select a vendor to delete.</p>
</div>
<div class="row">
<form action="index.php?pagelet=deletevendor" method="post">
<div class="form-group col-md-4">
<label for="vendor">Vendors</label>
<select name="vendor" class="form-control">
<option name="vendor" selected disabled>Choose here</option>
<?php
$query = "SELECT vendorID, contactFname, contactLname, businessName FROM vendors_T WHERE active = 1;";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<option name="vendor" value="'.$row['vendorID'].'">'
.$row['vendorID'].' '.$row['businessName']
.' '.$row['contactFname'].' '.$row['contactLname']
.'</option>';
}?>
</select>
<br>
<br>
<input class="btn btn-primary" id="submit" type="submit" value="Delete">
</div>
</div>
</form>
</div>
Your option names should be the value of the vendor ID (I presume) and certainly not "vendor".
removing name="vendor" from options & removing selected both work.
After removing name="vendor" - I added selected back and it still works.
Thank you!!

Is my statement not updating because of the way I have it layed out?

This "page" is part of many that are all linked together using includes, but because I can't make it work I'm going straight to the url that relates to this exact page, and I still can't make it work, or figure out why.
What is supposed to happen, is the query checks if that stock is in the db, if it is, echo the values of the row, and if a submit button is pressed update the db based on the input values. If it's not in, echo the blank form, and if a submit button gets pressed insert into the db. I can't get either update or insert to work.
I'm going to post the entire page (minus the mysql connect,) so hopefully someone can spot an error.
<?php
$status = 'Active';
$stock = (isset($_GET['stock'])) ? $_GET['stock'] : '';
$cat = (isset($_GET['cat'])) ? $_GET['cat'] : '';
include ('../helper_content/title_data.php');
/* WHAT CATEGORY DO WE WANT? */
if($cat == "Sales") {
$table = "Titles";
if($stock) {$where = "stock = $stock";}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$status = $status;
$title_status = mysqli_real_escape_string($conn,$_POST['title_status']);
$title_number = mysqli_real_escape_string($conn,$_POST['title_number']);
$title_location = mysqli_real_escape_string($conn,$_POST['title_location']);
$title_owners = mysqli_real_escape_string($conn,$_POST['title_owners']);
$stock = $_GET['stock'];
}
}
/* Begin Main Query */
$sql5 = "SELECT * FROM `$table` WHERE $where";
$result5 = $conn->query($sql5);
if ($result5->num_rows > 0) {
// Stock exists, so submit will Update dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($update = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$update->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$update->execute();
};
if ($update->execute == TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating: " . $update->error;
}
}
// Display the HTML results
while($row5 = $result5->fetch_assoc()) {
echo "Found In Database";
// Title Number
$title_number = 'value="'.$row5['title_number'].'"';
$TitleStatus = $row5['title_status'];
$TitleLocation = $row5['title_location'];
$Owners = $row5['owners'];
}
} else {
// No Query Results Found
echo "Not Found In Database";
// Insert into dB
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if ($add = $conn->prepare("INSERT INTO `Titles` status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?")){
$add->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
$add->execute();
};
if ($add->execute == TRUE) {
echo "Record added into database";
} else {
echo "Error adding: " . $add->error;
}
}
/* End Main Query */
}
// Title Status
foreach($title_statuses as $title_status){
$selected = ($TitleStatus == $title_status) ? ' selected="selected"' : '';
$Title_status .= '<option value="'.$title_status.'"'.$selected.'>'.$title_status.'</option>';
}
// Title Location
foreach($title_locations as $title_location){
$selected = ($TitleLocation == $title_location) ? ' selected="selected"' : '';
$Title_location .= '<option value="'.$title_location.'"'.$selected.'>'.$title_location.'</option>';
}
// Prior Owners
foreach($prior_owners as $owners){
$selected = ($Owners == $owners) ? ' selected="selected"' : '';
$Owners_drop .= '<option value="'.$owners.'"'.$selected.'>'.$owners.'</option>';
}
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>?stock=<?php echo $stock; ?>">
<section class="title">
<h3>Title Info - Stock #:<?php echo $stock; ?></h3>
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" <?php echo $title_number; ?>>
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php echo $Title_status; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<?php echo $Title_location; ?>
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<?php echo $Owners_drop; ?>
</select> <a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=<?php echo $vin; ?>"><i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i></a>
</p>
</section>
<input type="submit" id="Submit" value="Submit">
</form>
I would start by organizing your code a little differently. You have one of two things that can be true: either the form was submitted (a POST request), or the page was requested via URL (a GET request). So, start with this:
<?php
# Data for dropdowns
include ('../helper_content/title_data.php');
$error = array();
$status = "Active";
$title_number = "";
$title_status = "";
$title_location = "";
$title_owners = "";
$vin = "";
# Was the form submitted via POST?
if(isset($_POST['Submit']))
{
# Yes
# Is this a new stock item?
if(empty($_POST['stock']))
{
# Yes - insert
/*
... get your variables from the $_POST array
*/
$title_number = filter_var($_POST['title_number'], FILTER_SANITIZE_STRING);
# ... repeat for other variables
if ($stmt = $conn->prepare("INSERT INTO `Titles` (`status`,`title_status`,`title_number`,`title_location`,`title_owners`) VALUES (?,?,?,?,?)"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?inserted=true');
exit();
}
else
{
$error[] = "Error adding: " . $stmt->error;
$stmt->close();
}
}
}
else
{
# No - update
$stock = $_POST['stock'];
/*
... get your variables from the $_POST array
*/
if ($stmt = $conn->prepare("UPDATE `Titles` SET status=?, title_status=?, title_number=?, title_location=?, title_owners=? WHERE stock=?"))
{
$stmt->bind_param('ssssii', $status, $title_status, $title_number, $title_location, $title_owners, $stock);
if ($stmt->execute())
{
$stmt->close();
header('Location: ./?updated=true');
exit();
}
else {
$error[] = "Error updating: " . $stmt->error;
$stmt->close();
}
}
}
}
else
{
# No - assume a GET
$status = 'Active';
$stock = $_GET['stock'];
$cat = $_GET['cat'];
if(isset($_GET['updated']))
{
$message = "Record updated";
}
else if(isset($_GET['inserted']))
{
$message = "Record added into database";
}
if($stock != "")
{
# Load the item?
$query = "SELECT * FROM `Sales` WHERE stock=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('s', $stock);
if($stmt->execute())
{
$result = $stmt->get_result();
if($result)
{
$row = $result->fetch_assoc();
$title_number = $row['title_number'];
$title_status = $row['title_status'];
$title_location = $row['title_location'];
}
}
$stmt->close();
}
}
?>
<?php if(isset($message)) : ?>
<div class="alert alert-success">
<?= $message ?>
</div>
<?php endif; ?>
<?php if(isset($error)) : ?>
<div class="alert alert-danger">
<ul>
<?php foreach($error as $err): ?>
<li><?= $err ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="POST" action="<?= $_SERVER['PHP_SELF']; ?>">
<section class="title">
<h3>Title Info - Stock #:<?= $stock; ?></h3>
<input type="hidden" name="stock" value="<?= $stock; ?>" />
<p>
<label for="title_number" class="inline-edit">Title Num</label>
<input type="text" name="title_number" id="title_number" size="20" spellcheck="false" value="<?= $title_number; ?>" />
</p>
<p>
<label for="title_status" class="inline-edit">Status</label>
<select name="title_status" id="title_status">
<option></option>
<?php foreach($title_statuses as $option): ?>
<option <?= $option == $title_status) ? 'selected="selected"' : '' ?>><?= $option ?></li>
<?php endforeach; ?>
</select>
</p>
<p>
<label for="title_location" class="inline-edit">Location</label>
<select name="title_location" id="title_location">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
</p>
<p>
<label for="title_owners" class="inline-edit">Owners</label>
<select name="title_owners" id="title_owners">
<option></option>
<!-- Repeat the same process as $title_statuses -->
</select>
<a target="_blank" href="https://www.vehiclehistory.com/paging-vin-report-data/specifications.php?vin=$vin">
<i class="fa fa-history" aria-hidden="true" title="Vehicle History"></i>
</a>
</p>
</section>
<input type="submit" id="Submit" value="Submit" />
</form>
Here's a partial re-implementation of your page. I'm starting with the assumption that a stock number was part of the requesting URL, and looking that value up. I (for the moment) am ignoring loading the dropdown values in favor of getting a basic lookup to work.
You'll also notice I've switched to using shorttags in your markup - this is generally a more concise method of templating than sprinkling echos all over the place.
I've added a partial implementation of some save logic. You'll also notice that I added a hidden input to your form - you don't want to rely on a query string value when posting a form.
The code stores some simple error messages in an array, which gets echoed out if the insert or update fails. If successful, we redirect back to the same page with a simple flag variable, which we read on that request to know if we need to display an informational message. This is known as POST-REDIRECT-GET, and prevents users from accidentally (or purposefully) resubmitting the same form data over and over.

MYSQL and PHP Loop Failure

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).

Categories