I'm stuck on this and I'm not actually seeing where exactly the problem is.
I have a bunch of input tags which are placed like that:
<div class="col-md-3">
<label>Material 1</label>
<input hidden="hidden" name="idMaterial[]" value="13" type="text" />
<input class="form-control" name="total[]" type="text" />
</div>
<div class="col-md-3">
<label>Material 2</label>
<input hidden="hidden" name="idMaterial[]" value="8" type="text" />
<input class="form-control" name="total[]" type="text" />
</div>
I have 20 input like that, the idea here is that if I write 10 in the Material 1's input field, my DB would receice something like:
id => A.I
idMaterial => 13
total => 10
But once I run the code, it comes like that (repeating the idMaterial, even if I write in more than 1 input. It always repeat the first):
idMaterial: 13
total: 10
idMaterial: 13
total: 20
That's the code I'm using to receive that form:
$idMaterial = array();
$total = array();
if($this->input->post('total')){
foreach($this->input->post('idMaterial') as $row){
$idMaterial = $row;
foreach($this->input->post('total') as $row2){
$total = $row2;
echo 'Material: '. $idMaterial .'<br> Total: '. $total. '<br><br>'; // TESTING THE OUTPUT
$query = $this->pedido->salvaLabMaterial($total, $idMaterial); // I'M SENDING THE DATA TO MODEL HERE
}
}
}
Any tips is very welcome.
#RiggsFolly
That's where I'm sending the posts the way it comes from the HTML form as you said:
$query = $this->pedido->salvaLabMaterial($this->input->post('total'),
$this->input->post('idMaterial'),
);
The model:
public function salvaLabMaterial($this->input->post('idMaterial'), $this->input->post('total')){
$query = $this->db->query(" insert into labpedidomaterial (idMaterial, total) values ('".$this->input->post('idMaterial')."', '".$this->input->post('total')."') ");
}
Related
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'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 three inputs type text in an HTML page and a button which if clicked duplicate each text box (Javascript) making them 6.
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
<button>Add more</button>
Which generate same inputs again:
<input type="text" name="category[]">
<input type="text" name="quantity[]">
<input type="text" name="amount[]">
A piece of code in Cakephp I have been trying:
$data = $this->request->data;
foreach($data['category'] as $index => $value){
$this->ModelName->save($value);
}
Trying to get two rows inserted at once with quantity, category and amount as columns. But it is not inserting and not giving any error.
Is there a way I can achieve this?
Thanks.
I'm not sure how your model works in cakephp, but you should be able to get a complete grouping of data like:
foreach($data['category'] as $index => $value){
$category = $value
$quantity = $data['quantity'][$index];
$amount = $data['amount'][$index];
// use the above 3 variables however you need to to persist the model
//$this->ModelName->save($value);
}
On a side note, you may want to consider reordering your html inputs to be like:
<input type="text" name="item[0][category]">
<input type="text" name="item[0][quantity]">
<input type="text" name="item[0][amount]">
And then maintain the next index, incrementing the numeric index of item for each additional group
This will allow you to iterate like:
foreach($data['item'] as $index => $group){
//$group['category'];
//$group['quantity'];
//$group['amount'];
}
I have a scenario. Let's say someone is on my website and there is a form which adds an event for example and there is a field as follows:
<input type="text" name="title" id="title">
Let's say that person used F12 developer tools and changes the id="title" to id="whatever", or even remove the id attribute, then how would I make my PHP script stop running so that nothing is posted to MySQL?
Here's an example for a Bookmarks feature I have: (front-end form)
<form action="bookmarks.php" method="post" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="input-mini">Title*</label>
<div class="controls">
<input class="span12" id="title" name="title" type="text" placeholder="e.g. Oliver's pet cat...">
</div>
</div><!-- /control-group -->
<div class="control-group">
<label class="control-label" for="input-mini">Link*</label>
<div class="controls">
<input class="span12" id="link" name="link" type="text" placeholder="e.g. http://boopeo.com">
<input type="hidden" name="parse_var" id="parse_var" value="addbookmark" />
<br /><input name="submit" type="submit" class="btn btn-success span12" value="Bookmark" /></form>
Back-end PHP:
if (isset($_POST['parse_var'])){
$parser = $_POST['parse_var'];
$parser = htmlspecialchars($parser);
if ($parser == "addbookmark"){
$title = $_POST['title'];
$title = htmlspecialchars($title);
$linkurl = $_POST['link'];
$linkurl = htmlspecialchars($linkurl);
$sqlrecentmark = $db->query("SELECT link_url FROM tablenamehere WHERE mem_id='$id' ORDER BY id DESC LIMIT 20");
while($row = $sqlrecentmark->fetch(PDO::FETCH_ASSOC)) {
$recent_link = $row["link_url"];
}
if ( $linkurl != $recent_link ){
$dataact = array( 'mem_id' => $id, 'title' => $title, 'link_url' => $linkurl );
$sqlactivity = $db->prepare("INSERT INTO tablenamehere (mem_id, title, link_url) value (:mem_id, :title, :link_url)");
$sqlactivity->execute($dataact);
} else {
$not_msg = '<br /><br /><div class="alert alert-error">Oops! You have added that bookmark before. Just look and you shall find!</div>';
}
}
}
Never trust data from the user. Always sanitize and validate. You are using prepared statements which is good, so you'll be mostly protected from injection. The other thing you'll want to do is determine if the data the user has sent you matches up with what you were expecting, if it does then proceed to use it with the database. (Which you are for the most part doing, so in all honesty there should be no bad effects from a malicious user)
The id of input field doesn't get passed as posted data, so there's no way to tell in the back-end php code. Maybe you're talking about the name attribute.
<input type="text" name="theTitle" id="aTitle">
In my above example, the input field will be posted as $_POST["theTitle"]
You could use javascript to check these elements before the form is submitted, but if you're worried about the user manipulating the DOM, that probably won't help much.
After reading your concern about the Undefined index error, you simply need to check if the variable is set before you use it:
if(isset($_POST["title"])) {
$title = $_POST['title'];
} else {
//output error
}