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. ; )
Related
My code is not appropriately editing or deleting my comments. I put my code through a syntax checker and that doesn't seem to be the problem. I have tried going through all the articles I could find and even tried multiple different methods but nothing seems to be working.
The issue is that I keep getting this error
Notice: Undefined index: id in C:\Users\Owner\Desktop\xampp\htdocs\FinalSite\edit.php on line 5
and when I click on edit the boxes will be filled with text like
Title:
<br /><b>Notice</b>: Trying to access array offset on value of type null in <b>C:\Users\Owner\Desktop\xampp\htdocs\FinalSite\edit.php</b> on line <b>20</b><br />
and Comment:
<br /><b>Notice</b>: Trying to access array offset on value of type null in <b>C:\Users\Owner\Desktop\xampp\htdocs\FinalSite\edit.php</b> on line <b>24</b><br />
I have tried multiple different ways to define id but to no avail. I have looked and implemented all the solutions I could find on StackOverflow but with no luck.
This is what I used to create the comments table:
CREATE TABLE IF NOT EXISTS `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`page_id` int(11) NOT NULL,
`parent_id` int(11) NOT NULL DEFAULT '-1',
`name` varchar(255) NOT NULL,
`content` text NOT NULL,
`submit_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
This is my code:
//This is the comments.php:
<?php
// Update the details below with your MySQL details
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'database_name';
try {
$pdo = new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS);
} catch (PDOException $exception) {
// If there is an error with the connection, stop the script and display the error
exit('Failed to connect to database!');
}
// Below function will convert datetime to time elapsed string
function time_elapsed_string($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array('y' => 'year', 'm' => 'month', 'w' => 'week', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second');
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
// This function will populate the comments and comments replies using a loop
function show_comments($comments, $parent_id = -1) {
$html = '';
if ($parent_id != -1) {
// If the comments are replies sort them by the "submit_date" column
array_multisort(array_column($comments, 'submit_date'), SORT_ASC, $comments);
}
// Iterate the comments using the foreach loop
foreach ($comments as $comment) {
if ($comment['parent_id'] == $parent_id) {
// Add the comment to the $html variable
$html .= '
<div class="comment">
<div>
<h3 class="name">' . htmlspecialchars($comment['name'], ENT_QUOTES) . '</h3>
<span class="date">' . time_elapsed_string($comment['submit_date']) . '</span>
</div>
<p class="content">' . nl2br(htmlspecialchars($comment['content'], ENT_QUOTES)) . '</p>
<a class="reply_comment_btn" href="#" data-comment-id="' . $comment['id'] . '">Reply</a>
<a href=edit.php>edit</a>
<a href=delete_confirm.php>delete</a>
' . show_write_comment_form($comment['id']) . '
<div class="replies">
' . show_comments($comments, $comment['id']) . '
</div>
</div>
';
}
}
return $html;
}
// This function is the template for the write comment form
function show_write_comment_form($parent_id = -1) {
$html = '
<div class="write_comment" data-comment-id="' . $parent_id . '">
<form>
<input name="parent_id" type="hidden" value="' . $parent_id . '">
<input name="name" type="text" placeholder="Your Name" required>
<textarea name="content" placeholder="Write your comment here..." required></textarea>
<button type="submit">Submit Comment</button>
</form>
</div>
';
return $html;
}
// Page ID needs to exist, this is used to determine which comments are for which page
if (isset($_GET['page_id'])) {
// Check if the submitted form variables exist
if (isset($_POST['name'], $_POST['content'])) {
// POST variables exist, insert a new comment into the MySQL comments table (user submitted form)
$stmt = $pdo->prepare('INSERT INTO comments (page_id, parent_id, name, content, submit_date) VALUES (?,?,?,?,?)');
$stmt->execute([ $_GET['page_id'], $_POST['parent_id'], $_POST['name'], $_POST['content'], date('Y-m-d H:i:s') ]);
exit('Your comment has been submitted! Please reload the page to view your comment.');
}
// Get all comments by the Page ID ordered by the submit date
$stmt = $pdo->prepare('SELECT * FROM comments WHERE page_id = ? ORDER BY submit_date DESC');
$stmt->execute([ $_GET['page_id'] ]);
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Get the total number of comments
$stmt = $pdo->prepare('SELECT COUNT(*) AS total_comments FROM comments WHERE page_id = ?');
$stmt->execute([ $_GET['page_id'] ]);
$comments_info = $stmt->fetch(PDO::FETCH_ASSOC);}
else {
exit('No page ID specified!');
}
?>
<div class="comment_header">
<span class="total"><?=$comments_info['total_comments']?> comments</span>
Write Comment
</div>
<?php
if($_SESSION['is_open'] = TRUE){
echo show_write_comment_form();
}else{
echo "Please login to post.";
echo "</br>";
}
if($_SESSION['is_open'] = TRUE){
echo show_comments($comments);
}else{
echo "Please login to see others comments.";
}
?>
//This is the edit.php:
<?php
// connect to SQL
require_once('includes/mysqli_connect.php');
#data preparation for the query
$id = intval($_GET["id"]);
# selects title and description fields from database
$sql = "SELECT * FROM comments WHERE id= '$'";
$result = mysqli_query($dbc,$sql) or die(mysqli_connect_error());
# retrieved by using $row['col_name']
$row = mysqli_fetch_array($result);
?>
<h3>Edit</h3>
<form action=<?="save_edit.php?id='$id'"?>enctype="multipart/form-data" method="post" name="myForm" >
<table>
<tr>
<td><b>Title</b></td>
<td><input type="text" size="70" maxlength="100" name="name" value="<?php $row['name'] ?>"></td>
</tr>
<tr>
<td><b>Description</b></td>
<td><textarea cols="80" rows="18" name="content"><?php $row['content']; ?></textarea></td>
</tr>
</table>
<input type="hidden" name="id" value="<?php $id; ?>" />
<input name="enter" type="submit" value="Edit">
</form>
//This is the save_edit.php:
<?php
require_once('includes/mysqli_connect.php');
#data preparation for the query
$id = intval($_POST["id"]);
foreach ($_POST as $key => $value) $_POST[$key] = mysqli_real_escape_string($value);
$sql = "UPDATE comments SET
name='$_POST[name]',
content='$_POST[content]',
WHERE id=$id";
if (mysqli_error()) {
die('Error: ' . mysqli_error());
}
mysqli_close($dbc);
header ("location: index.html");
?>
//This is the delete.php:
<?php
require_once('includes/mysqli_connect.php');
$id = $_GET['comments_id'];
if($_SESSION['is_open'] = TRUE) {
session_start();
echo "Welcome | " . $_SESSION['user_name'] . "!";
$query = "DELETE FROM comments WHERE id=$id";
$result = mysqli_query($dbc, $query);
if($result){
echo "<br>The selected comment has been deleted.";
} else{
echo"<br>The selected comment could not be deleted.";
}
}else {
echo "login please";
header("Location: login.php");
}
echo "<p><a href=index.html>Go back to the main page</a></p>";
mysqli_close($dbc);
?>
If you are wondering about the is_open that is how I confirm that the user is logged in before allowing them to access the forum.
In your "save_edit.php" file you are not doing anything with the SQL query. With mysqli should look something like this: $dbc->query($sql)
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.
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).
Im trying to update a field in my database by adding to the original number value that is already in there.
i have a system where staff are able to log in and update a the balance of a normal user. Currently i have a test user and staff. the users balance is set to 100. i have the following code:
<?php
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$result = $mysqli->query( "SELECT * FROM Users WHERE Username ='$searchq'");
if ($result){
//fetch result set as object and output HTML
if($obj = $result->fetch_object())
{
echo '<div class="booksearched">';
echo '<form method="POST" id = "books" action="">';
echo '<div class="book-content"><h3>Student Username: '.$obj->Username.'</h3>';
echo '<br>';
echo '<div class="book-content"><i>First Name: <b>'.$obj->FirstName.'</b></i></div>';
echo '<div class="book-desc"><i>Last Name:<b> '.$obj->LastName.'</b></i></div>';
echo '<br>';
echo '<div class="book-qty"> Current Balance<b> '.$obj->Balance.'</b></div>';
echo 'New Balance: <input type="number" name="newBalance" value = "1" min = "1" />';
echo '<br><br>';
echo '<button name="submit_btn" class="save_order">Top Up</button>';
echo '</div>';
echo '</form>';
echo '</div>';
}
}
}
$newBalance="";
$newBalance = $_POST['newBalance'];
if(isset($_POST['submit_btn']) ){
$upsql = "UPDATE users SET Balance = Balance + '$newBalance' WHERE Username='" . $obj->Username . "'";
$stmt = $mysqli->prepare($upsql);
$stmt->execute();
}
?>
Ive tried a few things however i kept getting an error saying:
( ! ) Notice: Undefined index: newBalance
Im not sure what ive done wrong.
Any idea how to fix it?
Edit: Full code
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<br>
<div id="books-wrapper">
<!-- #content to center the menu -->
<div id="content">
<!-- This is the actual menu -->
<ul id="darkmenu">
<li>Home</li>
<li>New Books</li>
<li>Search</li>
<li>Update Balance</li>
</ul>
</div>
<div id = "welcome" >
Welcome, <?=$_SESSION['Username'];?>! <br> Logout
</div>
<br><br>
<h1 id = "mainHeader" >Update a Students Balance</h1>
<br>
<div id = "balanceupdate">
<form id = "adsearch" action="updateBalance.php" method="post">
<input type="text" name ="search" placeholder="Search For a Student">
<button name="submit" value="search">Search</button>
</form>
<br>
</div>
<?php
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$result = $mysqli->query( "SELECT * FROM Users WHERE Username ='$searchq'");
if ($result){
//fetch result set as object and output HTML
if($obj = $result->fetch_object())
{
echo '<div class="booksearched">';
echo '<form method="POST" id = "books" action="">';
echo '<div class="book-content"><h3>Student Username: '.$obj->Username.'</h3>';
echo '<br>';
echo '<div class="book-content"><i>First Name: <b>'.$obj->FirstName.'</b></i></div>';
echo '<div class="book-desc"><i>Last Name:<b> '.$obj->LastName.'</b></i></div>';
echo '<br>';
echo '<div class="book-qty"> Current Balance<b> '.$obj->Balance.'</b></div>';
echo 'New Balance: <input type="number" name="newBalance" value = "1" min = "1" />';
echo '<br><br>';
echo '<button name="submit_btn" class="save_order">Top Up</button>';
echo '</div>';
echo '</form>';
echo '</div>';
}
}
}
$newBalance="";
if(isset($_POST['submit_btn']) && !empty($_POST['newBalance']) ){
$newBalance = $_POST['newBalance'];
$upsql = "UPDATE users SET Balance = Balance + '$newBalance' WHERE Username='" . $obj->Username . "'";
$stmt = $mysqli->prepare($upsql);
$stmt->execute();
}
?>
</body>
</html>
It's throwing that notice because you need to place $newBalance = $_POST['newBalance']; inside if(isset($_POST['submit_btn'])){...} and verify that it is not empty (or set).
$newBalance="";
if(isset($_POST['submit_btn']) && !empty($_POST['newBalance']) ){
$newBalance = $_POST['newBalance'];
$upsql = "UPDATE users SET Balance = Balance + '$newBalance'
WHERE Username='" . $obj->Username . "'";
$stmt = $mysqli->prepare($upsql);
$stmt->execute();
}
You can also use isset($_POST['newBalance']) instead of !empty($_POST['newBalance'])
Sidenote: You may want to add a submit type for your button.
echo '<button type="submit" name="submit_btn" class="save_order">Top Up</button>';
Yet, it may not be required; do try it if you're still experiencing problems.
Edit:
Under
echo '<div class="book-content"><h3>Student Username: '.$obj->Username.'</h3>';
add
echo '<input type="hidden" name="username" value = "'.$obj->Username.'" />';
then under
$newBalance = $_POST['newBalance'];
add
$username = $_POST['username'];
and modify your query to read as
$upsql = "UPDATE users SET Balance = Balance + '$newBalance'
WHERE Username='".$username ."'";
My quoting may be a bit off for
echo '<input type="hidden" name="username" value = "'.$obj->Username.'" />';
where you may have to change it to
echo '<input type="hidden" name="username" value = '".$obj->Username."' />';
Edit #2:
Another way to do this since you're already using sessions <?=$_SESSION['Username'];?> would be to assign a variable to it and pass it in your query.
$username = $_SESSION['Username'];
$upsql = "UPDATE users SET Balance = Balance + '$newBalance'
WHERE Username='".$username ."'";
Edit #3:
Where you have
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
replace it with
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$student = $_POST['search'];
$_SESSION['student'] = $student;
echo $_SESSION['student']; // see what echos here
then in your query, do:
$upsql = "UPDATE users SET Balance = Balance + '$newBalance'
WHERE Username='".$student ."'";
If that doesn't work, I don't know what else to do that will be of further help. My tests were conclusive and worked. Your query may be failing, I have no more ideas at this point.
Base yourself on this scenario:
$_POST['search'] = "student1";
$student = $_POST['search'];
$_SESSION['student'] = $student;
// echo $_SESSION['student'];
$student2 = $student;
echo $student2; // will echo student1
Hello my name is Patrick and this is my first question, i'm sorry but i'm not very good in PHP. probably there are more improvements but this post is for the questions. (but improvements are also welcome)
Question:
You can choose a team of 2 monsters // The monster are selected form database
The question is: if you choose 1 monster how can i fix that you can't choose the same monster on option 2?
PHP CODE:
Action of the 2 sumbit buttons
<?php
session_start();
include("header.php");
if(!isset($_SESSION['uid'])){
echo "You must be logged in to view this page!";
}else{
if (isset($_POST['save'])) {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if($Result){
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5'){
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='".$_SESSION['uid']."' ",
mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if($Result){
echo 'Team is aangepast!';
}
}
echo '';}
?>
Get the monsters form database and put it in a select list
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option4 = '';
while($row = mysql_fetch_assoc($get))
{
$option4 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
Show the selected item
<?php
$k4 = mysql_query("
SELECT user_team.m_keuze4, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze4=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row4 = mysql_fetch_assoc($k4))
{
$k4_1 = ''.$row4['m_keuze4'].' - '.$row4['monster'].' - '.$row4['type'].' - '.$row4['attack'].' - '.$row4['defense'].'';
}
?>
Option 5 is the same code as 4:
<?php
$get=mysql_query("SELECT * FROM user_monsters WHERE `id`='".$_SESSION['uid']."' ORDER BY usid ASC");
$option5 = '';
while($row = mysql_fetch_assoc($get))
{
$option5 .= '<option value = "'.$row['usid'].'">'.$row['usid'].' - '.$row['monster'].' - '.$row['type'].'</option>';
}
?>
<?php
$k5 = mysql_query("
SELECT user_team.m_keuze5, user_monsters.usid, user_monsters.monster, user_monsters.type, user_monsters.attack, user_monsters.defense
FROM user_team
INNER JOIN user_monsters
ON user_team.m_keuze5=user_monsters.usid
ORDER BY user_monsters.type;
");
while($row5 = mysql_fetch_assoc($k5))
{
$k5_1 = ''.$row5['m_keuze5'].' - '.$row5['monster'].' - '.$row5['type'].' - '.$row5['attack'].' - '.$row5['defense'].'';
}
?>
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form>
<form action="team.php" method="post">
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
In php the best you can do check the option once its posted:
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST,'option4') == filter_input(INPUT_POST,'option5')){
echo "Sorry. You can't select the same monster twice";
}else{
//your db insert logic goes here
}
}
It would be a good idea to also include some javascript to alert the user before they submit the form. This example uses jQuery
$('[name="option4"],[name="option5"]').change(function(){
if ($('[name="option4"]').val() == $('[name="option5"]').val()){
alert('you already chose that monster, please choose another');
}
});
The Form
<form action="team.php" method="post">
<select name="option4">
<?php echo $option4; ?>
</select><br><br>Keuze 4
<?php
echo $k4_1;
?><br><br>
<input type="submit" name="save" value="keuze4"/>
</form> <!-- remove this line-->
<form action="team.php" method="post"> <!-- and this line-->
<select name="option5">
<?php echo $option5; ?>
</select><br><br>Keuze 5
<?php
echo $k5_1;
?><br><br>
<input type="submit" name="save" value="keuze5"/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
$('[name="option4"],[name="option5"]').change(function () {
if ($('[name="option4"]').val() == $('[name="option5"]').val()) {
alert('you already chose that monster, please choose another');
}
});
});
</script>
Action of the 2 sumbit buttons
if (isset($_POST['save'])) {
if (filter_input(INPUT_POST, 'option4') == filter_input(INPUT_POST, 'option5')) {
echo "Sorry. You can't select the same monster twice";
} else {
if ($_POST['save'] == 'keuze4') {
$fuelQuery4 = sprintf("UPDATE user_team SET `m_keuze4` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option4']));
$Result = mysql_query($fuelQuery4);
if ($Result) {
echo 'Team is aangepast!';
}
} elseif ($_POST['save'] == 'keuze5') {
$fuelQuery5 = sprintf("UPDATE user_team SET `m_keuze5` = '%s' WHERE `id`='" . $_SESSION['uid'] . "' ", mysql_real_escape_string($_POST['option5']));
$Result = mysql_query($fuelQuery5);
if ($Result) {
echo 'Team is aangepast!';
}
}
}
}
Edit again,
Demo Fiddle of js