Having trouble update in PHP the code is running no errors but when I enter a amount, it doesn't update in my tables and in my database please help. By the way I took some codes in my previous program so maybe some variable codes are no appropriate in the process. Thank you.
Here's the code:
load.php
<form method="POST" action="process-load.php">
<?php
require_once('connect/connect.php');
$id = mysql_escape_string($_GET['id']);
$sql = 'SELECT * FROM cards WHERE id='.$id.' LIMIT 0, 1';
$qry = mysql_query($sql);
$data = mysql_fetch_array($qry);
$html = '';
$html .= '<div class="box">';
$html .= '<b> Card #: '.$data['cardno'].'</b><br />';
$html .= '<b>Current Balance: </b>'.$data['balance'].'<br />';
$html .= '<b>Enter Addition Load: </b><input type="text" name="load" size="5" /><br />';
$html .= '<input type="hidden" value="'.$_GET['id'].'" name="id" />';
$html .= '<input type="hidden" value="'.$data['balance'].'" name="bal" />';
$html .= '<input type="submit" value="Submit" name="submit" />';
$html .= '</div>';
echo $html;
?>
</form>
process-load.php
<?php
session_start(); //don't forget to start session or else session will not be red
if(isset($_POST['submit'])) {
require_once('connect/connect.php');
$id = mysql_escape_string($_POST['id']);
$bal = $_POST['bal'];
$load = $_POST['load'];
$select_sql = 'SELECT balance FROM cards WHERE id="'.$id.'" LIMIT 0, 1';
$qry = mysql_query($select_sql);
$data = mysql_fetch_array($qry);
$new_bal = $data['balance'] + $bal;
$sql_update = 'UPDATE cards SET balance="'.mysql_escape_string($new_bal).'" WHERE id="'.$id.'"';
$qry2 = mysql_query($sql_update);
$bill = $bal += $load;
$_SESSION['profit'] += $bill; //add total bill always to your session
if($qry2) {
?>
<script>
alert('Thank you.\n New Balance: <?php echo $bill; ?>');
window.location.href = 'index.php?page=show';
</script>
<?php
} else {
?>
<script>
alert('Failed to load card.';);
window.location.href = 'index.php?page=show';
</script>
<?php
}
mysql_close($con);
}
?>
you need to echo out this thing
echo $sql_update = 'UPDATE cards SET balance="'.mysql_escape_string($new_bal).'" WHERE id="'.$id.'"';
check what you are getting here.
Related
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. ; )
i made a simple web app that can add text to database and also can display it. I have such problem, when i added a text(it is added to database and displayed in browser) and refresh the page, in database previous value of text input is added again even if text input is empty.
after refresh
<?php
include 'config.php';
if(isset($_POST['Submit'])) {
if(strlen(trim($_REQUEST['text'])) > 0) { $conn->query("INSERT INTO Posts (Text_Post,Data) VALUES ('".$_POST['text']."','".date("Y-m-d H:i:s")."')");
$value = '';
}
$result = $conn->query("SELECT * FROM Posts ORDER BY Data DESC");
$ul = '<ul>';
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['ID_Post'];
$text = $row['Text_Post'];
$data = $row['Data'];
$ul .= '<li id="'. $id .'"> '. $text . ' </li>';
}
$ul .= '</ul>';
$lista = $ul;
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>anonim</title>
<link rel="stylesheet" type="text/css" href="style/style.css">
</head>
<body>
<?php
include 'config.php';
$result = $conn->query("SELECT * FROM Posts ORDER BY Data DESC");
$ul = '<ul>';
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['ID_Post'];
$text = $row['Text_Post'];
$data = $row['Data'];
$ul .= '<li id="'. $id .'"> '. $text . ' </li>';
}
$ul .= '</ul>';
$lista = $ul;
?>
<form name="form" action="" method="post">
<input type="text" name="text" id="text" />
<input type="submit" id="Submit" name="Submit" value="Add" />
<div id="lista">
<?php if(isset($lista)){ echo $lista; } ?>
</div>
</form>
</body>
</html>
I am working on an online shopping cart project, which requires me to be able to add a custom text input field to each item that is added to the shopping cart. However, when I attempt to insert the information for each item in the card into a database, I cannot figure out how to pass the itemtext value into my INSERT statement. How would I go about being able to pass the itemtext value from the initial item list into my database for Orderitems? The itemtext input is on line 170, and I want to pass it into the INSERT statement seen on line 83.
<?php
session_start();
$user = $_SESSION['user'];
if(!isset($user)) {
header("Location:userlogin.php");
}
$cart = $_COOKIE['WSC'];
if(isset($_POST['clear'])) {
$expire = time() -60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['id']) {
$cart .= ',' . $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if(!$cart && $_GET['id']) {
$cart = $_GET['id'];
$expire = time() +60*60*24*7*365;
setcookie("WSC", $cart, $expire);
header("Location:order.php");
}
if($cart && $_GET['remove_id']) {
$removed_item = $_GET['remove_id'];
$arr = explode(",", $cart);
unset($arr[$removed_item-1]);
$new_cart = implode(",", $arr);
$new_cart = rtrim($new_cart, ",");
$expire = time() +60*60*24*7*365;
setcookie("WSC", $new_cart, $expire);
header("Location:order.php");
}
if(isset($_POST['PlaceOrder'])) {
$email = $user;
$orderdate = date('m/d/Y');
$ordercost = $_POST['ordercost'];
$ordertype = $_POST['ordertype'];
$downcost = $_POST['downcost'];
$cardtype = $_POST['cardtype'];
$cardnumber = $_POST['cardnumber'];
$cardsec = $_POST['cardsec'];
$cardexpdate = $_POST['cardexpdate'];
$orderstatus = "Pending";
if($ordertype=="") {
$ordertypeMsg = "<br><span style='color:red;'>You must enter an order type.</span>";
}
if($cardtype=="") {
$cardtypeMsg = "<br><span style='color:red;'>You must enter a card type.</span>";
}
if($cardnumber=="") {
$cardnumberMsg = "<br><span style='color:red;'>You must enter a card number.</span>";
}
if($cardsec=="") {
$cardsecMsg = "<br><span style='color:red;'>You must enter a security code.</span>";
}
if($cardexpdate=="") {
$cardexpdateMsg = "<br><span style='color:red;'>You must enter an expiration date.</span>";
}
else {
include ('includes/dbc_admin.php');
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
$sql = "SELECT orderid FROM Orders";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$myid = $row[orderid];
}
$itemnumber = 1;
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
$itemtext = $_POST['itemtext'];
$sql= "INSERT INTO OrderItems (orderid, itemnumber, itemid, itemtype, media, itemtext, price)
VALUE ('$myid', '$itemnumber', '$row[itemid]', '$row[itemtype]', '$row[media]', '$itemtext[itemnumber]', '$row[price]')";
mysql_query($sql) or trigger_error("WHOA! ".mysql_error());
}
$itemnumber++;
}
$inserted = "<h2>Thank You!</h2> <h3>Your order has been placed.</h3>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Williams Specialty Company</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function validateForm() {
var ordercost = document.form1.ordercost.value;
var downcost = document.form1.downcost.value;
var ordertype = document.form1.ordertype.value;
var cardtype = document.form1.cardtype.value;
var cardnumber = document.form1.cardnumber.value;
var cardsec = document.form1.cardsec.value;
var cardexpdate = document.form1.cardexpdate.value;
var ordertypeMsg = document.getElementById('ordertypeMsg');
var cardtypeMsg = document.getElementById('cardtypeMsg');
var cardnumberMsg = document.getElementById('cardnumberMsg');
var cardsecMsg = document.getElementById('cardsecMsg');
var cardexpdateMsg = document.getElementById('cardexpdateMsg');
if(ordertype == ""){ordertypeMsg.innerHTML = "You must enter an order type."; return false;}
if(cardtype == ""){cardtypeMsg.innerHTML = "You must enter a card type."; return false;}
if(cardnumber == ""){cardnumberMsg.innerHTML = "You must enter a card number."; return false;}
if(cardsec == ""){cardsecMsg.innerHTML = "You must enter a security code."; return false;}
if(cardexpdate == ""){cardexpdateMsg.innerHTML = "You must enter an expiration date."; return false;}
}
</script>
</head>
<body>
<?php include('includes/header.inc'); ?>
<?php include('includes/nav.inc'); ?>
<div id="wrapper">
<?php include('includes/aside.inc'); ?>
<section>
<h2>My Cart</h2>
<table width="100%">
<tr>
<th>Catalog ID</th>
<th>Item Name</th>
<th>Price</th>
<th>Item Text</th>
<th>Actions</th>
</tr>
<?php
$cart = $_COOKIE['WSC'];
if ($cart) {
$i = 1;
$ordercost;
include('includes/dbc.php');
$items = explode(',', $cart);
foreach($items AS $item) {
$sql = "SELECT * FROM Catalog where id = '$item'";
$result = mysql_query($sql) or die("Invalid query: " . mysql_error());
while($row=mysql_fetch_assoc($result)) {
echo '<tr>';
echo '<td align="left">';
echo $row['itemid'];
echo '</td>';
echo '<td align="left">';
echo $row['itemname'];
echo '</td>';
echo '<td align="left">';
echo $row['price'];
$ordercost+=$row['price'];
$downcost = $ordercost / 10;
echo '</td>';
echo '<td align="left">';
echo '<p><input type="text" id= "itemtext" name="itemtext"></p>';
echo '</td>';
echo '<td align="left">';
echo 'Remove From Cart';
echo '</td>';
echo '</tr>';
}
$i++;
}
}
?>
</table><br />
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="submit" name="clear" value="Empty Shopping Cart">
</form>
<?php if(isset($inserted)) {echo $inserted;} else{ ?>
<form method="post" action="<?php echo $SERVER['PHP_SELF'] ?>" name="form1" onSubmit="return validateForm()">
<p>Total Price: <?php echo $ordercost;?> <input type="hidden" id="ordercost" name="ordercost" value="<?php echo $ordercost;?>"> </p>
<p>Down Cost: <?php echo number_format((float)$downcost, 2, '.', '');?> <input type="hidden" id="downcost" name="downcost" value="<?php echo number_format((float)$downcost, 2, '.', '');?>"> </p>
<p><label>Order Type:</label><br> <input type="text" id="ordertype" name="ordertype">
<?php if(isset($ordertypeMsg)) {echo $ordertypeMsg;} ?>
<br /><span id="ordertypeMsg" style="color:red"></span>
</p>
<p><label>Card Type:</label><br> <input type="text" id="cardtype" name="cardtype">
<?php if(isset($cardtypeMsg)) {echo $cardtypeMsg;} ?>
<br /><span id="cardtypeMsg" style="color:red"></span>
</p>
<p><label>Card Number:</label><br> <input type="text" id="cardnumber" name="cardnumber">
<?php if(isset($cardnumberMsg)) {echo $cardnumberMsg;} ?>
<br /><span id="cardnumberMsg" style="color:red"></span>
</p>
<p><label>Card Security Code:</label><br> <input type="text" id="cardsec" name="cardsec">
<?php if(isset($cardsecMsg)) {echo $cardsecMsg;} ?>
<br /><span id="cardsecMsg" style="color:red"></span>
</p>
<p><label>Card Expiration Date:</label><br> <input type="text" id="cardexpdate" name="cardexpdate">
<?php if(isset($cardexpdateMsg)) {echo $cardexpdateMsg;} ?>
<br /><span id="cardexpdateMsg" style="color:red"></span>
</p>
<p><input type="submit" name="PlaceOrder" value="Place Order"></p>
</form><?php }?>
</section>
</div>
<?php include('includes/footer.inc'); ?>
</body>
</html>
Update: This is your answer: change '$itemtext[itemnumber]' into '$itemtext'
This is going wrong because of the way you use quotes. (not the answer but you might want to think about it ;-) )
$sql = "INSERT INTO Orders (email, orderdate, ordercost, ordertype, downcost, cardtype, cardnumber, cardsec, cardexpdate, orderstatus)
VALUES ('$email', '$orderdate', '$ordercost', '$ordertype', '$downcost', '$cardtype', '$cardnumber', '$cardsec', '$cardexpdate', '$orderstatus')";
You should not use '$email' but -for example- ...VALUES ('".$email."',...
Learn more about this here: What is the difference between single-quoted and double-quoted strings in PHP?
On another note, your code is not safe. Please use: http://php.net/manual/en/function.mysql-real-escape-string.php
Example:
...VALUES ('".mysql_real_escape_string($email)."',...
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
I'm currently just coding around in my free time and follow up some random tutorials that other developers/coder's created in there spare time. Now I'm stuck with something very small. I have been trying to find a answer on the interwebz but I cant seem to find one, so here I'm hoping that someone is willing to read my PHP and HTML and see the error I created.
But before I share my code let me tell you what my problem is and what I try to achieve.
If you go to the following link "removed because problem is solved." and when you click on Home/About/Service/Random, you are able to edit one of these menu's. (title, posistion, visible). Now when I want to change the menu name "Home" to "Welcome" it correctly execute my SQL but for some reason, in the HTML Form it loads it's previous information. What I can do is copy the PHP and save it in a new php file and when clicking on submit it will change both menu/title/html form at the same time, but it wont show my succes and fail message anymore. I hope any of you understand what I'm trying to explain here and try to achieve. Now lets share the code.
PHP
<? find_selected_page(); ?>
<?
if (intval($_GET['info']) == 0){
redirect_to("content.php");
}
if(isset($_POST['submit'])){
$errors = array();
$required_fields = array('menu', 'position', 'visible');
foreach ($required_fields as $fieldname){
if (!isset($POST[$fieldname]) || (empty($_POST[$fieldname]) &&
!is_numeric($_POST[$fieldname]))) {
$errors [] = $fieldname;
}
}
$fields_with_lengths = array('menu' => 30);
foreach($fields_with_lengths as $fieldname => $maxlength) {
if(strlen(trim(mysql_prep($_POST[$fieldname]))) > $maxlength){
$errors[] = $fieldname;
}
}
$id = mysql_prep($_GET['info']);
$menu = mysql_prep($_POST['menu']); //use post array cuz we used post var to coll val in form
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$query = "UPDATE information SET menu = '{$menu}', position = {$position}, visible = {$visible} WHERE id = {$id}";
$result = mysql_query($query, $connection);
if (mysql_affected_rows() == 1) {
$message = "The information was correctly updated.";
} else {
//failed
}
} else { //errors
}
?>
HTML
<? require_once ("includes/functions.php"); ?>
<? require_once ("includes/connect.php"); ?> //HERE IS MY CONNECTION TO MY DATABASE
///HERE IS MY PHP CODE
<? include ("includes/header.php"); ?>
<div id="content"> <!-- content here -->
<table id="table">
<tr>
<td id="nav">
<? echo navigation($sel_table1, $table2); ?>
</td>
<td id="main">
<h2>Edit Info <? echo $sel_table1['menu']; ?></h2>
<? if (!empty($message)) { echo "<p class=\"message\">" . $message . "</p>";} ?>
<form action="edit_info.php?info=<? echo urlencode($sel_table1['id']); ?>" method="post"/>
<p>Menu title
<input type="text" name="menu" value="<? echo ($sel_table1['menu']); ?>" id="menu">
</p>
<p>Position
<select name="position">
<?
$info_set = get_all_info();
$info_count = mysql_num_rows($info_set); //asks how many rows there are should be 3
for($count=1; $count <= $info_count+1; $count++){
echo "<option value='{$count}'";
if($sel_table1['position'] == $count){
echo "selected";
}
echo ">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0"
<? if ($sel_table1['visible'] == 0){ echo "checked"; } ?>
/>No
<input type="radio" name="visible" value="1"
<? if ($sel_table1['visible'] == 1){ echo "checked"; } ?>
/>Yes
</p>
<input type="submit" name='submit' value="Edit information" />
</form> <br>
Cancel
</td>
</tr>
</table>
</div>
<? include ("includes/footer.php");?> //HERE I HAVE IF ISSET MYSQL CLOSE
And a more simple short version of the story is, I want to update the menu's with the success and failure message's without getting the old previous data in my HTML FORM
if needed for any reasons I have included the part of my functions.php where $sel_table and $table2 are staying.
function find_selected_page(){
global $sel_table1;
global $table2;
if (isset($_GET['info'])){
$sel_table1 = get_info_by_id($_GET['info']);
$sel_t2 = 0;
$table2 = NULL;
} else if (isset($_GET['page'])){
$table1 = 0;
$sel_table1 = NULL;
$table2 = get_pages_by_id($_GET['page']);
} else {
$table1 = NULL;
$sel_table1 = NULL;
$table2 = 0;
}
}
function navigation($sel_table1, $table2){
$output = "<ul class='info'>";
$info_set = get_all_info();
while ($info = mysql_fetch_array($info_set))
{
$output .= "<li"; if ($info["id"] == $sel_table1 ["id"]){
$output .= " class='selected'";
}
$output .= "><a href='edit_info.php?info=" . urlencode($info["id"]) . "'>{$info['menu']}</a></li>";
$page_set = get_pages_for_info($info["id"]);
$output .= "<ul class='pages'>";
while ($page = mysql_fetch_array($page_set))
{
$output .= "<li"; if ($page["id"] == $table2 ["id"]){
$output .= " class='selected'";
}
$output .= "><a href='content.php?page=" . urlencode($page["id"]) . "'>{$page['menu']}</a></li>"; }
$output .= "</ul>";
}
$output .= "</ul>";
return $output;
}