At the moment, I'm using a loop to read the 'questions' and 'answers' fields from my postgresql "PDPC".considerations table and reflecting them on the form. I'd like to update them all with one submit button.
I refered to PHP MySQL Multiple Forms and Multiple Submits on single page and tried using the <input type="hidden">, arrays and while loop but the form either does not execute or it does not correctly update all the forms.
I think the error is around the $_POST (at the top) and the HTML form (at the bottom). (Sorry if the codes are messy, it is my first time with PHP, HTML and Postgres). Thank you!
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$question = $answer = "";
$question_err = $answer_err = "";
// Processing form data when form is submitted
if(isset($_POST["consideration_no"]) && !empty($_POST["consideration_no"])){
$counter = 0;
// Get hidden input value
//$consideration_no = $_POST['consideration_no'];
$dg_no = $_POST['dg_no'];
$consideration_no = $_POST['consideration_no'];
$answer = $_POST['answer'];
// Check input errors before inserting in database
if(empty($answer_err)){
while ($counter<5){
// Validate address address
$input_answer = trim($_POST["answer"]);
if(empty($input_answer)){
$answer_err = "Please enter an answer.";
} else{
$answer1[$counter] = $input_answer;
}
// Prepare an update statement
$sql = 'UPDATE "PDPC".consideration SET answer=:answer WHERE consideration_no = :consideration_no';
if($stmt = $pdo->prepare($sql)){
$stmt->bindParam(":answer", $param_answer);
$stmt->bindParam(":consideration_no", $param_consideration_no);
//Set Parameter
$param_answer = $answer1[$counter];
$param_consideration_no = $consideration_no[$counter];
// Attempt to execute the prepared statement
$stmt->execute();
$counter++;
}
}
if($stmt->execute()){
// Records updated successfully. Redirect to landing page
header("location: home1.php?dm_no=".$_GET["dm_no"]);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
// Close connection
unset($pdo);
} else{
// Check existence of dg_no parameter before processing further
if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){
// Get URL parameter
$dg_no = trim($_GET["dg_no"]);
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 1)';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection1_1); //Collection Purpose Section
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
echo "<a href='considerationupdate.php?consideration_no=". $row['consideration_no'] ."' title='Update Data Map' data-toggle='tooltip'><span class='glyphicon glyphicon-pencil'></span></a>";
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="answer1[]" id = "$answer1" value="<?php echo $answer; ?>"/>
<input type="hidden" name="consideration_no[]" id = "consideration_no" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
<?php
}
?>
<input type="submit" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
unset($stmt);
// Close connection
unset($pdo);
}
else{
// URL doesn't contain dg_no parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
It should read the questions and answers from the DB table, show it on the forms as the label and text fields (working), and the user should be able to update the form after editing the text fields and clicking submit (Not working properly).
Since is your form and you are using SQL to get and the objective is to update the data with one submit?
Why not just use one form?. I belive you can do all you need with just one and multiple input.
Your branch if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){ depends on get parameters, however, your <form method="post"> of <input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/> uses post parameters.
Therefore the branch will never be executed unless the page is requested by another GET-request like a link or another form.
If the parameters can occur in both methods, POST and GET as well, you might want to check the $_REQUEST array instead. Be aware that the parameters listed in $_REQUEST can vary depending on the .ini settings request_order and variables_order.
According to your comment 'Because each form is for one table row.' in another answer, this might be an XY problem.
Consider to take the common way not generating multiple forms but array parameters similar as you did in
<input type="hidden" name="answer1[]" id = "$answer1" value="<?php echo $answer; ?>"/>
Here you rely on keys getting generated automatically. As well you can specify an individual key:
<input type="text" name="some_parameter[<?php echo $answer; ?>]">
Further more
There is an HTML line in the loop having a static id on an element:
<input type="hidden" name="consideration_no[]" id="consideration_no" value="<?php echo $consideration_no; ?>"/>
This will not break PHP, however, it is against the HTML specs saying an id has to be unique per document.
I have fixed the issue! It was the logical flow of the script. Specifically, the POST variable at the top should be changed to dg_no, add the dg_no parameters along with it, loop the parameters instead of the entire preparation script and include the execute script in the whie loop too.
Thanks for the help and guidance, they were much appreciated!
Related
I'm new to PHP, and I'm sure this is a common think to do, but 99% of the answers I have found to this involve AJAX, JQuery and/or JavaScript.
I am only allowed to use HTML/CSS and PHP in my project, so I need a working option that does not involve anything else.
I have the following setup:
index.php, this holds my form structure
insert.php, this sanitizes/validates and inserts form data into a database table
Leaving action as insert.php sends me to my insert.php page, which I want to keep private and for developer eyes only...no good.
form action=" " method="post"
// OR
form action="index.php" method="post">
Leaving action blank or as index.php keeps me on the same page, but...
I want to keep my form processing in a separate file (insert.php) and NOT on the same page, if at all possible.
Do I have any options for this that are not excessively complex in pure PHP?
Thanks for any advice.
(PS. If there's any blatant errors or poor form here, I'm all ears to constructive criticism)
Here's a snapshot of my insert.php file if its helpful. I can upload my form as well, but its very basic (just select a course, input first/last name, input student id).
// Clean the data coming from the MySQL tables
$course_clean = htmlentities($_POST['course_id']);
$stu_name_clean = htmlentities($_POST['first_last']);
$stu_id_clean = htmlentities($_POST['stu_id']);
// Escape user input coming from forms
$course = mysqli_real_escape_string($open, $_REQUEST['course_id']);
$stu_name = mysqli_real_escape_string($open, $_REQUEST['first_last']);
$stu_id = mysqli_real_escape_string($open, $_REQUEST['stu_id']);
// INSERT DATA
$insert = "INSERT IGNORE INTO enrolled (course_id, stu_id) VALUES ('$course', '$stu_id')";
if(mysqli_query($open, $insert)){
echo "Records added successfully to ENROLLED.";
} else{
echo "ERROR: Could not add records to ENROLLED. " . mysqli_error($open);
}
Something like this might be what you want:
<?php
if (!empty($_POST)) {
require "insert.php";
}
?>
<html><head></head><body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="text" name="course_id"><br/>
<input type="text" name="first_last"><br/>
<input type="text" name="stu_id"><br/>
<input type="submit">
</form>
</body></html>
It's possible to submit the page to itself and check if the $_POST is empty or not. If it's empty show the form of the page if not insert the data into the database.
<?php if (!empty($_POST)):
// Clean the data coming from the MySQL tables
$course_clean = htmlentities($_POST['course_id']);
$stu_name_clean = htmlentities($_POST['first_last']);
$stu_id_clean = htmlentities($_POST['stu_id']);
// Escape user input coming from forms
$course = mysqli_real_escape_string($open, $_REQUEST['course_id']);
$stu_name = mysqli_real_escape_string($open, $_REQUEST['first_last']);
$stu_id = mysqli_real_escape_string($open, $_REQUEST['stu_id']);
// INSERT DATA
$insert = "INSERT IGNORE INTO enrolled (course_id, stu_id) VALUES ('$course', '$stu_id')";
if(mysqli_query($open, $insert)){
echo "Records added successfully to ENROLLED.";
} else{
echo "ERROR: Could not add records to ENROLLED. " . mysqli_error($open);
}
else: ?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="text" name="course_id"><br/>
<input type="text" name="first_last"><br/>
<input type="text" name="stu_id"><br/>
<input type="submit">
</form>
<?php endif; ?>
I have displayed the data in a form edit.php and again paas the truk_id in url on update page to update.php the data of the fields but it's not working. Can anyone check this
PHP Code
<?php
$truck_id=$_GET['truck_id'];
print_r($truck_id);
include("assets/database_con.php");
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
$truck_number= mysql_real_escape_string(htmlspecialchars($_POST['truck_number']));
$truck_model= mysql_real_escape_string(htmlspecialchars($_POST['truck_model']));
$truck_make= mysql_real_escape_string(htmlspecialchars($_POST['truck_make']));
$truck_type= mysql_real_escape_string(htmlspecialchars($_POST['truck_type']));
$truck_tierweight= mysql_real_escape_string(htmlspecialchars($_POST['truck_tierweight']));
$truck_gvm= mysql_real_escape_string(htmlspecialchars($_POST['truck_gvm']));
$truck_regodate= mysql_real_escape_string(htmlspecialchars($_POST['truck_regodate']));
$truck_inspectaiondate= mysql_real_escape_string(htmlspecialchars($_POST['truck_inspectaiondate']));
$sql1 ="UPDATE add_truck SET truck_number='$truck_number', truck_model='$truck_model', truck_make='$truck_make', truck_type='$truck_type', truck_tierweight='$truck_tierweight', truck_gvm='$truck_gvm', truck_regodate='$truck_regodate', truck_inspectaiondate='$truck_inspectaiondate' where truck_id='$truck_id'";
echo $sql1;
$results=$conn->query($sql);
if($results)
{
print 'Success! record updated';
}else{
print 'no! record updated';
}
}
?>
You are assigning values to fields in single quotes.
The main string is enclosed within single quotes.
Variables inside single quotes are not parsed (value is not calculated).
This is called variable interpolation.
Use double quotes for whole string and single quotes for values.
Corrected SQL:
$sql = "UPDATE add_truck
SET truck_number='$truck_number', truck_model='$truck_model',
truck_make='$truck_make', truck_type='$truck_type',
truck_tierweight='$truck_tierweight',
truck_gvm='$truck_gvm', truck_regodate='$truck_regodate',
truck_inspectaiondate='$truck_inspectaiondate' where truck_id='$truck_id'";
you are using GET for the truck id and POST for all other variables - is this intentional?
$truck_id=$_GET['truck_id'];
should it be
$truck_id=$_POST['truck_id'];
or should all the other variables be from the GET array?
$truck_id=$_GET['truck_id'];
Here is your problem part you can't get values from get method when you submit. So you need to add some hidden field into your form like this
<input type="hidden" name="truck_id" value="<?php echo $_GET['truck_id']; ?>">
Change your code like this
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
}
I changed your code please look at this
//Your code starts now
<?php
include("header.php");
include("assets/database_con.php");
$truck_id= $_GET['truck_id'];
//print ($truck_id);
?>
<?php
//submit part in top that is better
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
$truck_number= mysql_real_escape_string(htmlspecialchars($_POST['truck_number']));
$truck_model= mysql_real_escape_string(htmlspecialchars($_POST['truck_model']));
$truck_make= mysql_real_escape_string(htmlspecialchars($_POST['truck_make']));
$truck_type= mysql_real_escape_string(htmlspecialchars($_POST['truck_type']));
$truck_tierweight= mysql_real_escape_string(htmlspecialchars($_POST['truck_tierweight']));
$truck_gvm= mysql_real_escape_string(htmlspecialchars($_POST['truck_gvm']));
$truck_regodate= mysql_real_escape_string(htmlspecialchars($_POST['truck_regodate']));
$truck_inspectaiondate= mysql_real_escape_string(htmlspecialchars($_POST['truck_inspectaiondate']));
$sql1 ="UPDATE add_truck SET truck_number='$truck_number', truck_model='$truck_model', truck_make='$truck_make', truck_type='$truck_type', truck_tierweight='$truck_tierweight', truck_gvm='$truck_gvm', truck_regodate='$truck_regodate', truck_inspectaiondate='$truck_inspectaiondate' where truck_id='$truck_id'";
echo $sql1;
die();
$results=$conn->query($sql);
if($results)
{
print 'Success! record updated';
}else{
print 'no! record updated';
}
}
?>
And changed some thing in here(added action="")
<form role="form" method="post" action="">
And changed some thing in here also(added name="submit")
<div class="form-group">
<input type="hidden" name="truck_id" value="<?php echo $_GET['truck_id']; ?>">
<input type="submit" value="submit" name="submit" class="btn_full" id="submit-booking">
</div>
No need for another div for hidden because it is 'hidden'
Used a new code as solution :
<?php
if (isset($_POST['submit']))
{
$truck_id=$_POST['truck_id'];
...
}
and one hidden value with the submit name of attribute :
<input type="hidden" name="truck_id" value="<?php echo $_GET['truck_id']; ?>">
<input type="submit" value="submit" name="submit" class="btn_full" id="submit-booking">
I have a created an HTML form where users sign up and input there data into an SQL database. I have then retrieved that data in a webpage where they can view their profile. I have created a page where users can edit there profile by creating a form which updates the value in the SQL database for there user id.
I would like the form to use the current value of the SQL cell as the default for that user to make alterations easier. Example: currently user 7 has their city set as New York, when they visits the edit info page, the city field in the form already hase New York as the default value.
I have no problem getting the SQL info and assigning it to a variable, I just don't understand how to set it as the default value. I am aware of how you set default values for input fields though.
My code:
<?php
$id = $_SESSION["user_id"];
// Create a query for the database
$query = "SELECT full_name FROM users WHERE id = $id LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response){
while($row = mysqli_fetch_array($response)){
echo $row['full_name'];
echo mysqli_error();
}
}
?>
<input type="text" name="aboutme" defualt="<?php echo $row['aboutme'] ?>" >
There's no default value for html input.
Input can has value, using attribute value:
<input type="text" name="some_name" value="Some value" />
In your case it's
<input type="text" name="aboutme" value="<?php echo $row['aboutme']?> />
Input can also has placeholder - some value that is present in an input, but erased when user starts to edit input's content:
<input type="text" name="aboutme" value="<?php echo $row['aboutme']?> placeholder="some value" />
How about
<?php
$id = $_SESSION["user_id"];
// Create a query for the database
$query = "SELECT full_name FROM users WHERE id = $id LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response){
while($row = mysqli_fetch_array($response)){
echo $row['full_name'];
?>
<input type="text" name="aboutme" value="<?php echo $row['aboutme'] ?>" >
<?php
echo mysqli_error();
}
}
?>
And here is a good example http://www.w3schools.com/php/showphpfile.asp?filename=demo_db_select_pdo
Neither of the answers worked and upon further research and trial and error I created a solution.
I changed the value that was store in the array to just be a normal php variable:
$aboutme = $row['aboutme'];
I then called that variable using the following code:
<input type="text" name="aboutme" value="<?php echo htmlspecialchars($aboutme); ?>" >
Thanks for your help.
I hope you find my answer useful.
Why don't you try using it as a place holder? This will provide editable text.
<input type="text" name="aboutme" placeholder="<?php echo $row['aboutme'];" />
I am making a form in html. When a person clicks on submit, it checks if certain fields are filled correctly, so pretty simple form so far.
However, i want to save the text which is typed into the fields, if a person refreshes the page. So if the page is refreshed, the text is still in the fields.
I am trying to achieve this using php and a cookie.
// Cookie
$saved_info = array();
$saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][',
$_COOKIE['offer_saved_info']) : array();
foreach($saved_infos as $info)
{
$info_ = trim($info, '[]');
$parts = explode('|', $info_);
$saved_info[$parts[0]] = $parts[1];
}
if(isset($_SESSION['webhipster_ask']['headline']))
$saved_info['headline'] = $_SESSION['webhipster_ask']['headline'];
// End Cookie
and now for the form input field:
<div id="headlineinput"><input type="text" id="headline"
value="<?php echo isset($_SESSION['webhipster_ask']['headline']) ?
$_SESSION['webhipster_ask'] ['headline'] : ''; ?>"
tabindex="1" size="20" name="headline" /></div>
I am new at using SESSION within php, so my quesiton is:
Is there a simpler way of achieving this without using a cookie like above?
Or what have i done wrong in the above mentioned code?
First thing is I'm pretty sure you're echo should have round brackets around it like:
echo (isset($_SESSION['webhipster_ask']['headline']) ? value : value)
That's not really the only question your asking though I think.
If you're submitting the data via a form, why not validate using the form values, and use the form values in your html input value. I would only store them to my session once I had validated the data and moved on.
For example:
<?php
session_start();
$errors=array();
if($_POST['doSubmit']=='yes')
{
//validate all $_POST values
if(!empty($_POST['headline']))
{
$errors[]="Your headline is empty";
}
if(!empty($_POST['something_else']))
{
$errors[]="Your other field is empty";
}
if(empty($errors))
{
//everything is validated
$_SESSION['form_values']=$_POST; //put your entire validated post array into a session, you could do this another way, just for simplicity sake here
header("Location: wherever.php");
}
}
if(!empty($errors))
{
foreach($errors as $val)
{
echo "<div style='color: red;'>".$val."</div>";
}
}
?>
<!-- This form submits to its own page //-->
<form name="whatever" id="whatever" method="post">
<input type="hidden" name="doSubmit" id="doSubmit" value="yes" />
<div id="headlineinput">
<input type="text" id="headline" value="<?php echo $_POST['headline'];?>" tabindex="1" size="20" name="headline" />
<!-- the line above does not need an isset, because if it is not set, it will simply not have anything in it //-->
</div>
<input type="submit" value="submit" />
</form>
I have been using PHP for a while now and I have always wondered how to represent a single form to handle updates and inserts into a database. At the present, I am using 2 seperate forms to do this and they both have basically the same information and textboxes, etc. I know there is a better way of handling this but I'm not sure what that is.
I have tried to use a single form in the past but the html mixed with the php looks terrible and is really hard to maintain. I am after "clean" and neat.
Can someone please put me on the right track.
One of the things that I have to use are POST values if the user submits the form and the validation didn't pass, the refresh should not wipe out the already entered values.
You could use a single form, with a hidden field for id. If this field is set - then you should update the $_POST['id'] record with the rest of the form. If the field is not set (that is, it has value=""), you should insert the form data to a new record.
You'll set the id field according to the action, for example /data/edit/1 will set the id field to , and/data/new` will not set value to it.
For example, your view could be
<form action="/data/edit/1">
<input type="hidden" value="<?php echo $data->id; ?>" />
<input type="text" value="<?php echo $data->name; ?>" />
</form>
In case of a new record, call your view with the following data
$data->id = '';
$data->name = '';
In case of a known record, simply init the $data object with the data
$data->id = $record_id;
$data->name = $record_name;
This is how I would probably do it without using any other frameworks/libraries etc. It is basically what Elazar Leibovich said.
<?php
//id is zero or a record id depending on whether updating or inserting
//an existing record could be edited using edit.php?id=10
//if the id GET parameter is omitted a new record will be created
$id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
$error = '';
if ($id) {
//this array would be in the same format as the one below
$record = fetchRecordFromDb($id);
} else {
$record = array( 'field1' => 'default value', 'field2' => 'some other default' );
}
//allow POST data to override what is already in the form
foreach ($record as $key => $value) {
if (isset($_POST[$key])) {
$record[$key] = $_POST[$key];
}
}
if (isset($_POST['submit'])) {
if (!validateForm()) {
$error = 'Some form error';
} else {
if ($id) {
updateRecord($id, $record);
} else {
insertRecord($record);
}
//ok, redirect somewhere else
header('Location: http://somewhere');
exit();
}
}
?>
<form method="post">
<?php echo $error; ?>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($record['field1']); ?>"><br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($record['field2']); ?>"><br />
<input type="submit" name="submit">
</form>