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.
Related
I'm working on a formular, but for the moment I just want to insert into an array my elements (I have books and authors).
I can display my books with author (name + surname) with the foreach, but I can't add more elements.
Here is the code with the form.
<H1>Exercice 2</H1>
<form method="POST">
<label for"code" >Number :</label>
<input id="code" name="code" type="number" />
<label for"title">Title :</label>
<input id="title" name="title" type="text" />
<label for"author" >Author :</label>
<input id="author" name="author" type="text" />
<button type="input" type="submit">Ok</button>
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = array();
$book['code'] = 123;
$book['title'] = "Legendes";
$book['author'] = array("David", "Gemmel");
foreach($book as $value){
$book['key'] = $value;
var_dump($book);
if (is_array($value)) {
foreach($value as $otherValue) {
echo($otherValue);
}
} else {
echo($value);
}
}
I did some searcch, but I don't think it works, it's using the array_push() method with the POST, but I don't know where I can manipulate my form into the array.
If you want some details, I'll be happy to do that =) I'm working on it, if i have some news, you will know =)
Have a nice day =)
1) Assignments are in reverse. Correct way:
$myVar = $myValue
2) You need to set the name attribute in your inputs in order to be sent:
<input id="code" type="number" name="code" />
Then you can access them like:
$_POST['code']
3) To add an element by key in an array, use:
$array['key'] = $value;
Your Exercise 2 have some mistakes :
First, your HTML inputs must have the name attribute to be retrieved by post:
<h1>Exercice 2</h1>
<form method="post">
<label>
<input name="code" type="number" />
</label>
<button type="submit">Ok</button>
</form>
With PHP, you can access to any input value using the name:
$code = $_POST['code'];
Now, I think you want to "add" several books using this HTML form without a storage system. The problem is you can not do this if for every a new request since all the elements you have in your array will be deleted each time you run a new post request. To keep this information you need to use some persistent storage system as a database or others.
Since you seem to want to keep the information for each book together, you need to use a multidimensional array - hence, you'll need to redo the whole thing. Here's a suggestion:
Form:
<h2>Exercice 2</h2>
<form method="post">
<label for"code">Number :</label>
<input id="code" name="code" type="number">
<label for"title">Title :</label>
<input id="title" name="title" type="text">
<label for"author-firstname">Author First Name:</label>
<input id="author-firstname" name="author-firstname" type="text">
<label for "author-lastname">Author Last Name:</label>
<input id="author-lastname" name="author-lastname" type="text">
<input type="submit" name="submit_book" value="Ok">
</form>
Fixed the name-problems, changed the heading (you never, ever use H1 for a form, H1 is strictly used for the site-wide heading/logo/name of site). Also changed the button into a simple input type="submit".
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = []; // changed this to modern PHP version array assignment
$book[0]['code'] = 123;
$book[0]['title'] = "Legendes";
$book[0]['author-firstname'] = "David";
$book[0]['author-lastname'] = "Gemmel"; // no reason to assign a separate array for first and last name, just use two array-keys
for ($c = 0; $c <= count($book); $c++) { //changed this to a for, counting the amount of entries in the $book array
echo 'Title: '.$book[$c]['title'];
echo 'Author: '.$book[$c]['author-firstname'].' '.$book[$c]['author-lastname'];
} // the content should probably be wrapped in a container of some sort, probably a <li> (and then a <ul>-list declared before the for-loop)
Now. None of this has anything to do with putting stuff INTO the array. That would be something like this (there isn't even a point of assigning the $_POST-variables for the code you posted. But, you can do something like this:
if (isset($_POST['submit_book'])) {
$title = $_POST['title'];
$code = $_POST['code'];
$author-firstname = $_POST['author-firstname'];
$author-lastname = $_POST['author-lastname'];
// however, if all you're doing is putting this into the array, no need to assigne the $_POST to variables, you can just do this:
$temp_array = ['code'=>$_POST['code'],'title'=>$_POST['title'],'author-firstname'=>$_POST['author-firstname'],'author-lastname'=>$_POST['author-lastname']];
$book[] = $temp_array;
}
So, that would replace the assigned variables at the beginning of your code.
I have a small app where the user adds 3-4 ticket in a single Form via the 'Add Another Ticket' button. These text boxes are generated via Jquery .append() and each ticket has 5 input boxes in it. Code Below
<form action="ticket-addcode.php" method="post" enctype="multipart/form-data" class="my-form">
<span id="tixmegaform">
<input type="hidden" name="Eventid" value="<?php echo $eventid; ?>" />
<div class="AddRow">
<label>Package Name</label>
<input class="requierd" type="text" name="ticketgroup" placeholder="Enter the Package Name. Most Preferably Event name" id="EN" value="<?php echo $ticketgroup; ?>">
</div>
<h5>Ticket 1</h5>
<div class="AddRow">
<label>Ticket Title</label>
<input class="requierd" type="text" name="tname[]" placeholder="Enter the Package Name. Most Preferably Event name" id="EN">
</div>
<div class="AddRow">
<label>Ticket Desc</label>
<input class="requierd" type="text" name="tdesc[]" placeholder="Enter the Details" id="EN">
</div>
<div class="AddRow">
<label>Ticket Cost</label>
<input class="requierd" type="text" name="tprice[]" placeholder="Enter the ticket Cost in Numbers. No Currency" id="EN">
</div>
<div class="AddRow">
<label>Ticket Book URL</label>
<input class="requierd" type="text" name="turl[]" placeholder="Enter the URL without http" id="EN">
</div>
<div class="AddRow">
<label>Time</label>
<input type="text" class="left requierd" name="eventTime[]" id="timeformatExample1" placeholder="Start">
</div>
<div class="AddRow">
<label>Date</label>
<input class="requierd" type="text" name="tdate[]" placeholder="Enter the Package Name. Most Preferably Event name" id="from">
</div>
</span>
<input type="submit" name="submit" class="add_field_button_submit">
</form>
</div>
</div>
</div>
<div class="add_field_button">Add Another Ticket</div>
</div>
So, when I hit the Submit button, a nested foreach runs through an array generated by the submit button. I'm able to fetch the values out of the array but somehow the output is not useful to me. Below is the foreach & the output
foreach ($_POST as $pos => $newarr) {
foreach($newarr as $res => $final){
echo $pos.'-----'.$final.'<br>';
}
}
Output
**tname-----VIP tix
tdesc-----Early Bird Desc
tdesc-----VIP Desc Tix
tprice-----5000
tprice-----10000
turl-----google.com
turl-----yahoo.com
eventTime-----00:30:00
eventTime-----00:00:45
tdate-----2-2-2016
tdate-----3-3-2016**
I tried to use an Insert Statement, but it just won't work. It seems that my foreach is resolving the sub array (tname array) and the outer array. If my foreach could just fetch values of different key and not the entire subarray, I would be able to insert the record into db.
Can you guide me on how to achieve this and where to put the INSERT Statement?
I don't think looping over $_POST as you have done will do you any good. Notice how the order of your information coming out makes it difficult?
Instead pick any of your array fields to determine first the number of tickets you have. Then use the number of tickets for iterating over each ticket. This way you can get the index of each group (ticket) of related information together. With the index, you can get all the information related for the group.
Once you have the necessary information, you can either store each information by doing one insert at a time or by doing one big insert. For simplicity, we shall use the former approach (using PDO).
Below is a rough and untested sketch of how it might look:
try {
$dbh = new PDO($dsn, $user, $password);
// prepare your SQL statement
$sth = $dbh->prepare("INSERT INTO table (title, desc, price, url) VALUES(?, ?, ?, ?)");
// loop over each ticket information
for ($i = 0, $numTickets = count($_POST['tname']); $i < $numTickets; $i++) {
$title = $_POST['tname'][$i];
$desc = $_POST['tdesc'][$i];
$price = $_POST['tprice'][$i];
$url = $_POST['turl'][$i];
// insert information into database
$sth->execute(array($title, $desc, $price, $url));
}
} catch (PDOException $e) {
// if something goes wrong, add some logic
}
For more information on PDO, read the documentation.
Use below format of SQL for insertion:
Example:
INSERT INTO tbl_name
(a,b,c)
VALUE (7,8,9);
As per your code:
$sql01 = "INSERT INTO tbl_name (tname,tdesc,tprice, turl) VALUES ";
foreach ($_POST as $pos => $newarr) {
$sql01 .= "(";
$sql01 .= isset($_POST['tname'])?array_merge($_POST['tname'],","):"";
$sql01 .= isset($_POST['tdesc'])?array_merge($_POST['tdesc'],","):"";
$sql01 .= isset($_POST['tprice'])?array_merge($_POST['tprice'],","):"";
$sql01 .= isset($_POST['turl'])?array_merge($_POST['turl'],","):"";
$sql01 .= ")";
}
mysql_query($sql01);
I have some strange problems with this codes:
The while loopp that contains a form inside
<?php
$sql = "SELECT * FROM sessions WHERE SES = '$SES' ORDER BY ID DESC";
$preorders = mysql_query($sql);
while ($pre = mysql_fetch_array($preorders)) { ?>
<tr>
<td class="center">
<form id="update" action="update" method="post">
<input type="number" name="QTY[]" value="<?=$pre[QTY]?>" min="1" max="100">
<input type="hidden" name="ID[]" value="<?=$pre[ID]?>">
</form></td>
</tr>
<?php } ?>
The submit button
<button type="submit" form="update">Update</button>
Process page
foreach ($_POST['ID'] as $key => $ID) {
$QTY = $_POST['QTY'][$key];
mysql_query("UPDATE sessions SET QTY= '$QTY' WHERE ID = '$ID' ");
}
THE ISSUE
That foreach update only the first item. Mostly, I need to update more than one item. Where is the problem?
Thank you so much!
There are multiple things going wrong with your code. First you use [] in this input's name:
<input type="number" name="QTY[]" value="<?=$pre[QTY]?>" min="1" max="100">
and this input as well:
<input type="hidden" name="ID[]" value="<?=$pre[ID]?>">
You probably want to place them inside <?php ... ?> tags.
Second. You only have one update button but multiple forms. Each form needs its own update button which needs to be included inside each <form> element.
Third. You're using the deprecated mysql functions. Change to mysqli or PDO.
Fourth. You should use Prepared Statements for your update query or else your code is susceptible to SQL Injection.
I'm working on a PHP dynamic form based on the tutorial found here:
http://blog.calendarscripts.info/dynamically-adding-input-form-fields-with-jquery/
Here is the table layout:
ID | depratecat | MinBalance | InterestRate | APY | suborder
inputted rows
ID is auto-increment.
The form fields for depratecat are visible in my code only for testing; normally the user would not be able to change this value. The value of depratecat would come from a POST value from a previous page and should be the same for all rows inputted or edited in this instance. For testing I'm declaring the value as 14.
My test page is here:
http://www.bentleg.com/fcsbadmin/dynamictest4.php
The problems:
The "Add row" script function does not work and the code won't insert new data thru form; nothing happens. No errors are shown in the Chrome console
Editing or deleting pre-existing rows seems to work.
Below is my complete test code minus the connection, Some print_r added to show the array.:
<?php
error_reporting(E_ALL);
// Connect to the DB
$link = myconnection stuff
$new_depratecat='14'; //for testing
// store in the DB
if(!empty($_POST['ok'])) {
//first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
// you can optimize below into a single query, but let's keep it simple and clear for now:
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM tblRates_balance WHERE id=$id";
$link->query($sql);
}
}
// now, to edit the existing data, we have to select all the records in a variable.
$sql="SELECT * FROM tblRates_balance WHERE depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
// now edit them
while($rates = mysqli_fetch_array($result)) {
// remember how we constructed the field names above? This was with the idea to access the values easy now
$sql = "UPDATE tblRates_balance SET
MinBalance='".$_POST['MinBalance'.$rates['id']]."',
InterestRate='".$_POST['InterestRate'.$rates['id']]."',
APY='".$_POST['APY'.$rates['id']]."',
suborder='".$_POST['suborder'.$rates['id']]."'
WHERE id='$rates[id]'";
$link->query($sql);
}
// (feel free to optimize this so query is executed only when a rate is actually changed)
// adding new
if($_POST['add_MinBalance']!= "") {
//echo ("OKAY");
$sql = "INSERT INTO tblRates_balance (depratecat, MinBalance, InterestRate, APY, suborder) VALUES ('$new_depratecat','".$_POST['add_MinBalance']."', '".$_POST['add_InterestRate']."', '".$_POST['add_APY']."','".$_POST['add_suborder']."' );";
$link->query($sql);
}
}
// select existing rates here
$sql="SELECT * FROM tblRates_balance where depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
?>
<html>
<head>
<title>Example of dynamically adding row and inserting into mySql with jQuery</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<h1>Example of dynamically adding row and inserting into mySql with jQuery </h1>
<form method="POST" id="newrate">
<div id="itemRows">
Minimum Balance: <input type="text" name="add_MinBalance" size="30" />
Interest Rate: <input type="text" name="add_InterestRate" />
APY: <input type="text" name="add_APY" />
Order: <input type="text" name="add_suborder" size="2"/>
<< Add data and click on "Save Changes" to insert into db. <br>
You can add a new row and make changes to existing rows all at one time and click on "Save Changes."
New entry row will appear above after saving.
<?php
// Next section does updating. let's assume you have the rate data from the DB in variable called $rates
while($rates = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$rates['id']?>">
<?php //echo $rates['id']; ?>
Minimum Balance: <input type="text" name="MinBalance<?=$rates['id']?>" value="<?=$rates['MinBalance']?>" />
Interest Rate: <input type="text" name="InterestRate<?=$rates['id']?>" value="<?=$rates['InterestRate']?>" />
APY: <input type="text" name="APY<?=$rates['id']?>" value="<?=$rates['APY']?>" />
Order: <input type="text" name="suborder<?=$rates['id']?>" value="<?=$rates['suborder']?>" />
<input type="checkbox" name="delete_ids[]" value="<?=$rates['id']?>"> Mark to delete</p>
<?php endwhile;?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script language="Javascript" type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Minimum Balance:<input type="text" name="add_MinBalance[]" value="'+frm['add_MinBalance[]'].value+'">Interest Rate:<input type="text" name="add_InterestRate[]" value="'+ frm['add_InterestRate[]'].value +'">APY:<input type="text" name="add_APY[]" value="'+frm['add_APY[]'].value+'">Order:<input type="text" name="add_suborder[]"value="'+ frm['add_suborder[]'].value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+')(this);"></p>';
jQuery('#itemRows').append(row);
frm['add_MinBalance[]'].value = '';
frm['add_InterestRate[]'].value = '';
frm['add_APY[]'].value = '';
frm['add_suborder[]'].value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
//}
</script>
</body>
</html>
The inputs in the initial form have names add_depratecat, add_MinBalance, add_InterestRate, add_APY, and add_suborder. When you add new rows, they have the same names, but with [] appended. So the original row creates single inputs, the added rows create array inputs, but they have the same names, and they conflict.
You should use the array form for the original inputs as well:
<form method="POST" id="newrate">
<div id="itemRows">
Dep_rate_cat:<input type="text" name="add_depratecat[]" size="30"/>
Minimum Balance: <input type="text" name="add_MinBalance[]" size="30" />
Interest Rate: <input type="text" name="add_InterestRate[]" />
APY: <input type="text" name="add_APY[]" />
Order: <input type="text" name="add_suborder[]" size="2"/>
so that they're consistent with the added rows.
Initially you are not adding [] in the form fields,
change <input type="text" name="add_depratecat" size="30"> to <input type="text" name="add_depratecat[]" size="30">, do the same for other fields as well.
And in foreach where you are inserting data to database use array $depratecat[] instead of string $depratecat
if(isset($_POST['add_depratecat'])) {
$depratecat = $_POST['add_depratecat']; ........
For debugging purpose write echo '<pre>'; print_r($_POST); OR var_dump($_POST); Instead of
echo '<pre>',print_r($_POST,true),'</pre>';.
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.