Code required to automatically update database - fix needed - php

I could really do with some help. I've successfully managed to display how many items I have in stock on my product page using PHP code with help from other members which I am most grateful for.
I'm very new to PHP and have been trying to figure this out for days.
I have a database set up with a table called 'items' which I would like to update automatically if possible. I know I can do this manually but I want to prevent over selling stock I have not got.
For instance, when a customer has placed an order I would like for this to happen:
1) Get the quantity of items in stock under 'inventory' and reduce the number by 1.
2) Have the new quantity in stock replace the old quantity displayed on my product page.
Now, I use Mals-e for my shopping cart and have all orders sent to the database with a remote call. This is working fine so no problems with info going to the database.
This is the code I use to display the quantity:
<?php
include("config.php");
mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database $DBName");
mysql_select_db($DBName) or die("Unable to select database $DBName");
// Get a specific result from the "items" table
$result = mysql_query("SELECT * FROM items
WHERE Product='Baby Girls Sock Cupcake'");
while($row = mysql_fetch_array($result))
{
echo "Available Stock: ";
echo $row['inventory'] . " " . $row['Inventory'];
}
mysql_close();
?>
This is my form code:
<?php
echo "<form action=\"http://ww6.aitsafe.com/cf/add.cfm\" method=\"post\">\n";
echo "<input type=\"hidden\" name=\"userid\" value=\"12345678\">\n";
echo "<input type=\"hidden\" name=\"id\" value=\"6\">\n";
echo "<input type=\"hidden\" name=\"scode\" value=\"ABCD123\">\n";
echo "<input type=\"hidden\" name=\"nocart\">\n";
echo "<input type=\"hidden\" name=\"return\" value=\"http://www.mysite.co.uk\">\n";
echo "<b>Qty:</b> <input type=\"text\" name=\"qty\" size=\"1\">\n";
echo "<input type=\"hidden\" name=\"product\" value=\"Socks\">\n";
echo "<input type=\"hidden\" name=\"price\" value=\"1.85\">\n";
echo "<input name=\"submit\" value=\"Add to Cart\" type=\"submit\">\n";
echo "</form>";
?>
These are other bits of code I think I may need but I don't know what to do with them or if they are really what I need:
<?php
$ud_id = $_POST['ud_id'];
$ud_scode = $_POST['ud_scode'];
$ud_product = $_POST['ud_product'];
$ud_price = $_POST['ud_price'];
$ud_inventory = $_POST['ud_inventory'];
// query update
$sql = "UPDATE items SET `items` (`ID`, `$ud_Scode`, `$ud_Product`, `$ud_Price`, `$ud_Inventory` WHERE inventory=`$ud_Inventory`)
VALUES (\'6\', \'ABC123\', \'Socks\', \'1.85\', \'2\');";
?>
I notice in this line of code:
echo "<form action=\"http://ww6.aitsafe.com/cf/add.cfm\" method=\"post\">\n";
Other people have a link to a php page:
echo "<form action=\"update.php\" method=\"post\">\n";
Does the link have to be to a php page?
I also have this:
<?php
include("config.php");
mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database $DBName");
mysql_select_db($DBName) or die("Unable to select database $DBName");
// Get a specific result from the "items" table
$result = mysql_query("SELECT * FROM items
WHERE inventory='$inventory'") or die(mysql_error());
while($row = mysql_fetch_array($result))
// check stock
if ($row !== false)
{
echo 'out of stock';
}
else if ($row['count'] == 0)
{
echo 'out of stock.';
}
// if there is stock decrease quantity
$sql = "UPDATE items SET inventory = (inventory -1) WHERE id = '6'";
$result = mysql_query;
}
mysql_close();
?>
I know it's not right and I've got it completely wrong. Could someone please point me in the right direction with an example of code that I need, as I think I need more than this to get it to work.
My htm code and php code are on separate pages, I echo the available quantity in the htm page.
Many Thanks.
This is the code that is used to update the database when an order is placed with remote call fro mals-e:
<?PHP
include("sbconf/config.php");
mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database $DBName");
mysql_select_db($DBName) or die("Unable to select database $DBName");
$order_date=time("m j y h:i");
// create varibles
$id = $_POST['id'];
$username = $_POST['username'];
$ip = $_POST['ip'];
$method = $_POST['method'];
$cart = $_POST['cart'];
$discount = $_POST['discount'];
$subtotal = $_POST['subtotal'];
$shipping = $_POST['shipping'];
$tax = $_POST['tax'];
$total = $_POST['total'];
$shipping_zone = $_POST['shipping_zone'];
$inv_name = $_POST['inv_name'];
$inv_company = $_POST['inv_company'];
$inv_addr1 = $_POST['inv_addr1'];
$inv_addr2 = $_POST['inv_addr2'];
$inv_state = $_POST['inv_state'];
$inv_zip = $_POST['inv_zip'];
$inv_country = $_POST['inv_country'];
$del_name = $_POST['del_name'];
$del_addr1 = $_POST['del_addr1'];
$del_addr2 = $_POST['del_addr2'];
$del_state = $_POST['del_state'];
$del_zip = $_POST['del_zip'];
$del_country = $_POST['del_country'];
$tel = $_POST['tel'];
$fax = $_POST['fax'];
$email = $_POST['email'];
$message = $_POST['message'];
$sd = $_POST['sd'];
// query insert
mysql_query("INSERT INTO orders (id,username,ip,date,method,cart,discount,subtotal,shipping,tax,total,shipping_zone,inv_name,inv_company,inv_addr1,inv_addr2,inv_state,inv_zip,inv_country,del_name,del_addr1,del_addr2,del_state,del_zip,del_country,tel,fax,email,message,sd)
VALUES
('$id','$username','$ip','$order_date','$method','$cart','$discount','$subtotal','$shipping','$tax','$total','$shipping_zone','$inv_name','$inv_company','$inv_addr1','$inv_addr2','$inv_state','$inv_zip','$inv_country','$del_name','$del_addr1','$del_addr2','$del_state','$del_zip','$del_country','$tel','$fax','$email','$message','$sd')");
?>
Link to mals-e I used the php_mals.zip file:
https://www.mals-e.com/tpv.php?tp=26

I don't understand what you really want. here is a corrected version of the last piece of code you gave us (i removed your comments and put mines) :
<?php
include("config.php");
mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database $DBName");
mysql_select_db($DBName) or die("Unable to select database $DBName");
$result = mysql_query("SELECT * FROM items
WHERE inventory='$inventory'") or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row !== false)
{
echo 'out of stock';
}
else if ($row['count'] == 0)
{
echo 'out of stock.';
}
// only execute this request if there is stock
else
{
$sql = "UPDATE items SET inventory = (inventory -1) WHERE id = '6'";
}
//what is this ?
//$result = mysql_query;
}
BTW? do not use mysql_ functions, they are now deprecated. have a look at mysqli (http://fr.php.net/mysqli) or pdo (http://php.net/manual/fr/ref.pdo-mysql.php).
And to answer your question
I notice in this line of code:
echo "<form action=\"http://ww6.aitsafe.com/cf/add.cfm\" method=\"post\">\n";
Other people have a link to a php page:
echo "<form action=\"update.php\" method=\"post\">\n";
Does the link have to be to a php page?
Not really, this page can be anything. The thing is that if you want to process the form inputs with php, u'll have to call a page interpreted by php. By default apache recognizes php files those which have php extensions (*.php, *.php5 ...) but you can configure it to be able to handle all extensions you want (have a look at https://stackoverflow.com/a/12021997/2806497)

Related

Switched computers and get two new mysqli_fetch_row errors.

after I managed to connect my website form to my database, I decided to try to transfer over my files to my work computer.
Initially I only had one error: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in...
However now I get an extra mysqli_fetch_row() error the same as above but the error is on a different line.
Additionally I also get the error: Undefined index: fill which I never got before. Are there any mistakes in my code? The form still works and can connect to my database.
<center><form action="fill.php" method="post">
Fill
<input type="text" id="fill"" name="fill">
<input type="submit" id ="submit" name="submit" value="Submit here!">
</form></center>
</div>
<?php
$val1 = $_POST['fill'];
$conn = mysqli_connect('localhost', 'root', '')or
die("Could not connect");
mysqli_select_db($conn, 'rfid');
$val2 = "SELECT * FROM card_refill WHERE refill = $val1";
$result1= $conn->query($val2);
$row = mysqli_fetch_row($result1);
$refill1 = $row[2];
$value = "SELECT *FROM card_credit ORDER BY id DESC LIMIT 1:";
$result = $conn->query($value);
$row = mysqli_fetch_row($result);
$refill = $row[2];
$money= $refill+$refill1;
echo $money;
$sql = "UPDATE card_credit SET value = '$money'";
if ($conn->query($sql) === TRUE) {
echo "Success";
}
else {
echo "Warning: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
</body>
</html>
You're getting that error because you use $_POST['fill'] without checking whether it's set first. It will only be set when the form is submitted, not when the form is first displayed. You need to put all the code that processes the form input into:
if (isset($_POST['submit'])) {
...
}
BTW, you can do that entire update in a single query.
UPDATE card_credit AS cc
CROSS JOIN card_refill AS cr
CROSS JOIN (SELECT * FROM card_credit ORDER BY id DESC LIMIT 1) AS cc1
SET cc.value = cr.col2 + cc1.col2
WHERE cr.refill = '$val1'
Like GolezTrol said from his comment. You're mixing object and functional notation.
Although this might not work exactly how you need it to because I don't have all the information. I have written you something I think is close to what you're looking for.
<?php
// Define the below connections via $username = ""; EXTRA....
// This is best done in a separate file.
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$val1 = $_POST['fill'];
$result1 = $conn->query("SELECT * FROM card_refill WHERE refill = '$val1' ");
$result2 = $conn->query("SELECT * FROM card_credit ORDER BY id DESC LIMIT 1:");
$refill1 = array(); // Pass Results1 Into Array
while($row = $result1->fetch_assoc()) {
$refill1[] = $row[2];
}
$refill = array(); // Pass Results2 Into Array
while($row = $result2->fetch_assoc()) {
$refill[] = $row[2];
}
/* Without an example of what data you are getting from your tables you will have to figure out what data you want from the arrays.
$money= $refill+$refill1;
echo "DEBUG: $money";
*/
// This code will not be functional until your populate the $money value.
$sql = "UPDATE card_credit SET value = '$money' ";
if ($conn->query($sql) === TRUE) {
echo nl2br("Record updated successfully"); // DEBUG
print_r(array_values($refill1)); // DEBUG
print_r(array_values($refill)); // DEBUG
echo nl2br("\n"); // DEBUG
} else { // DEBUG
echo "Error updating record: " . $conn->error; // DEBUG
echo nl2br("\n"); // DEBUG
}
$conn->close();
?>

execute mysql DELETE query on click

i'm kind of a new player in php and sql field.
i'm trying to delete identity from my persons table when clicking on the remove link (or button)
can somebody tell me what am i doing wrong?
this is my php code:
<?php
$db = new DB();
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
$sql ="SELECT f_name, phone, c.id as idc
FROM contacts as c
WHERE c.cg_id = '$cg_id'";
$result = $db->mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article>";
if(isset($_POST['idc'])){
$idco = $_POST['idc'];
$removeQuery = "DELETE FROM contacts as c WHERE id=".$idco." ";
$resultt = mysql_query($removeQuery);
if($resultt) {
header('Location: '.$_SERVER['REQUEST_URI']);
}
echo "<script>window.location.reload(true);</script>";
}
}
}else {
echo "Please edit senior profile for monitoring!";
}
?>
Try this (obviously replacing "localhost", "dbuser", "dbpassword" and "database_name" with the details for your mysql server and database):
<?php
$db = new mysqli("localhost","dbuser","dbpassword","database_name");
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
// I've moved the deletion code to BEFORE the select query, otherwise the
// query will be shown including the to-be-deleted data and it is then deleted after it is displayed
if(isset($_GET["del"])){ // <--- this was $_POST["del"] which would have been unset
$idc = $_GET["del"];
if($db->query("DELETE FROM contacts WHERE id=$idc")){
echo "deleted";
} else {
echo "fail";
}
}
$sql ="SELECT photo, f_name, phone, street, street_num, city, l_name, c.id as idc FROM contacts as c, address as a WHERE c.cg_id = '$cg_id' and a.id = c.address_id";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<article class='contact5 lior'>";
echo "<img class='CSImage' src='" .$row["photo"]."'>";
echo "<section class='generalFormTextW nameCPosition'> " .$row["f_name"]." ".$row["l_name"]."<br></section>";
echo "<section class='generalFormTextW phoneCPosition'> " .$row["phone"]."<br></section>";
echo "<section class='generalFormTextB addressCPosition'>".$row["city"].", <br> ".$row["street"]." ".$row["street_num"]. "<br></section>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article></article>";
}
}
?>
Notice that I'm changing the way you're using mysqli so that you are using it directly rather than as a member of the DB object which is the way I've seen it used elsewhere - It looks to me as if you don't actually open the database connection (although maybe you just didn't include it because it showed your password?)
**EDIT: I've changed $_POST["del"] to $_GET["del"] -- because you are setting del in a url ("contacts2.php?del=") this will be GET not POST.
**EDIT: I've moved the deletion code so that it fixes the problem where you have to refresh the page to see the data with the record deleted - previously the information was shown and THEN deleted, we want to delete THEN show.

Using PHP to submit a Vector onto MySQL to make a connection with 2 tables

i have a list of emails on a database, which are brought onto the screen, this is coming from a previous page where you choose the category to add emails into.
The idea is for the user to check in the emails he wants to add to a connecting table that will join those two.
But i seem to be having problems. I have tried editing the page where i think the problem is, which is the , but no clue as to how i should edit it.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$idcategoria = $_GET["id"];
$query = "SELECT nome,email,id FROM email";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo"<form id='formulario' name='formulario' method='post' onsubmit='return validar(this);' action='../inserir/inserirmailcat.php'>";
echo "<br>";
echo "<button type='submit'>Submeter</button>";
echo "<tr align='center'><td>Nome</td><td>Email</td><td>Adicionar a Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if($campo=="nome")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="email")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="id")
{
echo "<td><input name='nome[".$valor."]' type='checkbox' value='Adicionar'></td></tr>";
}
}
echo "<input type='hidden' name='categoria' value='".$idcategoria."'>";
echo "</form>\n";
}
echo "</table>\n";
echo"</center>";
?>
This first page receives the ID from the previous one, and it lists a series of emails, where i check out the ones i want to add to a new table. And i try to pass them through a vector.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$queryq = "SELECT id FROM email";
$resultsq = mysql_query($queryq) or die(mysql_error());
while ($rowq = mysql_fetch_assoc($resultsq)) {
foreach ($rowq as $campoq=>$valorq) {
$cat = $_POST["categoria"];
$username = $_POST['nome['.$valorq.']'];
if ($username != '')
{
$query = "INSERT INTO emailcategoria (email,categoria) VALUES ('".$username.",".$cat."')";
mysql_query($query) or die(mysql_error());
}
}
}
mysql_query($queryq) or die(mysql_error());
header("Location:../listar/listarcategoria.php");
?>
On this second page i try to add only the emails which have been selected onto a new table which will receive the email's ID and the category's ID, but it is giving me the following error "after a few different error's when i tried a diferent approach":
Notice: Undefined index: nome[8445] in C:\xampp\phpMyAdmin\trabalho\inserir\inserirmailcat.php on line 10
The error is given for all the email ID's.
UPDATED
Error is on this like
$username = $_POST['nome['".$valorq."']'];
Firstly, is it supposed to be 'nome' ?
Secondly change the syntax like this
$username = $_POST['nome['.$valorq.']'];
$username = $_POST['nome['".$valorq."']'];
Well that's wrong, as the syntax highlighting shows.
$username = $_POST['nome['.$valorq.']'];
Also, sanitise your input or (better) use prepared statements!
> xkcd

double click required to insert into database

this might be a really simple solution but I really can't figure it out. if i insert into my database I have to press the insert button twice for it to work.. My guess is that it has to do with my using of 2 forms in one file or just because I did it all in one file. please help me.
thanks
code:
<?php
/*require "link.php";*/
?>
<html>
<head>
<!--<link rel="stylesheet" type="text/css" href="css.css">--> <!-- verwijzing naar je css -->
<!--<script type="text/javascript" src="js.js"></script>-->
</head>
<header>
</header>
<article>
<div id="cards">
<?php
$host = "localhost";
$user = "root";
$pwd = "";
$db_name = "flashcards";
$link = mysqli_connect($host, $user, $pwd, $db_name)or die("cannot connect");
$array = array();
$IDarray = array();
ini_set('display_errors', 1);
error_reporting(E_ALL);
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or die(mysqli_error($link));
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
while ($rows = mysqli_fetch_assoc($sql))
{
echo "<tr id='".$rows['ID']."'><td>".$rows['Question']."</td><td><input type='text' name='Answer[]' id='V".$rows['ID']."'></input></td></tr>";
$array[] = $rows["Answer"];
$IDarray[] = $rows["ID"];
}
echo "</table><input type='submit' name='submit'></input></form>";
$i = 0;
$count = sizeof($IDarray);
if(!empty($_POST['Answer']))
{
foreach($_POST['Answer'] as $answer)
{
if (isset($_POST['Answer'])) {
if ($answer == $array[$i])
{
echo "<script>document.getElementById('".$IDarray[$i]."').style.background='green'; document.getElementById('V".$IDarray[$i]."').value='".$array[$i]."'</script>";
}
elseif ($answer !== $array[$i])
{
echo "<script>document.getElementById('".$IDarray[$i]."').style.background='red'; document.getElementById('V".$IDarray[$i]."').value='".$answer."'</script>";
$count = $count-1;
}
$i ++;
}
}echo $count." van de ".sizeof($IDarray)." goed";
if ($count == sizeof($IDarray))
{
header('Location: http://localhost:1336/php3/');
}
}
echo "</br></br>insert";
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
echo "<tr><td>vraag</td><td><input type='text' name='vraag'></input></td><td>antwoord</td><td><input type='text' name='antwoord'></input></td></tr>";
echo "</table><input type='submit' name='submitinsert' value='insert'></input></form>";
if ($_POST['vraag'] != "") {
$vraag = $_POST['vraag'];
$antwoord = $_POST['antwoord'];
mysqli_query($link, "INSERT INTO questions (Question, Answer) VALUES (".$vraag.",".$antwoord.");") or die(mysqli_error($link));
}
?>
</div>
</article>
<footer>
</footer>
</html>
The problem is you're processing the form submission in the same script as the one that generates the form. Couple that to the fact that you firsT query the DB, generate a form with what you've already stored, and then add whatever data the user may have posted, you'll never see the data you've added show up the first time 'round you submit the form.
Either move the insert queries to the top (before generating the form), or separate concerns
Let me show you what I mean:
//don't OR DIE
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or die(mysqli_error($link));
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
while ($rows = mysqli_fetch_assoc($sql))
{//build form here
}
/*
CODE HERE
*/
if ($_POST['vraag'] != "") {
//insert here, after form is generated
}
So the data you query cannot, yet, contain the submitted form data.
There are some other issues with the code, though, like or die: don't do that. Be consistent with your coding style (allman brackets + K&R in the same script is messy). Properly indent your code and this:
if ($_POST['vraag'] != "") {
}
should be:
if (isset($_POST['vraag'])) {
}
You're comparing a key of an array that may not exist to an empty string, whereas you should check if that array key exists. Use isset.
I could go on a bit, but I'll leave it at that for now. Just one more thing: again -> separrate concerns! The presentation layer (the output: HTML and such) should not contain DB connection stuff. That should be done elsewhere.
Process your form either asynchronously (as whatever is submitted gets added to the table that is already there) using AJAX, or at least, use a separate script. Having 1 script doing all the work will soon leave you crying over a mess of spaghetti code
Its not submitting twice, actually its not loading the data after insertion,
Try adding
if ($_POST['vraag'] != "") {
$vraag = $_POST['vraag'];
$antwoord = $_POST['antwoord'];
echo "are you sure?";
mysqli_query($link, "INSERT INTO questions (Question, Answer) VALUES (".$vraag.",".$antwoord.");") or die(mysqli_error($link));
}
before
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or
die(mysqli_error($link));
this will select your records after the current record is saved.

PhP - username and password validation works, however, clearing out other rows

I have a html page with the form log-in with username and password. When people enter the correct password, it will take them to the php page with their bills. If the password is incorrect, it will display the error message and then exit the program. I got the log-in function to work. However, it's also effecting my other program. Now every time i try to write something in the item/amount row, it also display the error message and exit the program. I know it has something to do with the $numresult>0 condition. When i took that condition out, my amount/item rows work, but the log-in page also allow blank entry in username/password to log in. Any idea how i can make sure that people have to enter the correct password (not a blank entries) to log in, at the same time, get my item/amount rows in the second page behave as normal? My codes are below. Sorry it's a little long.
</head>
<body style="font-family: Arial, Helvetica, sans-serif; color: black;" onload=>
<h1>My Bills</h1>
<form method=post>
<?php
//*************************************************
//Connect to Database
//*************************************************
//*************************************************
//Verify password and username
//*************************************************
$password = $_POST['password']; //retrieve variables for password and userId
$userid = $_POST['userid'];
$query = "SELECT * FROM valid_logon WHERE userid = '$userid' AND
password='$password'"; //get query from database
$result = mysql_query($query);
$numresults = mysql_num_rows($result); //get row number
$row = mysql_fetch_array($result); //get array into variable
$dbuserid = $row['userid'];
$dbpassword = $row['password'];
if ($numresults>0)
{
if ($userid == $dbuserid && $password == $dbpassword)
{
process();
}
}else{
err_msg();
}
//*************************************************
//Error message.
//*************************************************
function err_msg()
{
print "The username and/or password you have entered are invalid.";
print "</body>";
print"</html>";
exit;
}
//*************************************************
//Write out records with data if they exist.
//*************************************************
function process()
{
print "<table>";
print "<tr><th>Item</th><th>Amount</th></tr>";
$action = $_POST['action'];
if ($action == 'update')
{
$write_ctr = 1;
// Delete all rows in the table
$query = "DELETE FROM n1417_expenses ";
$result = mysql_query($query);
if (mysql_error()) {
echo("<br>MySQL Error - Cannot delete from table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
// Loop through table and insert values into the database
while (true)
{
$item_name = 'item'."$write_ctr";
$item_value = $_POST[$item_name];
$amount_name = 'amount'."$write_ctr";
$amount_value = $_POST[$amount_name];
if (empty($item_value))
{
break;
}
// Insert an item to the table
if(!is_numeric($amount_value))
{
print "<font color=red>I'm sorry, amount \"".$amount_value."\" is not a valid number.</font><br>\n";
}else{
$query = "INSERT INTO n1417_expenses (item, amount)
VALUES('".$item_value."','".$amount_value."') ";
$result = mysql_query($query);
}
if (mysql_error())
{
echo("<br>MySQL Error - Cannot insert a row into table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
$write_ctr++;
}
}
//*************************************************
//Now Select from table and Display
//*************************************************
$err_cnt = 0;
$read_ctr = 1;
$query = "SELECT item, amount FROM n1417_expenses ";
$result = mysql_query($query);
if (mysql_error()) {
echo("<br>MySQL Error- Cannot select from table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
if (!empty($result))
{
$rowresults = mysql_num_rows($result);
if ($rowresults > 0)
{
for ($read_ctr=1; $read_ctr<=$rowresults; $read_ctr++)
{
$row = mysql_fetch_array($result);
$item_value = $row['item'];
$item_name = 'item'."$read_ctr";
$amount_value = $row['amount'];
$amount_name = 'amount'."$read_ctr";
print "<tr>";
print "<td><input type=text name=$item_name value='$item_value'></td>\n";
print "<td><input type=text name=$amount_name value='$amount_value'></td>\n";
print "<td>";
print "</tr>";
$total_amt = $total_amt + $amount_value;
}
}
}
//*************************************************
//Now write the blank lines
//*************************************************
for ($i = $read_ctr; $i < $read_ctr + 2; $i++)
{
$item_name = 'item'."$i";
$amount_name = 'amount'."$i";
print '<tr>';
print "<td><input type=text name=$item_name value=''></td>\n";
print "<td><input type=text name=$amount_name value=''></td>\n";
print '</tr>';
}
print "</table>";
print "<br>Total Bills: $total_amt";
}
?>
<br><input type=submit value=Submit>
<br<br>
<!-- Hidden Action Field -->
<input type=hidden name=action value=update>
</form>
To answer the question posted, your problem appears to be that the username and password being are checked again when your user submits the form. Because the fields don't exist, the query finds zero rows, triggering your error message.
There are a number of ways of fixing your problem, one way would be to use a Session to remember that a user is logged in. This could be implemented by altering your password check as follows:
session_start();
if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in'])
{
$password = $_POST['password']; //retrieve variables for password and userId
$userid = $_POST['userid'];
$query = "SELECT * FROM valid_logon WHERE userid = '".mysql_real_escape_string($userid)."' AND
password='".mysql_real_escape_string($password)."'"; //get query from database
$result = mysql_query($query);
$numresults = mysql_num_rows($result); //get row number
$row = mysql_fetch_array($result); //get array into variable
$dbuserid = $row['userid'];
$dbpassword = $row['password'];
if ($numresults>0)
{
if ($userid == $dbuserid && $password == $dbpassword)
{
$_SESSION['logged_in'] = TRUE;
process();
}
}else{
err_msg();
}
}
I've kept the code as similar to the original as possible, but I will echo the comments above on the need to secure your SQL calls. Have a look at using PDO if possible, or at the very least start using mysql_real_escape_string as above.

Categories