I have a problem here with break and loops things in php.I have an input type, if I give the id 2 for ex, if there is 2 in db then only "You liked this url already" should be appear.This works. If I give then id 3 it says "Data added".Good for now.But if I enter again id 3 it says:
Data added!You liked this url already
and a new value of 3 is posting in the db.How to avoid this? Here is my function:
<form method="post">
Url id: <input type="text" name="urlid" id="urlid">
<input type="submit" name="givelikes" value="Give Likes">
<br />
<br />
</form>
<?php
if(isset($_POST['givelikes'])){
$urlid = $_POST['urlid'];
$con = mysqli_connect('localhost','root','root', 'db');
$user = $_SESSION['sess_user'];
$query=mysqli_query($con,"SELECT likes FROM users WHERE user='".$user."'");
$row = mysqli_fetch_array($query);
$array = explode(" ", $row['likes']);
foreach ($array as $value) {
echo $value;
echo $urlid;
if($value == $urlid){
echo "You liked this url already";
break;
}
else{
$array = $row['likes'];
$array .= " ";
$array .= "$urlid";
$query = ("Update users set likes = '".$array."' where user = '".$user."'");
if(mysqli_query($con,$query)){
echo "Data added!";
}
else{
echo "ERROR: Could not able to execute sql: " . mysqli_error($con);
}
}
}
}
?>
Currently you're looping through all "likes" and comparing them. So the sequence of steps is like this:
Enter 2
No likes yet, so the data is added
Enter 2
Loop over likes, find 2, data was already added
Enter 3
Loop over likes, find 2, not match so data is added
Enter 3
Loop over likes, find 2, not match so data is added
Continue looping, find 3, data was already added
Correcting this is going to involve changing your design a bit. Right now you have one de-normalized record with a string of space-delimited "likes". Normalize your data. Have one record per "like". And instead of constantly updating a single record, insert new records.
Then when you want to see if a "like" already exists, you can use a WHERE clause. Something like this:
SELECT * FROM users WHERE user=? AND like=?
(Note: This is using query parameters as a prepared statement. This is highly recommended. Your current code is wide open to SQL injection.)
If any record is found at all, then the item was "already liked" and you can output the message. If no record was found, INSERT a new one for that "like".
No need for a loop.
Related
I am coding a discography tool for a music database.
Artists are able to insert tracks, singles, EPs, and albums all into separate tables on the database.
Having tracks be in their own separate table allows the same tracks to be attached to multiple singles, EPs and albums while only requiring there to be one record for that track in the database.
Which means individual track pages can have an automatically generated list of links back to the Singles, EPs and albums that they appear on. Making navigating the database through the website a much smoother experience.
I have come to the point where I am coding a tool to attach any existing tracks in the database for a given artist onto an album page.
I am using another table in the database called 'trackconnections' to create the relational links between the track ids from the track table and the album id from the album table, with an additional column called albumtracknum available to be able to output the tracks in the right order when queried on the album page.
The code for the tool is behind a button labelled 'Attach existing track(s) to album'. The code for this tool is as follows:
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "includes/db_connect.pdo.php";
$artistid = $_POST["artistid"];
$albumid = $_POST["albumid"];
echo '<strong>Select each track you would like to add to this album below and type in the track number you want it to have on the album in the box underneith the name of each selected track.</strong><br><br>';
$stmt = $pdo->query("SELECT * FROM track WHERE artist_id = '$artistid'
order by trackname");
while ($row = $stmt->fetch())
{
echo '<form action="includes/attachexistingtracktoalbum.inc.php" method = "post">';
echo '<div class="checkbox">';
echo '<label>';
echo "<input type='checkbox' name='trackid[]' value='".$row['id']."' />";
echo '<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>';
echo ' '.$row['trackname'];
echo '</label>';
echo "<br><label for='albumtracknum'>Track number:</label><br>
<input type='text' name='albumtracknum[]'>
<input type='hidden' name='albumid[]' value='".$albumid,"'>
<br><br>";
echo '</div>';
}
?>
<input type="hidden" name="albumidforreturn" value="<?php echo $albumid;?>">
<button type="submit" name="attachexistingtracktoalbum-submit">Attach track(s) to album</button>
<?php }
else {
header("Location: /index.php");
exit();
}?>
(NB: The post data here is not sanitised for the sql query as it has been passed along in a hidden form from the original album page)
This generates a page with all track names for the current artist available on a list with checkboxes, with each track name being followed by a data entry box to enter the track number for the album being added to.
Submission of the form then hands off to the following include code:
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "db_connect.pdo.php";
$albumid = implode(',',$_POST['albumid']);
$trackid = implode(',',$_POST['trackid']);
$albumtracknum = implode(',',$_POST['albumtracknum']);
$albumidforreturn = $_POST['albumidforreturn'];
// echo 'albumid: '.$albumid.'<br>';
// echo 'trackid: '.$trackid.'<br>';
// echo 'albumtracknum: '.$albumtracknum.'<br>';
$sql = "INSERT INTO trackconnections (albumid, trackid, albumtracknum) VALUES (?,?,?);";
$stmt= $pdo->prepare($sql);
$stmt->execute([$albumid,$trackid,$albumtracknum]);
header("Location: ../albumdetail.php?albumid=$albumidforreturn");
exit();
}
else {
header("Location: ../index.php");
exit();
}
(NB: The commented out echos are there to test what the output is from the previous form)
The 2 problems I am having are that my 'Attach existing tracks to album' form submit:
1. Passes on too much data.
The generated form should only pass on the track ids, album number, and track numbers that have had their checkboxes ticked. For insertion into the 'trackconnections' table.
Instead it narrows down the ticked checkbox track ids only and then creates comma separated values for every available track to select, rather than just those actually selected.
Which leads to annoying outputs such as the following when passing on data from form to include:
albumid: 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4
trackid: 30,14
albumtracknum: ,2,3,,,,,,,,,,,,,,,,,,,,,
Where it should only read as:
albumid: 4,4
trackid: 30,14
albumtracknum: 2,3
Having too much data get passed through means that the row inserts won't be correct on multiple INSERTS once I do get this working, as they won't align with one another in the correct order.
2. The include only INSERTS 1 row to the 'trackconnections' table.
It seems I am misunderstanding how to add multiple rows to the database with my code here.
As having multiple checkboxes ticked on my 'Attach existing tracks to album' form only inserts 1 single row to the database on submission of the form each time.
Consistently the only track that gets added to the 'trackconnections' table is the first track with its checkbox ticked and, because of issue no. 1 above, the albumtracknum is always 0 unless I type a number into the first albumtracknum box on the available checklist.
I need to make tweaks to this code so that both problem 1 and 2 are addressed together, meaning that ticking the checkboxes & adding track numbers into each box following the track names actually adds multiple rows to the database along with their corresponding album track numbers.
I hope someone can help.
EDIT TO SHOW REFINED AND WORKING CODE:
New code for checkbox and textbox sections -
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "includes/db_connect.pdo.php";
$artistid = $_POST["artistid"];
$albumid = $_POST["albumid"];
echo '<strong>Select each track you would like to add to this album below and type in the track number you want it to have on the album in the box underneith the name of each selected track.</strong><br><br>';
$stmt = $pdo->query("SELECT * FROM track WHERE artist_id = '$artistid'
order by trackname");
echo '<form action="includes/attachexistingtracktoalbum.inc.php" method = "post">';
while ($row = $stmt->fetch())
{
echo '<div class="checkbox">';
echo '<label>';
echo "<input type='checkbox' name='trackid[]' value='".$row['id']."' />";
echo '<span class="cr"><i class="cr-icon glyphicon glyphicon-ok"></i></span>';
echo ' '.$row['trackname'];
echo '</label>';
echo "<br><label for='albumtracknumber'>Track number:</label><br>
<input type='text' name='albumtracknumber_".$row['id']."'>
<input type='hidden' name='albumid[]' value='".$albumid,"'>
<br><br>";
echo '</div>';
}
?>
<input type="hidden" name="albumidforreturn" value="<?php echo $albumid;?>">
<button type="submit" name="attachexistingtracktoalbum-submit">Attach track(s) to album</button>
</form>
<?php }
else {
header("Location: /index.php");
exit();
}
New code for the include INSERT processing -
if (isset($_POST['attachexistingtracktoalbum-submit'])) {
require "db_connect.pdo.php";
$albumid = implode(',',$_POST['albumid']);
$trackid = implode(',',$_POST['trackid']);
$albumidforreturn = $_POST['albumidforreturn'];
foreach($_POST['trackid'] as $trackidloop) {
$albumtracknum = $_POST["albumtracknumber_{$trackidloop}"];
$sql = "INSERT INTO trackconnections (albumid, trackid, albumtracknum) VALUES (?,?,?);";
$stmt= $pdo->prepare($sql);
$stmt->execute([$albumid,$trackidloop,$albumtracknum]);
}
header("Location: ../albumdetail.php?albumid=$albumidforreturn");
exit();
}
else {
header("Location: ../index.php");
exit();
}
This isn't an entire solution but I see some problems:
You are looping through tracks and creating a new form for each one. The first problem is , you are missing the closing form tag. I guess the browser is automatically creating one, when it sees the next form start tag. ?? That's why you only get one single posted checkbox.
I would put all the track checkboxes into a single form. Then the posted trackid[] array will contain all the checked items.
[EDIT after your comment: The hidden fields albumid[] post the entire array, whereas the trackid[] checkboxes only post the actual checked boxes (HTML spec).
Instead of having albumid[], You could put the trackID and albumID together for the checkbox value, then parse them apart when you handle the post:
$value = $row['id']. ',' . $row['albumid'];
echo "<input type='checkbox' name='trackid[]' value='".$value."' />";
ALSO, the SQL, "INSERT INTO (..) .. VALUES (...) " only inserts one row.
It's easy to do that SQL in a loop for all the checked boxes.
foreach($_POST['trackid'] as $value) {
// parse the $value...
// SQL Insert...
}
EDIT 2: From my own comment:
Like hidden fields, input (text) field arrays also post the entire array (with empty values for blank inputs). (Again, this is not a PHP thing, it's a web browser standard to only post checked checkboxes and radio buttons. But ALL text and hidden INPUTs are posted.) So in your example, you need to code a mechanism to know which textbox goes with each checkbox. Quick and dirty...You could add a row index (0,1,2,3...) as another comma-separated number in your checkbox values, then you'll have the index into the posted textbox array. Alternatively, you could name the textboxes ' .. name="textinput_' . $row['trackid'] . '" ...' (not an array), then upon post, read them in your foreach loop with
$val = $_POST["textinput_{$trackid}"];
How can I update a database with the values from an array? For example, let’s say we got a database with three tables:
Meals:
mealnr(PK), name, sort
Ingredients: ingredientnr(PK), name, stock
Structure: mealnr(FK), ingredientnr(FK), amount
I filled the database with some meals and ingredients. Every meal consists of multiple ingredients. The chef decides you only need 75g of ingredient x instead of 100g for meal y, so it needs to be changed in the database. Of course it can be done with SQL-commands, but I want to do it using a form in PHP.
First I made a page where all the meals are displayed. A meal can be edited using the edit-button next to it and based on the mealnr, you can change the amount of one or multiple ingredients for that particular meal. On the edit-page all the ingredient names and amounts are displayed in a table. The amount fields are textfields, those can be edited.
I made this script, but I don’t know exactly how I can update my database with the values of an array. I tried it with a foreach-loop, but it doesn't work.. yet. Can somebody help me?
<?php
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db("eatit", $conn);
$id = $_REQUEST['mealnr'];
$result = mysql_query("SELECT meals.name AS mealname, structure.amount, ingredients.name AS ingredientname
FROM Meals, Structure, Ingredients
WHERE meals.mealnr = structure.mealnr
AND structure.ingredientnr = ingredients.ingredientnr
AND meals.mealnr = '$id'");
if(isset($_POST['save']))
{
$new_amount = $_POST['amount[]'];
foreach ($new_amount as $value) {
mysql_query("UPDATE structure SET amount ='$value', WHERE mealnr = '$id'")
or die(mysql_error());
}
}
mysql_close($conn);
?>
<p><strong>Ingredients:</strong></p>
<?php
echo "<table>";
echo "<tr>";
echo "<th>Ingredient</th>";
echo "<th>Amount (gr)</th>";
echo "</tr>";
while($ingredient = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>";
echo $ingredient['ingredientname'];
echo "</td>";
echo "<td>";
echo '<input type="text" formmethod="post" name ="amount[]" value="' . $ingredient['amount'] . '" />';
echo "</td>";
echo "</tr>";
}
?>
<input type="submit" name="save" value="save" />
In your HTML markup you have declared the elements holding the name amount as an array by using amount[].
So, in your php code that receives the data it's enough to just refer to the amounts this way:
$new_amount = $_POST['amount'];
instead of:
$new_amount = $_POST['amount[]']; // in fact, this is wrong
Your foreach is fine, you should add some checks so that the $value actually contains a value that you expect, for example an int, float or not less than zero (or whatever checks you find necessary).
foreach($new_amount as $value){
if($value != '' && $value >= 1){
//sql statements goes here.
}
}
Receiving form data this way and then directly injecting the result to your SQL statement is always dangerous:
$id = $_REQUEST['mealnr'];
If you declare that you expect an integer (as the id's should be) before you directly inject the code to your SQL statement you have already written safer code.
$id = (int)$_REQUEST['mealnr'];
Also, just for the record - the mysql_* library is deprecated. As pointed out in the comments, try using PDO or mysqli instead - really!
I have two tables in mysql: a master table called "grants" and a child table called "goals". Grants has an id field as well as a bunch of others and goals has a goal name and a grant_id to link it to the grants table.
On the html form, the user can add or edit as many goals as they wish (I'm using Javascript to add new inputs). The form also gets any previous goals added and adds them to the form.
<div id="goals">
<?php
$goals = getGoalsById($_GET['id']);
if (empty($goals)) echo "<p>Goal 1: <input type='text' size='40' name='goals[]' /></p>";
else {
$i = 1;
foreach($goals as $goal) {
echo "<p>Goal {$i}: <input type='text' size='40' name=\"goals[{$goal['id']}]\" value=\"{$goal['goal']}\" /></p>";
$i++;
}
}
?>
</div>
<input type="button" value="Add goal" onClick="addInput('goals')" />
When I submit the form, I have the following statement to insert or update the goals:
foreach($goals as $key=>$goal) {
$sql_goals_add[] = "INSERT INTO goals (id, goal, grant_id) VALUES ($key,:goalnew,$grant_id) ON DUPLICATE KEY UPDATE goal = :goalupdate";
foreach ($sql_goals_add AS $sql_goal) {
$stmt_goal = $DBH->prepare($sql_goal);
$stmt_goal->bindValue(':goalnew', $goal, PDO::PARAM_STR);
$stmt_goal->bindValue(':goalupdate', $goal, PDO::PARAM_STR);
}
$stmt_goal->execute();
}
This works fine for updating existing goals as the key that is passed is the id that is in the goal table. However, the problem I run into is when they have new goals, the $goals array that gets passed from the form always starts at 0 and therefore the insert query tries to use 0, 1, 2, etc as the insert id. I'd rather have it automatically choose the next available id in the goals table.
I have tried to auto-populate what I think could be the new goal id's, but this is a bad idea as multiple people may hit the site as once and it could overlap. Any help is appreciated!
I’m going to make a few assumptions for this process to work for you.
The form in the case of a new entry is blank .
In the case of an update the form is populated from the database as
it stands.
On update the form is redisplayed from the database with a note at
the top that says the update has happened.
This is not bank data or hyper critical fault intolerant data. Which
for your application I don’t think it is. It is a form for
processing administrative data.
The Post process I suggest is a follows.
I suggest split up your insert process a little.
Insert/update into the master table. If it is an insert, grab the record Id from the crated row for use as your external key for the goals table.
Delete all entries from your goals table related to the external key. This will run even if there is no entry yet and will clear all goals should there be any. Literally rip out all rows and do a fresh insert.
Loop through the goals part of the post array using the master table’s record id as the external key for insertion. It is damn hard to keep track of the original goal record IDs for update. Because you cleared the table you don't worry with it as that data is in the post also. If the person edits the wording of a goal you don’t need to detect that to see if the goal needs updating as they are all reentered at once.
Display the form again with data pulled from the database. If there is an error and you output the result back into the form the user can always update again if there is a fault in the update process after the data is cleared from the goals table. The user will see the problem and try again if data is lost.
Again not how I handle bank data but for the form with an infinite number of goals that can be tacked on this is the easiest solution I have found.
Best of luck
So, after having the discussion over in G+, I ended up splitting things out:
1) Rename the arrays that are passed to goalsNew and goalsExisting
2) Changing the function to parse each array separately so it will perform an insert on new entries, but an update on existing entries. Below is the completed code, in case anyone cares. :)
<div id="goals">
<?php
$goals = getGoalsById($_GET['id']);
if (empty($goals)) echo "<p>Goal 1: <input type='text' size='40' name='goalsNew[]' /></p>";
else {
$i = 1;
foreach($goals as $goal) {
echo "<p>Goal {$i}: <input type='text' size='40' name=\"goalsExisting[{$goal['id']}]\" value=\"{$goal['goal']}\" /></p>";
$i++;
}
}
?>
</div>
And here is the function that does it all (and I renamed it dealingWithChildren from dealingWithGoals because this is going to be used for multiple child tables, but also because a new father should have a function called dealingWithChildren!
function dealWithChildren($childType, $childNew, $childExisting, $grant_id) {
$fieldName = substr($childType, 0, -1);
dbConnect();
global $DBH;
try {
// If there are no children at all, delete them all
if(empty($childNew) && empty($childExisting)) {
$sql_child_delete = "DELETE FROM $childType WHERE grant_id = $grant_id";
$stmt_child = $DBH->prepare($sql_child_delete);
$stmt_child->execute();
}
// If the user removed a child, delete those children
if(!empty($childExisting)) {
$sql_child_delete = "DELETE FROM $childType WHERE grant_id = $grant_id AND id NOT IN (";
$i = 0;
$len = sizeof($childExisting);
foreach($childExisting as $key=>$child) {
$sql_child_delete .= $key;
if ($len > 1 && $i < $len-1) $sql_child_delete .= ",";
$i++;
}
$sql_child_delete .= ")";
$stmt_del_child = $DBH->prepare($sql_child_delete);
$stmt_del_child->execute();
}
// If a user added any children
if(!empty($childNew)) {
foreach($childNew as $key=>$child) {
$sql_child_add[] = "INSERT INTO $childType ($fieldName, grant_id) VALUES (:childnew,$grant_id)";
foreach ($sql_child_add AS $sql_child) {
$stmt_child = $DBH->prepare($sql_child);
$stmt_child->bindValue(':childnew', $child, PDO::PARAM_STR);
}
$stmt_child->execute();
}
}
// If a user updated any children
if(!empty($childExisting)) {
foreach($childExisting as $key=>$child) {
$sql_child_update[] = "UPDATE $childType SET $fieldName = :childupdate WHERE id = $key";
foreach ($sql_child_update AS $sql_child) {
$stmt_child = $DBH->prepare($sql_child);
$stmt_child->bindValue(':childupdate', $child, PDO::PARAM_STR);
}
$stmt_child->execute();
}
}
} catch (PDOException $f) {
echo 'Database query failure: ' . $f->getMessage();
//exit;
}
dbDisconnect();
}
I've been racking my brain trying to figure out how to get this to work. Now, i'll explain it a bit better here.
What i'm trying to do is, when the user types something into a form it returns the result of the query, then using the results from that query, carry out another query on them. I'm using PHP and an oracle database.
For instance: currently I've a database full of recipes and their ingredients; and I have a form that a user can enter an ingredient into. In this example, it's bacon.
That works just fine. However, what i'm having difficulty achieving is when the user enters another ingredient, the results of the current table there and further queried. Say I enter 'cheese', all the recipes containing bacon AND cheese are then queried and displayed.
This process is easily achieved in simple SQL, however like I saw i'm having difficulty transferring it to use a form.
Now, I've an idea the solution is either something to do with temporary tables, dynamic sql or a combination of the both.
Thank you in advance for any help regarding the matter.
My code is as follows:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
}
function do_fetch($myeid, $s)
{
print '<table border="1">';
while ($row = oci_fetch_array($s, OCI_RETURN_NULLS+OCI_ASSOC)) {
print '<tr>';
foreach ($row as $item) {
print '<td>'.($item?htmlentities($item):' ').'</td>';
}
print '</tr>';
}
print '</table>';
print '<br>';
}
// Create connection to Oracle
$c = oci_connect("system", "luigi98", "localhost/XE");
// Use bind variable
$query = "SELECT DISTINCT r.recipeTitle AS recipe
FROM RECIPES.recipe r
WHERE recipeID IN(
SELECT r.recipeID
FROM recipes.recipeIng il
INNER JOIN RECIPES.ingredient i ON il.ingredientID = i.ingredientID
WHERE il.recipeID = r.recipeID
AND i.ING = :eidbv)";
$s = oci_parse($c, $query);
$myeid = $name;
oci_bind_by_name($s, ":EIDBV", $myeid);
oci_execute($s);
do_fetch($myeid, $s);
// Close the Oracle connection
oci_close($c);
?>
<p>Enter ingredient</p>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Search"><br>
</form>
There are several ways you can do that.
The easiest is probably to display your original ingredient(s) in the search box again and instruct the user to add more (separated by space, comma, etc.) ingredients if they want to.
Then you can explode your search terms on these characters and add a condition for every ingredient.
I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app.
I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present,
the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are
obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my
understanding (and guess-ology).
I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php,
etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other.
Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up)
cheers, s
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
and:
<form id="invoiceData" method="post" action="/html/form.php">
When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this:
<form
id="invoiceData"
method="post"
action="/html/form.php?ID=<?php echo $_GET['ID']; ?>"
>
This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure.
Hope this helps!
$_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to
<form id="invoiceData" method="post" action="/html/form.php?ID=12">
Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.