Populate HTML Form from Database - php

So I have searched for how to insert items from a MySQL database into a form. From what I understand, for each field, I need to add value="<?php echo htmlentities($Variable); ?>" is there a way to insert the fields all at once? Like in a PHP script? Each field already has a name identifier, that's how the insert.php insert the values into the database, like this:
//SQL Query to insert data
$sql="INSERT INTO case_info (Volunteer,CaseShortTitle,CaseNumber,HearingDate...)
VALUES ('$_POST[Volunteer]','$_POST[CaseShortTitle]','$_POST[CaseNumber]','$_POST[HearingDate]'...)
and the form fields look like this:
<div><input type="text" id="p1f5c" name="CaseShortTitle" class="fieldcontent"><div class="fielderror"></div></div>
Then the Submit button goes to this insert.php file
Is there a way to use GET to populate the fields in this manner?
Thank you!

It's generally bad practice to input data into your database directly from the $_POST variables, you should consider sanitizing them first.
If I understand what you are asking, you can do something like this;
<form action="" id="myForm" title="myForm">
<?php
$query = "SELECT * FROM case_info LIMIT 1";
$result = myqsl_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
?>
<input type="text" id="volunteer" value="<?php echo $row['Volunteer']; ?>"
<input type="text" id="CaseShortTitle" value="<?php echo $row['CaseShortTitle']; ?>"
<?php
} //Close while{} loop
?>
</form>

Related

Process PHP form on hidden page, but stay on same page. No Ajax, pure php only (project)

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; ?>

Using a PHP variable as a form fields default value

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'];" />

Php: updating database with values from dynamically generated form fields

How do I save the following form?
<form name="myform">
<input type="text" name="title" value="title" />
$result = mysql_query("SELECT id, text from details where parent='$parent'
order by id asc") or die('Error');
while(list($id,$ftext) = mysql_fetch_row($result)) {
?>
<textarea name="formfield<?php echo $id;?>" id="<?php echo $id;?>">
<?php echo $ftext;?>
</textarea>
<?php
}
</form>
As you can see above, the MySQL query will load data and dynamically create textareas:
<textarea name="formfield34" id="34">text</textarea>
<textarea name="formfield56" id="56">more text</textarea>
<textarea name="formfield78" id="78">anothet text</textarea>
I need to update database like this:
$result = mysql_query("UPDATE details SET text='$formfield34' WHERE id ='34'") or die('Error');
$result = mysql_query("UPDATE details SET text='$formfield56' WHERE id ='56'") or die('Error');
$result = mysql_query("UPDATE details SET text='$formfield78' WHERE id ='78'") or die('Error');
The problem is that each form will have a different number of textareas loaded dynamically and different $ids. I can not imagine hot to save this form.
Thanks.
What you probably need to do is to look at using array notation in your form field names like this:
<textarea name="formfield[34]" id="34">text</textarea>
<textarea name="formfield[56]" id="56">more text</textarea>
<textarea name="formfield[78]" id="78">anothet text</textarea>
PHP will automatically build an array in $_POST['formfield']. that you can access with all this data. This make it easy to loop through this array and generate SQL for your updates.
foreach($_POST['formfield'] as $key => $value) {
// write SQL here
}
Now, rather than a bunch of individual SQL queries, you might want to consider using REPLACE syntax so that you can insert/update your data with a single query.
in the "while" while creating the textarea save an array with the id of these textarea.
Then retrace the array to use ids when you need it

How to use multiple forms to submit unique data PHP/MySQL

The way I've structured my form data is by creating them in a while loop, but each time they are created the form will take a unique id.
So my question is, how do I access them individually and update specified data to a MYSQL server.
I've attempted to do it in the code at the end of the script, but I'm not sure how to access the forms individually
<?php
include 'user_data.php';
include 'core.inc.php';
$query = mysql_query("SELECT `post_text` FROM `posts`,`sub_posts` WHERE sub_posts.post_id = posts.id AND sub_posts.user_id='$user_id'");
while($row = mysql_fetch_array($query)){
?><?php echo $row[post_text].'<br>'?>
<form action="<?php $curent_file ?>" method="POST">
<textarea name="answer_field" > </textarea><br />
<input type="submit" value="Submit Answer">
<input type="hidden" name="post_id" value="<?php echo $row['post_id']; ?>" />
</form>
<?php
}//While Loop
if (isset($_POST['answer_field']) && !empty($_POST['answer_field'])){
$answer = mysql_real_escape_string($_POST['answer_field']);
$id = intval($_POST ['post_id']);
$query = "UPDATE `sub_posts` SET `sub_answer`='$answer' WHERE `post_id`='$id'";
}
?>
Only a single form gets posted when clicking the "submit" field. The form name does not get submitted by itself. Instead, you would place the post ID to which the form corresponds as a hidden field:
<input type="hidden" name="post_id" value="<?php echo $row['post_id']; ?>" />
And then later:
$answer = mysql_real_escape_string ($_POST ['answer']);
$id = intval ($_POST ['post_id']);
$query = "UPDATE `sub_posts` SET `sub_answer`='{$answer}' WHERE `post_id`={$id}";
Note that you definitely need to escape the answer before putting it in the query and make sure that the ID is a number. Otherwise, you're opening up your code to SQL injection attacks.

List option values fail to insert into the database

I've created a php form to insert values into a database.
One of my form options is a dynamic list populated with fields from another table.
I first created the form without the dynamic option, and all data inserted just fine (and still does).
Now I'm attempting to include the code below, and while it displays the option values properly, the value fails to insert. Any advice?
<?php
/*
* LIST ALL CATEGORIES
****************************************/
include('../dbconnection.php');
$query = 'SELECT category_id, category_name FROM ingredient_categories';
$result = mysql_query($query);
echo '<select>';
while ($ingredientCategoryOption = mysql_fetch_array($result)) {
echo '<option value="'.$ingredientCategoryOption[category_id].'">'.$ingredientCategoryOption[category_name].'</option>';
}
echo '</select>';
?>
I had created something similar yesterday. The $polls array is passed to the view in CodeIgniter in the $this->load->view('poll.php', $data['polls']), while you do it in the page itself. However, you can have the general idea.
<FORM id="formPoll" class="question" name="createpoll" action="<?php echo base_url()?>index.php/poll/selectOption/" method="POST">
<select name="poll_list">
<?php
foreach($polls as $poll){
echo "<option name='poll_table'>$poll->name</option>";
}
?>
</select>
<div id="input">
Poll name: <input type="text" name="name"></input>
Title: <input type="text" name="title"></input>
</div>
<div id="options">
Option: <input type="text" name="option"></input>
</div>
<input type="submit"></input>
</FORM>
Some ideas:
Check if $results is not empty before using it
Give your <select> form a name, as I showed above
Check if $ingredientCategoryOption is not null or is something returned.
Check your database connection

Categories