Problem with the Edit and Delete for my Forum page - php

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)

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

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

PHP checklist get ID and value and store it

So I have a form to add a new item to database with a checkbox as follows
So my difficulty is the checkbox. I can easily enough create the array for all items checked but I need an ID for them along with it. I've tried to think of many ways and searched a lot but I just can't think of a way to get the ID in a way that is then useable to me along with the name of the feature (checklist). Since I have to get each feature item and add it to the table houses_has_features.
<?php
$title = 'Add a new house';
require_once 'header.php';
require_once 'nav.php';
require_once 'mysqli-con.php';
$conn = new MYSQLI($hn, $un, $pw, $db);
// If house name and type is set then add them into the database
if( !empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
$house_name = $conn->real_escape_string($_POST['h_name']);
$house_type = $conn->real_escape_string($_POST['h_type']);
//show names added
echo '<b>House name: </b>'.$house_name . '<br><b> House type:</b> ' . $house_type;
$query = "INSERT INTO `house_names` (`id`, `name`) VALUES (NULL, '$house_name')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
global $house_name_id;
$house_name_id = $conn->insert_id;
$query = "INSERT INTO `house_types` VALUES ('$house_name_id', '$house_type')";
$result = $conn->query($query);
if (!$result) die ("<b class='text-danger'><p>Insert failed ERRROR: " . $conn->error. "</p>");
} else {
global $house_name_id;
$house_name_id= NULL;
}
//Start container for page content
echo '<div class="container">';
//Display an error message if house name is filled in but not house type
if ( !empty($_POST['h_name']) && empty($_POST['h_type']) || empty($_POST['h_name']) && !empty($_POST['h_type']) ) {
echo "<p class='error-text'>* Please fill in both the house name and house type *</p>";
}
$query_feat = $conn->query('SELECT * FROM features');
$rows = $query_feat->num_rows;
$features_list = $_POST['check_list'];
$feature_id = $_POST['feature_id'];
//display checked boxes.
if(isset($_POST['check_list'])) {
for ($i=0; $i<sizeof($features_list); $i++){
//echo '<br>House name id:' . $house_name_id . '<br> $_POST[] = ' . "$features_list[]";
print_r($features_list); echo '<br>';
print_r($feature_id);
}
}
// Add house form
echo <<<_END
<h1>Add a house</h1>
</div>
<div class="container">
<form action="add.php" method="post">
<p>House Name: <input type="text" name="h_name"></p>
<p>House type: <input type="text" name="h_type"></p>
<b>features:</b>
<ul class="list-group">
_END;
for ($c = 0 ; $c < $rows ; ++$c){
$query_feat->data_seek($c);
$feat = $query_feat->fetch_array(MYSQLI_NUM);
echo '<li><input type="checkbox" name="check_list[]" value="' .$feat[1]. '">'.$feat[1].'</li>';
}
echo <<<_END
<ul>
<input class="btn-primary" type="submit" value="Submit">
</form>
</div>
_END;
require_once 'footer.php';
I'm really lost on this one any help would be greatly appreciated :)
change your value of checkbox to id or anything you want.
<li><input type="checkbox" name="check_list[]" value="' .$feat[0]. '">'.$feat[1].'</li>
$feat[1] => $feat[0] or else

Duplicate entry for key 'PRIMARY

This is my database of table cart when I add product to my cart table then error occurs
Database
mysql_query($query, $db) or die(mysql_error($db));
$query = 'CREATE TABLE IF NOT EXISTS ecomm_temp_cart (
session CHAR(50) NOT NULL,
product_code CHAR(5) NOT NULL,
qty INTEGER UNSIGNED NOT NULL,
PRIMARY KEY (session, product_code),
FOREIGN KEY (product_code) REFERENCES ecomm_products(product_code)
)
ENGINE=MyISAM';
my product table
mysql_query($query, $db) or die(mysql_error($db));
$query = 'CREATE TABLE IF NOT EXISTS ecomm_products (
product_code CHAR(5) NOT NULL,
name VARCHAR(100) NOT NULL,
description MEDIUMTEXT,
price DEC(6,2) NOT NULL,
PRIMARY KEY(product_code)
)
ENGINE=MyISAM';
<?php
session_start();
require 'db.inc.php';//connection to database
?>
<html>
<head>
<title>Here is Your Shopping Cart!</title>
<style type="text/css">
th { background-color: #999;}
td { vertical-align: top; }
.odd_row { background-color: #EEE; }
.even_row { background-color: #FFF; }
</style>
</head>
<body>
<h1>Comic Book Appreciation Store</h1>
<?php
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
$session = session_id();
$query = 'SELECT
t.product_code, qty,
name, description, price
FROM
ecomm_temp_cart t JOIN ecomm_products p ON
t.product_code = p.product_code
WHERE
session = "' . $session . '"
ORDER BY
t.product_code ASC';
$result = mysql_query($query, $db) or die (mysql_error($db));
$rows = mysql_num_rows($result);
if ($rows == 1)
{
echo '<p>You currently have 1 product in your cart.</p>';
}
else
{
echo '<p>You currently have ' . $rows . ' products in your cart.</p>';
}
if ($rows > 0)
{
?>
<table style="width: 75%;">
<tr>
<th style="width: 100px;"></th><th> Item Name </th><th> Quantity </th>
<th> Price Each </th><th> Extended Price </th>
</tr>
<?php
$total = 0;
$odd = true;
while ($row = mysql_fetch_array($result))
{
echo ($odd == true) ? '<tr class="odd_row">' : '<tr class="even_row">';
$odd = !$odd;
extract($row);
?>
<td style="text-align:center;"><a href="ecomm_view_product.php?product_code=<?php
echo $product_code; ?>"><img src="images/<?php echo $product_code;
?>_t.jpg"
alt="<?php echo $name; ?>"/></a></td>
<td><a href="ecomm_view_product.php?product_code=<?php echo $product_code;
?>"><?php
echo $name; ?></a></td>
<td>
<form method="post" action="ecomm_update_cart.php">
<div>
<input type="text" name="qty" maxlength="2" size="2"
value="<?php echo $qty; ?>"/>
<input type="hidden" name="product_code"
value="<?php echo $product_code; ?>"/>
<input type="hidden" name="redirect" value="ecomm_view_cart.php"/>
<input type="submit" name="submit" value="Change Qty"/>
</div>
</form>
</td>
<td style="text-align: right;"> $<?php echo $price; ?></td>
<td style="text-align: right;"> $<?php echo number_format
($price * $qty, 2); ?>
</td>
</tr>
<?php
$total = $total + $price * $qty;
}
?>
</table>
<p> Your total before shipping is:
<strong>$<?php echo number_format($total, 2); ?></strong></p>
<form method="post" action="ecomm_checkout.php">
<div>
<input type="submit" name="submit" value="Proceed to Checkout" style="font- weight: bold;"/>
</div>
</form>
<form method="post" action="ecomm_update_cart.php">
<div>
<input type="hidden" name="redirect" value="ecomm_shop.php"/>
<input type="submit" name="submit" value="Empty Cart"/>
</div>
</form>
<?php
}
?>
<hr/>
<p><< Back to main page </p>
</body>
</html>
I have created a product web page and when I add quantity and click on add to cart then it shows duplicate error . I try to fix it but can't fix it..
> My update cart
<?php
require 'db.inc.php';
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
session_start();
$session = session_id();
$qty = (isset($_POST['qty']) && ctype_digit($_POST['qty'])) ? $_POST['qty'] : 0;
$product_code = (isset($_POST['product_code'])) ? $_POST['product_code'] : '';
$action = (isset($_POST['submit'])) ? $_POST['submit'] : '';
$redirect = (isset($_POST['redirect'])) ? $_POST['redirect'] : 'ecomm_shop.php';
switch ($action)
{
case 'Add to Cart':
if (!empty($product_code) && $qty > 0) {
$query = 'INSERT INTO ecomm_temp_cart(session, product_code, qty)
VALUES
("' . $session . '", "' .
mysql_real_escape_string($product_code, $db) . '", ' . $qty . ')';
mysql_query($query, $db) or die(mysql_error($db));
}
header('Location: ' . $redirect);
exit();
break;
case 'Change Qty':
if (!empty($product_code)) {
if ($qty > 0) {
$query = 'UPDATE ecomm_temp_cart
SET
qty = ' . $qty . '
WHERE
session = "' . $session . '" AND
product_code = "' .
mysql_real_escape_string($product_code, $db) . '"';
} else {
$query = 'DELETE FROM ecomm_temp_cart
WHERE
session = "' . $session . '" AND
product_code = "' .
mysql_real_escape_string($product_code, $db) . '"';
}
mysql_query($query, $db) or die(mysql_error($db));
}
header('Location: ' . $redirect);
exit();
break;
case 'Empty Cart':
$query = 'DELETE FROM ecomm_temp_cart
WHERE
session = "' . $session . '"';
mysql_query($query, $db) or die(mysql_error($db));
header('Location: ' . $redirect);
exit();
break;
}
?>
Your answer is signifying you already have that primary key in the table.
The primary key of the table ecomm_temp_cart is (session, product_code). So you already have a row with that session and product_code.
If you are trying to update the quantity, you should be using REPLACE instead of INSERT or simply an UPDATE statement. REPLACE can be a drop in replacement for INSERT and will delete the existing row and insert the new row, effectively overwriting it.
Another possibility is you are not using a valid product_code. From your error, the product_code is 0000. If that isn't correct, then you're probably using the default product_code for each insert.

undefined index using update statement

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

Categories