I need to update multiple records into a database on submit of a form. The form fields are repeating showing all the values but, the code doesn't seem to do anything. When someone hits submit, for each dataID presented in the hidden field, the progress and last_modified_date fields should be updated. I have googled and can't seem to find an answer anywhere. Any help would be appreciated. Thanks
Here is the update code:
if(isset($_POST['dataID'])){
foreach($_POST['dataID'] as $updateid){
$progress = $_POST['progress_'.$updateid];
$last_modified_date = $_POST['last_modified_date_'.$updateid];
$updateUser = "UPDATE data SET
progress='".$progress."',last_modified_date='".$last_modified_date."'
WHERE dataID=".$updateid;
mysqli_query($sdpc_i,$updateUser);
}
}
}
?><form method="post" name="form1" enctype="multipart/form-data">
<select title="progress" name="progress[]" id="progress" class="form-control form-control-sm-3">
<option selected value="">Select One</option>
<option value="Contract Sent">Contract Sent</option>
<option value="Approved">Approved</option>
<option value="With Legal">With Legal</option>
<option value="Declined">Declined</option>
<option value="Vendor Unresponsive">Vendor Unresponsive</option>
<option value="Approved/No Data Collected">Approved/No Data Collected</option>
</select>
<?php
while(!$district_results_private->atEnd()) {
?>
<input name="dataID[]" type="text" id="dataID" value="<?php echo($district_results_private->getColumnVal("dataID")); ?>" />
<?php
$district_results_private->moveNext();
}
$district_results_private->moveFirst(); //return RS to first record
?>
<input name="last_modified_date[]" type="hidden" id="last_modified_date" value="<?php echo date('Y-m-d'); ?>" />
<input type="image" src="images/save.png" name="submit" id="submit" alt="Save" />
</form>
--------------------------------------------
UPDATE:
Thank you so much for your help! I did what you said and I am still getting these errors.
Notice: Undefined index: progress in /var/www/html/progress_workflow_multiple3.php on line 97
Notice: Undefined index: dataID in /var/www/html/progress_workflow_multiple3.php on line 98
Warning: Invalid argument supplied for foreach() in /var/www/html/progress_workflow_multiple3.php on line 98
Here is the code I have:
<?php
$stmt = mysqli_stmt_init($sdpc_i);
mysqli_stmt_prepare($stmt, "UPDATE data SET progress = ?, last_modified_date = CURDATE() WHERE dataID = ?");
mysqli_stmt_bind_param($stmt, 'si', $progress, $dataID);
$progress = $_POST['progress'];
foreach ($_POST['dataID'] as $dataID) {
mysqli_stmt_execute($stmt);
}
?>
Here is the form code:
<label for="progress"></label>
<span class="small_links">
<select title="progress" name="progress" id="progress" class="form-control form-control-sm-3">
<option value="">Select One</option>
<option>Contract Sent</option>
<option>Approved</option>
<option>With Legal</option>
<option>Declined</option>
<option>Vendor Unresponsive</option>
<option>Approved/No Data Collected</option>
</select>
</span>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<?php
while(!$district_results_private->atEnd()) {
?>
<input name="dataID[]" type="text" value="<?php echo $district_results_private->getColumnVal("dataID"); ?>" />
<?php
$district_results_private->moveNext();
}
$district_results_private->moveFirst(); //return RS to first record
?>
</p>
</div>
</div>
<p> </p>
<p>
<input type="image" src="images/save.png" name="submit" id="submit" alt="Save" />
</form>
Your form has 3 essential parts (excluding the submit of course) for the user to interact with:
<select id="progress"> ...(progress field)
<input id="dataID"> ...(dataId fields) this may occur multiple times
<input id="last_modified_date"> ...(lastMod field)
The progress field will only occur once, so there is no benefit in structuring its data as an array. Furthermore, a select field will default to its first option, so there is no need for selected on the first option. Also, when the value value of an option is exactly the same as the option's text, you can safely omit the value attribute.
<select title="progress" name="progress" class="form-control form-control-sm-3">
<option value="">Select One</option>
<option>Contract Sent</option>
<option>Approved</option>
<option>With Legal</option>
<option>Declined</option>
<option>Vendor Unresponsive</option>
<option>Approved/No Data Collected</option>
</select>
The dataId fields are rightly given an array-type name. However, it is inappropriate to assign multiple elements with the same id attribute. If you application is not using the id attributes (for any fields), just omit the declaration(s). If you need to assign unique id attributes, you will need to provide an incrementing counter and append that counter to the end of the id value.
while(!$district_results_private->atEnd()) {
?>
<input name="dataID[]" type="text" value="<?php echo $district_results_private->getColumnVal("dataID"); ?>" />
<?php
$district_results_private->moveNext();
}
The lastMod field can be completely omitted from the document. You are always passing the current date with the submission and don't want the user fiddling with it -- good news, you can hardcode that directly into your sql and the user won't be able to touch it.
As for the UPDATE queries, best practice indicates that you should be implementing a prepared statement and binding dynamic values to it in a loop for security and stability.
(Untested -- I never use procedural syntax)
$stmt = mysqli_stmt_init($sdpc_i);
mysqli_stmt_prepare($stmt, "UPDATE data SET progress = ?, last_modified_date = CURDATE() WHERE dataID = ?");
mysqli_stmt_bind_param($stmt, 'si', $progress, $dataID);
$progress = $_POST['progress'];
foreach ($_POST['dataID'] as $dataID) {
mysqli_stmt_execute($stmt);
}
p.s. I hope that data isn't your real table name -- because it is bad/imprecise/non-descriptive. Name it something intuitive/logical/expressive.
Related
all.
I'm pretty new to PHP, but I did a lot of research on this specific issue I'm having, and I can't seem to find my issue explained anywhere to my understanding.
Currently, I have a system where a user submits a form with the following attributes:
Username
Trainer
Rank
It then submits the selected answers into a MySQL table called 'pr_members'.
This all works as intended.
However, when I try to add one more field that is a dropdown, where they choose from three options, the code no longer works.
Basically, I have another table (pr_branch), which has the following in it:
Branch MySQL Image
The new field I want to add is a dropdown box, which allows for the user filling out the form to select from the 3 Branches in the above table. (Army, Navy, and Air Force).
I currently have the following code for this:
<?php require_once "403check.php";
if ($_SESSION["AddUser"] !== true) {
UNIVERSAL::buildfooter(1);
die('<div class="container">Insufficient Permissions</div>');
}?>
<div class="form-group">
<?php
if (isset($_POST["newmember"]) && isset($_SESSION["cur_id"])) {
PERSONNEL::createnewmember($_POST["username"], $_POST["rank"], $_POST["trainer"], $_POST["branch"]);
} ?>
<form name="new-member" method="POST">
<label for="username">Username</label>
<input name="username" type="text" class="form-control" for="new-member" required>
<label for="trainer">Trainer</label>
<select name="trainer" type="text" class="form-control" for="new-member" required>
<option value="" disabled selected hidden>Choose An Option</option>
<?php UNIVERSAL::rendersystemadmin(); ?>
<?php UNIVERSAL::rendermemberoptions("SELECT * FROM pr_members WHERE Rank_ID >= 4 OR Rank_ID = 0 ORDER BY Rank_ID desc"); ?>
</select>
<label for="rank">Rank</label>
<select name="rank" type="text" class="form-control" for="new-member" required>
<option value="" disabled selected hidden>Choose An Option</option>
<?php UNIVERSAL::renderoptions("SELECT * FROM pr_ranks WHERE Rank_ID > 0 and Rank_ID < 3 ORDER BY Rank_ID asc", "Rank"); ?>
</select>
<label for="branch">Branch</label>
<select name="branch" type="text" class="form-control" for="new-member" required>
<option value="" disabled selected hidden>Choose An Option</option>
<?php UNIVERSAL::renderoptions("SELECT * FROM pr_branch WHERE branch_ID > 0 ORDER BY branch_ID asc", "branch"); ?>
</select>
<br>
<button class="btn btn-outline-danger" name="newmember" type="submit" for="new-member">Add User</button>
</form>
</div>
Now, when I view the page with the form on it, it appears with the dropdown, and the three selections to choose from, but the fields do not have values/text. As such: Form Dropdown Image
And finally, the major issue, is that when a user submits the form, it no longer actually inserts it as a new row onto the pr_members table. The page just simply refreshes.
I apologize if there is something obvious missed here. I'm very new to php and tables/MySQL. I just really hope I can learn from this! Thank you!
What I've tried:
I've tried having simply 'Army', 'Navy', and 'Air Force' values as select options, rather than pulling from the table pr_branch. With this option, the values did appear, but the table still was not created upon submitting the form.
EDIT:
I managed to fix the invisible fields by editing the function renderoptions. But it still does not insert the rows into pr_members after submission of the form.
EDIT 2:
I managed to ensure the tables were being inserted by setting the default value to Null for the Branch column. So yeah, it did have to do with the function.
What do I need to add to this to ensure the branch that is chosen, is inserted into the branch column in pr_members?
/*
* Use the given parameters to create a new member into the database.
*/
function createnewmember($username, $rid, $trainer) {
$promoter = htmlentities($trainer);
$rank = htmlentities($rid);
$user = htmlentities($username);
$stmt = $GLOBALS["db"]->prepare("SELECT Member_ID, Member_Username FROM pr_members WHERE Member_Username=?");
$stmt->execute([$user]);
$stmt->closeCursor();
if ($stmt->rowCount() > 0) {
echo '<div class="container"><div class="alert alert-warning" role="alert">An member with the same username already exists.</div></div>';
return false;
}
$stmt = $GLOBALS["db"]->prepare("INSERT INTO pr_members (Rank_ID, Member_Username) VALUES (:rank, :user)");
$stmt->bindParam(':rank', $rank);
$stmt->bindParam(':user', $user);
$stmt->execute();
$newuser = $GLOBALS["db"]->lastInsertId();
UNIVERSAL::createnewpromolog($promoter, $newuser, 0, $rank, "New Member");
UNIVERSAL::createnewadminlog("Added User", $_SESSION["cur_id"], $newuser, "N/A", "User Added");
header("Location: admin.php?module=newmember");
}
Thanks a bunch for all the help so far!
Below is code that I am using, when i submit the survey, arrrive and mode work but not trans/checkboxes, data comes back displayed as 'on' in table (survey) database (wdtlabwork), also the field is trans, same with the other two being mode n arrive in the database, all fields were type VARCHAR. Apologies if formatting is bad i am new to site. NOTE: I want the data to come back as either car, train or bus but because its checkboxes if the user checked train and car i want the database to display train and car.
HTML
<section id="content">
<form action="connect.php" method="post">
<div class="col-6 col-s-9">
<h3>Available Transportation?</h3>
<input id="trans1" type="checkbox" name="trans[]"><label for ="trans1">Car</label>
<input id="trans2" type="checkbox" name="trans[]"><label for ="trans2">Train</label>
<input id="trans3" type="checkbox" name="trans[]"><label for ="trans3">Bus</label>
<h4>How do you intend to arrive at the Hostel?</h4>
<input id="arrive1" type="radio" value="car" name="arrive"><label for="arrive1">Car</label>
<input id="arrive2" type="radio" value="train" name="arrive"><label for="arrive2">Train</label>
<input id="arrive3" type="radio" value="bus" name="arrive"><label for="arrive3">Bus</label>
<h5>Preferred mode of transport?</h5>
<select name="mode">
<option selected hidden value="">Select Option</option>
<option value="car">Car</option>
<option value="train">Train</option>
<option value="bus">Bus</option>
</select><input type="submit" class="btn btn=primary"></div></section>
PHP
<?php
$arrive = $_POST['arrive'];
$trans = $_POST['trans'];
$mode = $_POST['mode'];
$conn = new mysqli('localhost', 'root','','wdtlabwork');
if ($conn->connect_error){
die('Connection Failed : '.$conn-> connect_error);
}else{
$stmt = $conn->prepare("insert into survey(trans, arrive, mode)
values(?, ?, ?)");
$stmt->bind_param("sss",$trans, $arrive, $mode);
$stmt->execute();
echo "registration successfully...";
$stmt->close();
$conn->close();
}
?>
Your input fields do not have value= attribute so they default to on as described here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox#Value
To get the values in the POST you need to specify the values, for example:
<input id="trans1" type="checkbox" name="trans[]" value ="car"><label for ="trans1">Car</label>
<input id="trans2" type="checkbox" name="trans[]" value ="train"><label for ="trans2">Train</label>
<input id="trans3" type="checkbox" name="trans[]" value ="bus"><label for ="trans3">Bus</label>
Then in your PHP you would receive an array of the selected elements in $_POST['trans']. If you would like to join them (not recommended) to be saved in a single field in the database you can just use implode(',', $_POST['trans']), for example:
$trans = implode(',', $_POST['trans']);
$arrive = $_POST['arrive'];
$mode = $_POST['mode'];
This is my updated code to show what has been done and to help people see easier what im asking for
in my current project, i am trying to make a page that adds fixture for the top 4 leagues in English football/soccer. with help from others, i have got as far as..
created a page with a row of inputs and select-option items that sit inside a form, this row is just one fixture out of a possible 10 or 12 depending which league is selected. with the one row, this means i looped through the data and it produces as many rows as that specific league needs.
Again, with help from others, the process of preparing, binding and executing the MySQLi query seems to be done.
My problem is to do with how to fit it all together. When i validate the form that POSTS the fixtures, do i then call upon a function to *add_fixtures()* to the database. If this is the case, passing the parameters then becomes the issue..
As there will be 10 params coming from each row, then there being upto 12 rows, thats 120 pieces of data to be passed through the function, or is there another way?...
here is the code for my premier_league.php page that is called upon when the premier league is selected in a dropdown menu...
<form action="" method="POST">
<input type="submit" name="add" value="Add" class="btn btn-medium btn-success"><br><br>
<?php
$leaguelist = '<option disabled>Please select team</option>';
if ($league_var == NULL) {
$leaguelist .= '<option "disabled"><strong>Please Select a League Table</strong></h1>';
} else {
$league_table = get_table($league_var);
foreach ($league_table as $rows) {
$leaguelist .= '<option>'.htmlspecialchars($rows['team']).'</option>';
}
}
$needed_rows = ceil(count(get_table($league_var)) / 2);
for($i=1; $i <= $needed_rows; $i++){
?>
<select name="result[<?=$i?>][home]" id="" style="width:175px">
<?=$leaguelist?>
</select>
<input type="text" name="result[<?=$i?>][home-score]" class="edit_league_input" value="">
vs
<input type="text" name="result[<?=$i?>][away-score]" class="edit_league_input" name="" value="">
<select name="result[<?=$i?>][away]" id="" style="175px">
<?=$leaguelist?>
</select>
<input type="date" name="result[<?=$i?>][date]" style="width:150px;">
<input type="time" name="result[<?=$i?>][kickoff]" style="width:90px;">
<input type="checkbox" name="result[<?=$i?>][on-tv]" value="Yes" style="margin:-10px 5px 0px 5px;">on T.v
<input type="text" name="result[<?=$i?>][channel]" value="" placeholder="Channel..." style="width:100px;">
<select name="result[<?=$i?>][result]" id="" style="width:125px;">
<option value="">Match Choice...</option>
<option value="HT">Half Time</option>
<option value="FT">Full Time</option>
<option value="P">Postponed</option>
</select>
<br>
<?php
}
And then the code mysqli query tha prepares,binds then executes the query is ...
$sql = "INSERT INTO `fixtures`
(`home`, `home-score`, `away-score`, `away`, `kickoff`, `on-tv`, `channel`, `league`, `result`, `date`)
VALUES
(?,?,?,?,?,?,?,?,?,?)";
$stmt = $db->prepare($sql);
foreach($_POST['result'] as $fixture) {
$stmt->bind_param("s", $fixture['home']);
$stmt->bind_param("i", $fixture['hs']);
$stmt->bind_param("i", $fixture['as']);
$stmt->bind_param("s", $fixture['away']);
$stmt->bind_param("s", $fixture['kickoff']);
$stmt->bind_param("s", $fixture['on-tv']);
$stmt->bind_param("s", $fixture['channel']);
$stmt->bind_param("s", $fixture['league']);
$stmt->bind_param("s", $fixture['result']);
$stmt->bind_param("s", $fixture['date']);
$stmt->execute();
So i think my question has now changed, i guess its more like ...
how do i bind the parameters of an array? and how should i pass the array through the function
i guess thats more fitting to my needs currently.
To summarize from the comments:
<form action="" method="POST">
<input type="submit" name="add" value="Add" class="btn btn-medium btn-success"><br><br>
<?php
/*
1. Prepare elements that require actions, but stay the same througout, before the loop:
*/
$leaguelist = '<option disabled>Please select team</option>';
if ($league_var == NULL) {
$leaguelist .= '<option "disabled"><strong>Please Select a League Table</strong></h1>';
} else {
$league_table = get_table($league_var);
foreach ($league_table as $rows) {
/*
2. Always use htmlspecialchars() if you're outputting something that shouldn't be interpreted as HTNL
2.a If the value is exactly the same as the text in an <option>, you may omit the value=""
*/
$leaguelist = .'<option>'.htmlspecialchars($rows['team']);'</option>';
}
}
/*
3. Loop though content that stays the same
*/
$needed_rows = 10;
for($i=1; $i <= $needed_rows; $i++){
?>
<!-- ....................................... FIXTURE 1 .............................................. -->
<!--
4. use names with the [] format, so your POST is a nicely formatted array, and you know wich options belong to each other
-->
<select name="result[<?=$i?>][home]" id="" style="width:175px">
<?=$leaguelist?>
</select>
<input type="text" name="result[<?=$i?>][hs]" class="edit_league_input" value="">
vs
<input type="text" name="result[<?=$i?>][ha]" class="edit_league_input" name="" value="">
<select name="result[<?=$i?>][away]" id="" style="175px">
<?=$leaguelist?>
</select>
....
<?php
}
Which makes on the receiving side:
//prepare content that stays the same _outside_ of the loop:
$sql = "INSERT INTO `fixtures`
(`home`, `home-score`, `away-score`, `away`, `kickoff`, `on-tv`, `channel`, `league`, `result`, `date`)
VALUES
(?,?,?,?,?,?,?,?,?,?)";
$stmt = $db->prepare($sql);
foreach($_POST['result'] as $fixture) {
$stmt->bind_param("s", $fixture['home']);
$stmt->bind_param("i", $fixture['hs']);
$stmt->bind_param("i", $fixture['as']);
$stmt->bind_param("s", $fixture['away']);
//...and so on
$stmt->execute();
}
Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.
i am really new on php. I try to make and examination project with php but i have some issues. I have exam form and this form have different type of inputs. For example some questions have combobox, some questions have textarea. I wrote my form code and i wanna learn how can i get all values from the form to the database.
my codes :
$question_id = $question_list['question_id'];
$answer_query = mysql_query("SELECT * FROM answers where question_id = $question_id ORDER BY answer_id ASC");
$total_answers = mysql_num_rows($answer_query);
if ($total_answers > 1)
{
<select name="answers[]" id="answers"> <option value="x">please select one</option>
while ($answer_list = mysql_fetch_array($answer_query)) {
<option value="<?PHP echo $answer_list['answer_id']; ?>"><?PHP echo $answer_list_list['answer_value']; ?></option>
else
{
while ($answer_list = mysql_fetch_array($answer_query)) {
<textarea name="answers[]" id="answers" rows="5" cols="100"></textarea>
so this is my answer listing part of my exam form. So as you see combobox values getting from database but textarea values will be filled by the users. So how can i get all values (answers from database in combobox (selected value) and textarea values which will be filled by users).
to get the form values to the database:
The HTML form has to be something like:
<form action="insert_into_db.php" method="POST">
<input type="text" id="answer1" name="answer1"/>
<textarea id="answer2" name="answer2"></textarea>
<input type="submit" value="POST ANSWERS" />
</form>
Then in the insert_into_db.php:
$answer1=$_POST['answer1'];
$answer2=$_POST['answer2'];