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.
Related
My goal: I wanted to make a list system that stores an array that has 3 values...
"Product's Name",
"Product's Price",
"Amount of Products".
And I want the user to keep adding products and be able sum it all up by multiplying the price by products and summing it all together if there's two or more products in the array.
Expectations:
"Milk",
2.99,
40
"Apples",
3.00,
5
My problem is the array input is replacing index 0.
Result:
Milk
2.99
40
I tried adding the other value, it replaces index 0.
I need some help to understand this problem.
<html>
<body>
<input id="inventory" name="p-name" type="text" placeholder="product name">
<input id="inventory" name="p-price" type="text" placeholder="product name">
<input id="inventory" name="p-amount" type="text" placeholder="product name">
<input id="inventory" name="s-name" type="text" placeholder="product name">
<input id="inventory" name="s-price" type="text" placeholder="product name">
<input id="inventory" name="s-amount" type="text" placeholder="product name">
<input type=submit name=submit[AddToList] value='Add to list'>
<input type=submit name=submit[ClearAllList] value='Clear All List'>
<?php
$listOfInventories = array();
if (isset($_POST["submit"])) { // Checks if user clicked btn.
$sub = $_POST["submit"];
$time = $_POST["time"];
$pName = $_POST["p-name"];
$pPrice = $_POST["p-price"];
$AmountOfProducts = $_POST["p-amount"];
$sName = $_POST["s-name"];
$sPrice = $_POST["s-price"];
$TimesWorkersLabored = $_POST["s-amount"];
if (isset($sub["AddToList"])) {
echo " Added to list <br>";
array_push($listOfInventories, array($pName, $pPrice, $AmountOfProducts)) ;
foreach ($listOfInventories as $value) {
foreach ($value as $x) {
echo $x;
}
}
echo count($listOfInventories);
// Save something;
} elseif (isset($sub["ClearAllList"])) {
$listOfInventories = [];
// Delete something
}
?>
</body>
</html>
Adding first product
Adding second product
Edit1: Possibly the fault is the initialization array, but where should I put it? It might not work before the array_push.
Please use SESSION to do what you want (this is a rather standard way to handle things like "shopping cart")
Hence, try something like $_SESSION["listOfInventories"] = array(); and then array_push($_SESSION["listOfInventories"], array("Apple", 10.5, 1)) ;
Please try to run the following PHP script, and RELOAD to see the effect - it will preserve the data and add more item(s)
<?php
session_start();
if (!isset($_SESSION["listOfInventories"]))
{$_SESSION["listOfInventories"] = array();}
array_push($_SESSION["listOfInventories"], array("Apple", 10.5, 1)) ;
echo count($_SESSION["listOfInventories"]);
echo "....<br>";
array_push($_SESSION["listOfInventories"], array("Orange", 10.5, 1)) ;
echo count($_SESSION["listOfInventories"]);
echo "....<br>";
?>
Use method="POST", put your Type="submit" attribute to Submit in Double Quote and Value="".. also put your } at the end of the if statement, add session_start() into the Login file and call only the number of inputs in the Field. use Localhost to store your Timestamp.
I am programming a page right now, and I am stuck with a problem.
The thing is that I am making a page, where you can answer all kind of question, but as it is possible to make new questions for that page, I am not able to keep a track of every input box, as it can't be something manual.
Let us say that i have the textboxes:
<input type="text" name="question_1" />
<input type="text" name="question_2" />
<input type="text" name="question_3" />
<input type="text" name="question_4" />
But as I add more questions from another page, with help from MySQL, there come new fields, for example:
<input type="text" name="question_5" />
<input type="text" name="question_6" />
<input type="text" name="question_7" />
As there can come unlimited questions, I cant really get their values by making PHP string like these:
$question1 = $_POST["question_1"];
$question2 = $_POST["question_2"];
$question3 = $_POST["question_3"];
and so on, because I can't know how many there are going to be made.
So my question is: Is it possible to get the value of every input box, which name is starting with "question_" and store them in a variable?
Thanks in advance, and sorry for my bad English :)
$i = 1;
$myarray = [];
while ($_POST["questions_".$i]) {
$i++;
array_push($myarray, $_POST["questions_".$i]);
}
Loop thru them until it's null. This pushes them to an array, but you could use them in the loop.
You can then generate a string from those too, for example a MySQL query:
$i = 1;
$firstpartofquery = "";
$secondpartofquery = "";
while ($_POST["questions_".$i]) {
$i++;
if ($firstpartofquery) { $firstpartofquery .= ", "; }
$firstpartofquery .= "question_" . $i;
if ($secondpartofquery) { $firstpartofquery .= ", "; }
$secondpartofquery .= "'" . $_POST["questions_".$i] . "'";
}
$myquery = "INSERT INTO question($firstpartofquery) VALUES($secondpartofquery)";
Just name you all of form's input elements as question[]
i.e
<input type="text" name="question[]" />
<input type="text" name="question[]" />
<input type="text" name="question[]" />
Then from your script you can loop through them, something like the following,:
$questions = $_POST['question'];
foreach ($questions as $question){
echo $question." <br /> \n";
}
This solution make life easier if you want to handle those fields on the client-side i.e via javascript or jquery for example, you will be able to handle them easily as:
<script>
questions = document.getElementsByName('question[]');
</script>
So by this way you have an array of all objects -fields- that contain your questions. As I think, that's the standard solution for handling multiple fields of the same entity in your forms.
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
}
I am trying to add commenting like StackOverflow and Facebook uses to a site I'm building. Basically, each parent post will have its own child comments. I plan to implement the front-end with jQuery Ajax but I'm struggling with how to best tackle the PHP back-end.
Since having the same name and ID for each form field would cause validation errors (and then some, probably), I added the parent post's ID to each form field. Fields that will be passed are commentID, commentBody, commentAuthor - with the ID added they will be commentTitle-12, etc.
Since the $_POST array_key will be different each time a new post is processed, I need to trim off the -12 (or whatever the ID may be) from the $_POST key, leaving just commentTitle, commentBody, etc. and its associated value.
Example
$_POST['commentTitle-12']; //how it would be received after submission
$_POST['commentTitle']; //this is what I am aiming for
Many thanks
SOLUTION
Thanks to CFreak-
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$title = $_POST['title'][0];
$body = $_POST['body'][0];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[]"/>
<input type="text" name="body[]"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
Update 2
Oops, kind of forgot the whole point of it - unique names (although it's been established that 1) this isn't really necessary and 2) probably better, for this application, to do this using jQuery instead)
//Basic example, not actual script
<?php
if (array_key_exists("send", $_POST)) {
$id = $_POST['id'];
$title = $_POST['title'][$id];
$body = $_POST['body'][$id];
echo $title . ', ' . $body;
}
?>
<html>
<body>
<form name="test" id="test" method="post" action="">
<input type="text" name="title[<?php echo $row['id'];?>]"/>
<input type="text" name="body[<?php echo $row['id'];?>]"/>
<input type="hidden" name="id" value="<?php echo $row['id']; //the ID?>"/>
<input type="submit" name="send" id="send"/>
</form>
</body>
</html>
PHP has a little trick to get arrays or even multi-dimensional arrays out of an HTML form. In the HTML name your field like this:
<input type="text" name="commentTitle[12]" value="(whatever default value)" />
(you can use variables or whatever to put in the "12" if that's what you're doing, the key is the [ ] brackets.
Then in PHP you'll get:
$_POST['commentTitle'][12]
You could then just loop through the comments and grabbing each by the index ID.
You can also just leave it as empty square brackets in the HTML:
<input type="text" name="commentTitle[]" value="(whatever default value)" />
That will just make it an indexed array starting at 0, if you don't care what the actual ID value is.
Hope that helps.
You just have to iterate through $_POST and search for matching keys:
function extract_vars_from_post($arr) {
$result = array();
foreach ($arr as $key => $val) {
// $key looks like asdasd-12
if (preg_match('/([a-z]+)-\d+/', $key, $match)) {
$result[$match[1]] = $val;
} else {
$result[$key] = $val;
}
}
return $result;
}
Didn't test the code, though