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.
Related
I am trying to pass on a row ID by user click on the specified row, onto another page. I have a table with ID and info column.
code below displays the wanted row ID and info
if ($info = $stmnt2->fetch()) {
echo '<p>Your Info:</p>';
do {
echo "$info[id] . $info[review] . <a href=edit.php?edit=$info[id]>edit</a></br> </br>" ; //The info id is contained in the $info['id']
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
I want the user to be able to click on any of the rows and the selected row to pass on its ID onto another page. How do I do this?
This is the code on the other page and I want the ID on which the user clicked to replace "$info[id]" in the sql query. This replaces the whole column and not the specified row.
if(isset($_POST['id'])){
$update=$_POST['id'];
$db->exec("UPDATE infos SET info = '$update' WHERE reviewid = '$info[id]'");
}
In the edit page I have an input which the user can write to replace the selcted row (from the ID that gets passed on)
<form action="edit.php" method="POST">
<input type="text" name="id" value="">
<input type="submit" value=" Update "/>
</form>
So I want the ID that was passed from the first page to be used to replace the info row with the user input from the edit page
Pass the ID to the URL to the next page, navigate to the next page, then use $id =$_GET['id'];
Your edit=$info['id'] part is right but you're using $_POST and $_POST['id'], on the next page. The GET global is needed and it's named edit, not id
if ($info = $stmnt2->fetch()) {
echo '<p>Your Info:</p>';
do {
echo "$info[id] . $info[review] . <a href=edit.php?edit=$info[id]>edit</a></br> </br>" ; //The info id is contained in the $info['id']
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
edit.php:
if(isset($_GET['edit'])){
$update = $_GET['edit'];
$db->exec("UPDATE infos SET info = '$update' WHERE reviewid = '$info[id]'");
}
Also for future expansion and learning, read into how to do prepared statements with bound parameters if you are going to be using queries with variables built in. You're prone to sql injection currently and it's good practice to learn the newer and safer methods.
you can get the parameter value by using $_REQUEST
$update = $_REQUEST['edit'] in edit.php file
when you use $_REQUEST method you can catch both $_GET and $_POST values.
I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.
I have a little problem on database update activity.
Case study:
I created a form with PHP editing, and perform queries to retrieve the value of a record that wants to be updated. Excerpts of the script:
<?php
$row = mysql_fetch_assoc(mysql_query("SELECT id, field_1, field_2 FROM mytable WHERE id = $editid"));
?>
...
<form action="" method="post">
FIELD 1 <input type = "text" name = "f1v" value = "<? Php echo $ row ['field_1'];?>" />
FIELD 2 <input type = "text" name = "f2v" value = "<? Php echo $ row ['field_2'];?>" />
<input type="submit" />
</form>
....
// When the form posted
if ($_POST)
{
$f1v = $ _POST['f1v'];
$f2v = $ _POST['f2v'];
mysql_query("UPDATE mytable SET field_1 = '$f1v', field_2 = '$f2v' WHERE id = $editid") or die ();
// Redirect form
}
In this case I want when the form submited, there are activities to check whether there is a change in one or more fields values. Its logic approximately like this:
if ($ _POST)
{
// Compare
if the submitted value is different from the existing value in the record
{
Updated record
}
else
{
Do not update record
}
// Redirect form
}
Do you have any easy way to do it? Thank you for your help.
Don't bother checking. Just make sure the entry is valid and throw it in.
Keep two hidden fields with current values of the fields. After submitting the form check whether submitted values are different from the hidden field values.
I have the following query that I ran on my database to remove some data:
delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;
But I now need to make the a php function that runs when I press a button called clean
then print out all the subscriber data that was deleted.
Not quitesure where to start with this.
this is my html so far:
<form id="form1" name="form1" method="post" action="">
Clean subscribers:
<input type="submit" name="clean" id="clean" value="Clean" />
</form>
Any help or advice with this is very much appreciated.
C
You'll need the button to submit a form to a handler page, the handler page would then run the query, and collect+print the data.
If you don't want to refresh the page (or have your users diverted into another page), you'll want to use Ajax.
That's where you start.
Is abvious you made no effort! but I will answer you anyway.
<?php
$con = mysql_connect("serverUrl","login","password");
mysql_select_db("dbName", $con);
$result = mysql_query("SELECT * FROM subscriber, subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
while($row = mysql_fetch_array($result))
{
echo $row['subscriber.name']; //assuming you have a field {name} in your table
echo "<br />";
}
mysql_query("delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
?>
First you'll need to select the data you're about to delete.
Then you'll need to delete it and return the selected rows.
$rows = array();
mysql_connect(...);
$res = mysql_query(...select query here...);
while($row=mysql_fetch_assoc($res)) {
$rows[] = $row;
}
$res = mysql_query(...delete query here...);
return $rows;
You might not want to totally delete the subscriber. If I were you I would include a field named "deleted" or something along those lines, indicating whether or not the subscriber has been deleted. Then query according to whether or not that field is true or false.
Need a little help...
I have a basic html table with text field form in last column and a hidden field on each row of the web table. The data in this table is extracted out of a table in the database.
I want my users to be able to update one field in the database (a score) using this web form (page).
I have a hidden web form component on each row that contains the unique id of the record in the database for each row in the web page table.
I was attempting to create code that would update the entire list of entries on the web form, even if the user is not updating that particular field. (The values of the scores field are populated into the web form at the creation of the table. So if you did not update any scores, but hit the submit button, it would update the database table with the same values.)
Here’s my code: (abbreviated to save bytes…)
<?php
//Do all the database connection stuff up front
if (isset($_POST[‘score’]))
{
$student_id = $_POST[‘student_id’];
$score = $_POST['score'];
$n = count($score);
$i = 0;
echo "You have updated these student scores on this assignment. \r\n" .
"<ol>";
while ($i < $n)
{
echo "<hr><P>{$score[$i]} \r\n";
echo "<hr><P>{$student_id[$i]} \r\n";
$qry = "UPDATE assignments SET score = ".$score[$i]." WHERE student_id = " .$student_id[$i]. '"';
$result=#mysql_query($qry);
$i++;
}
}
if($result) {
header("location: member-index.php");
exit();
}else {
die("Query failed");
}
?>
Am I on the right track? Is there a better way to do what I’m attempting? All suggestions and ideas welcome!
Thank you in advance!
i'm guessing you are using
<input name="scores[]"/>
why not echo the unique id into the input name?
<input name="score[<?php echo $unique_id ?>]" />
this means in the loop, the $i would be the unique id (one less variable and less HTML).
and please use mysql_real_escape_string() when working with DB transactions. I know it's an example code but please don't forget that
Besides that, yes, you are on the right track