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'];
Related
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.
I'm creating a database system to house and retrieve invoices for a retailer/ company. I'm looking for a way to add multiple entries to a mysql database through a php form without having to add each item individually. My form looks like;
<div class="new_invoice">
<form action="addCustomerInvoice.php" method = "post" enctype= "multipart/form-data">
<fieldset>
<legend> Add new invoice for <?php echo $rsCustomer['forename']; echo ' '; echo $rsCustomer['surname']; ?></legend>
<h4>Invoice Number:</h4>
<input type="text" name="invoice_no">
<h4>Item Quantity:</h4>
<input type="text" name="quantity">
<h4>Item Name:</h4>
<input type="text" name="item_name">
<h4>Item Category:</h4>
<input type="text" name="item_category">
<h4>Manufacturer:</h4>
<input type="text" name="item_manufacturer">
<h4>Item Description:</h4>
<input type="text" name="item_description">
<h4>Item Price:</h4>
<input type="text" name="item_price">
<h4>Item Information:</h4>
<input type="text" name="item_info">
<input type="submit" value="Add new record">
</fieldset>
</form>
</div>
And process like;
<?php
include 'database_conn.php';
$InvoiceNumber = $_POST['invoice_no'];
$Quantity = $_POST['quantity'];
$ItemName = $_POST['item_name'];
$ItemCat = $_POST['item_category'];
$ItemMan = $_POST['item_manufacturer'];
$ItemDesc = $_POST['item_description'];
$ItemInfo = $_POST['item_info'];
$sql = "INSERT INTO hlinvoicetable (invoice_no, quantity, item_name, item_category, item_manufacturer, item_description, item_info) VALUES ('$InvoiceNo', '$Quantity', '$ItemName', '$ItemCat', '$ItemMan', '$ItemDesc', '$ItemInfo')";
$queryresult = mysqli_query($conn,$sql) or die(mysqli_error());
echo "New invoice added.
mysqli_close($conn);
?>
I'm wondering is there a way to repeat the form and have it add a new entry to the database unless fields are left blank and it is therefore ignored and no rows are added? Also could all items added hold the same primary key (invoice_no)?
Thanks in advance!
You need to use array names on your inputs. For example:
<input type="text" name="invoice_no[]">
...
<input type="text" name="invoice_no[]">
Then in PHP you would obtain the values from $_POST['invoice_no'][0], $_POST['invoice_no'][1], etc.
You could loop over the values, like:
foreach ($_POST['invoice_no'] as $key => $invoice) {
if (!empty($_POST['invoice_no'][$key])
&& !empty($_POST['quantity'][$key])
&& !empty($_POST['item_name'][$key])
//... include all fields that can't be left empty
) {
// Do insert
}
}
Also, as mentioned above, make sure to use bound parameters instead of putting user-supplied data directly into the SQL queries. It is really not much extra code and is necessary to save you from SQL injection attacks.
I have a form that has various inputs. One of the inputs contains a pre determined value that is loaded by script that is named "invoiceid". This invoiceid is the name and id of the form input and also the name of a column in my database. How can update the row in my database that contains the same value under the invoiceid column with all other form data submitted? I dont know what I'm doing...please help. Thanks for your time.
FORM
<form action="update.php" id="contactForm" method="post">
<input id="invoiceid" name="invoiceid" type="hidden" value=""/>
<input id="txt1" name="txt1" type="text" value=""/>
<input id="q1" name="q1" value="9.50" checked="checked" type="radio">
<input id="q1" name="q1" value="12.50" type="radio">
<select id="selectbox" name="selectbox">
<option selected="selected" value="">Please select...</option>
<option value="PURCHASE">Order for Purchase</option>
<option value="REVIEW">Order for Review</option>
</select>
<button id="btn1" type="submit" name="submit">Submit</button></div>
</form>
update.php
//Table name: seguin_orders
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
// Check if the connection failed
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_GET['invoiceid']))
{
$invoiceid= $_GET['invoiceid'];
}
?>
I think it can help you.
update.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
// Check if the connection failed
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_POST['invoiceid']))
{
$invoiceid= $_POST['invoiceid'];
$column1 = $_POST['txt1'];
$column2 = $_POST['q1'];
$column3 = $_POST['selectbox'];
$sql = "UPDATE TableName SET column1='".$column1."', column2='".$column2."', column3='".$column3."' WHERE invoiceid='".$invoiceid."'";
}
?>
///note: change the table name and column names according to your database
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'];
i'm new to php , i have been searching for a tutorial regarding inserting form's input(text) , radio and selection data to MySQL database's table using php. i found some tutorials but most are confusing. So i decided to ask.
Okay here's what i want to do. I have a form which have two types of input and a selection
1. input type text
2. input type radio
3. selection
Here's the HTML code :
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
<input type="submit" name="submit" value="Submit">
</form>
I have set the form action to blank because the php code will be in the same file as the HTML (it's a php file btw)
MySQL table : info
structure :
1. name
2. class
3. agree
I want the php code to insert myname into name , selection's selected data into class , radio selected data into agree
P/S Yes i have added a connect to database php script , i just want to know how to get the form data into mysql.
Can someone write a php code example on how can i do this?
Thanks and have a nice day . I hope i have provided enough information. Thanks again if you help.
1. There is a problem with your radio element. The name should be the same for both options.
It should be like this:
<input type="radio" name="agree" value="Yes"> or
<input type="radio" name="agree" value="No">
2. You can access everything in the $_POST array, since you are using the method post for the form.
$name = $_POST['myname'];
$selection = $_POST['selection'];
$agree = $_POST['agree'];
3. If you are not using parametrized SQL with a library such as PDO, MySQLi, etc... you must always escape the data, which will be used in query using mysql_real_escape_string(), in order to protect against SQL injection.
This would be a sample code, to do the escaping and the query.
// write a function somewhere, to use as a shortcut
// for escaping data which will be used in a query
function sql_escape($str){
return "'".mysql_real_escape_string($str)."'";
}
// build the query
$query = sprintf('INSERT INTO table_name(name, class, agree) VALUES(%s, %s, %s)',
sql_escape($_POST['myname']),
sql_escape($_POST['selection']),
sql_escape($_POST['agree']));
// finally run it
$result = mysql_query($query);
I've taken it a little further here, there is still plenty more that can be done and many way's to do it, for instance you could extend the $errors array to include a field id and then highlight the HTML form field so the user can see exactly where they went wrong.
Considering your form is fairly simple you would not need this.
#Shef's code would certainly do the job but I thought you might be interested in some more.
<?php
// check the form has been submitted
if (isset($_POST['submit'])) {
// escape the form fields and assign them to variables
// validate myname to ensure the user entered data
if (isset($_POST['myname']) && $_POST['myname']!='') {
$myname = mysql_real_escape_string($_POST['myname']);
} else {
// create an error variable array to store errors to display
$errors[] = 'Please enter your name';
}
// no need to validate selection here as it alway's has a value
$classtype = mysql_real_escape_string($_POST['selection']);
// validate agree unless you want to add 'checked' to one of the values
if (isset($_POST['agree']) && $_POST['agree']!='') {
$agree = mysql_real_escape_string($_POST['agree']);
} else {
$errors[] = 'Please tell us if you agree?';
}
//if errors found tell the user else write and execute the query
if ($errors) {
$message = '<p class="error">We found a problem:</p><ul>';
foreach($error as $msg){
$message .= '<li>'.$msg.'</li>';
}
$message .= '</ul><p>Please fix the error/s to continue.</p>';
} else {
// write the query
$query = "INSERT INTO table (myname, classtype, agree) VALUES ";
$query .= "('$myname','$classtype','$agree')"
// run the query
mysql_query($query);
$message = '<p class="sucessful">Thanks '.htmlspecialchars($myname).'. Your selection has been saved.</p>';
}
}
// print the message
// show the variables in the form field so they don't need re-input
if ($message!='') { echo $message; }
?>
<form action="" method="post" enctype="multipart/form-data">
<strong>Your Name: </strong><br>
<input type="text" name="myname" value="<?php echo htmlspecialchars($myname) ?>" />
<br /><br/>
<strong>Which class type you want:</strong><br>
<select name="selection">
<option value="A"<?php if ($classtype=='A') { echo ' selected'; } ?>>A</option>
<option value="B"<?php if ($classtype=='B') { echo ' selected'; } ?>>B</option>
<option value="C"<?php if ($classtype=='C') { echo ' selected'; } ?>>C</option>
</select>
<strong>Do you agree?</strong><br>
<input type="radio" name="agree" value="Yes"<?php if ($agree=='Yes') { echo ' checked'; } ?>> or
<input type="radio" name="agree" value="No"<?php if ($agree=='No') { echo ' checked'; } ?>>
<input type="submit" name="submit" value="Submit">
</form>
Also: #sqwk, Don't point people towards w3schools, see this: http://w3fools.com/
Check whether there is any data in the $_POST array and get the values from it.
Have a look hereāthe second example down is what you need: http://www.w3schools.com/php/php_mysql_insert.asp
(You do have to make the changes that Shef suggested, though.)
Also remember to check your data-integrity, otherwise people could use your insert to run malicious code.
check this simple example:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Sname: <input type="text" name="sname" />
<input type="submit" />
</form>
after you submit form, you can take name and sname.
welcome.php::
<?php
$name= $_POST["name"];
$sname= $_POST["sname"]; ?>
now you can use this variables as if you want.