Searching for Array Key in $_POST, PHP - php

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

Related

First element in array keeps getting overwritten, will not add onto array

I am trying to create a quiz, in order to do this I am using a form which users will input information into, once they submit this form it should add the input to an array/list.
The user should then be able to enter information and the process would repeat.
The finished product would be an array with each element corresponding to the order the answers were given.
-
I have tried so far using both array_push() and declaring elements, eg: $my_array[0] = $input;.
The current problem I am experiencing is that each time I submit the form, the $count variable doesn't seem to increment.
Instead it simply stores the data in the first element and overwrites which was previously there.
I am inclined to believe this is a problem with the posting of the submit button.
-
Here is my code:
<html>
<body>
<form action="" method="POST">
<input type="text" name="INPUT" placeholder="Input something"; required /><br><br>
<input type="submit" name="Submit" /><br><br>
<?PHP
$my_array = array();
$count = 0;
if(isset($_POST['Submit'])){
global $count;
$input = $_POST['INPUT'];
$my_array[$count] = $input;
print_r($my_array);
echo "Count:" . $count;
$count++;
}
?>
</form>
</body>
</html>
The crux of the issue here is that variable values do not persist across PHP requests. Every time you submit the form, you are throwing away your old $count and $my_array variables and initializing new variables with the same names.
Here is a working version of your code snippet, which takes advantage of the PHP $_SESSION variable to have persistent information between requests:
<?php
session_start();
if (!isset($_SESSION["my_array"])) {
$_SESSION["my_array"] = array();
}
?>
<html>
<body>
<form action="" method="POST">
<input type="text" name="INPUT" placeholder="Input something"; required /><br><br>
<input type="submit" name="Submit" /><br><br>
<?php
if(isset($_POST['Submit'])){
array_push($_SESSION["my_array"], $_POST['INPUT']);
print_r($_SESSION["my_array"]);
echo "Count:" . count($_SESSION["my_array"]);
}
?>
</form>
</body>
</html>

i want to be able to echo all the element in an array?

I pretty newbie to php and javascript but more i am curious about PHP. I want to add elements into a empty array every time i add a new element trough a input form, and after that i want those elements to be displayed in to the browser .The code i use is this
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
if (isset($_POST['submit'])) {
$_SESSION['names']=array();
$names=$_SESSION['names'];
$name=$_POST['name'];
array_push($names,$name);
for($i=0;$i<count($names);$i++){
echo $names[$i];
}
};
How could i achieve to display every element inside the array that i add trough the input field in php?
You overwrite the value every time because you wipe out the array on every page load: $_SESSION['names']=array();. Instead check to see if that session variable exists (and is an array) first and, if it doesn't, then create it. Otherwise just append to that array.
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
session_start();
if (isset($_POST['submit'])) {
if (!isset($_SESSION['names']) || !is_array($_SESSION['names'])) {
$_SESSION['names'] = array();
}
$name = $_POST['name'];
$_SESSION['names'][] = $name;
$num_names = count($_SESSION['names']);
for($i=0;$i<$num_names;$i++){
echo $_SESSION['names'][$i];
}
};

PHP - Insert elemens into an array

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.

Saving form values with php and calling cookie using SESSION

I am making a form in html. When a person clicks on submit, it checks if certain fields are filled correctly, so pretty simple form so far.
However, i want to save the text which is typed into the fields, if a person refreshes the page. So if the page is refreshed, the text is still in the fields.
I am trying to achieve this using php and a cookie.
// Cookie
$saved_info = array();
$saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][',
$_COOKIE['offer_saved_info']) : array();
foreach($saved_infos as $info)
{
$info_ = trim($info, '[]');
$parts = explode('|', $info_);
$saved_info[$parts[0]] = $parts[1];
}
if(isset($_SESSION['webhipster_ask']['headline']))
$saved_info['headline'] = $_SESSION['webhipster_ask']['headline'];
// End Cookie
and now for the form input field:
<div id="headlineinput"><input type="text" id="headline"
value="<?php echo isset($_SESSION['webhipster_ask']['headline']) ?
$_SESSION['webhipster_ask'] ['headline'] : ''; ?>"
tabindex="1" size="20" name="headline" /></div>
I am new at using SESSION within php, so my quesiton is:
Is there a simpler way of achieving this without using a cookie like above?
Or what have i done wrong in the above mentioned code?
First thing is I'm pretty sure you're echo should have round brackets around it like:
echo (isset($_SESSION['webhipster_ask']['headline']) ? value : value)
That's not really the only question your asking though I think.
If you're submitting the data via a form, why not validate using the form values, and use the form values in your html input value. I would only store them to my session once I had validated the data and moved on.
For example:
<?php
session_start();
$errors=array();
if($_POST['doSubmit']=='yes')
{
//validate all $_POST values
if(!empty($_POST['headline']))
{
$errors[]="Your headline is empty";
}
if(!empty($_POST['something_else']))
{
$errors[]="Your other field is empty";
}
if(empty($errors))
{
//everything is validated
$_SESSION['form_values']=$_POST; //put your entire validated post array into a session, you could do this another way, just for simplicity sake here
header("Location: wherever.php");
}
}
if(!empty($errors))
{
foreach($errors as $val)
{
echo "<div style='color: red;'>".$val."</div>";
}
}
?>
<!-- This form submits to its own page //-->
<form name="whatever" id="whatever" method="post">
<input type="hidden" name="doSubmit" id="doSubmit" value="yes" />
<div id="headlineinput">
<input type="text" id="headline" value="<?php echo $_POST['headline'];?>" tabindex="1" size="20" name="headline" />
<!-- the line above does not need an isset, because if it is not set, it will simply not have anything in it //-->
</div>
<input type="submit" value="submit" />
</form>

How to get input field value using PHP

I have a input field as follows:
<input type="text" name="subject" id="subject" value="Car Loan">
I would like to get the input fields value Car Loan and assign it to a session. How do I do this using PHP or jQuery?
Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.
For Example, change the method in your form and then echo out the value by the name of the input:
Using $_GET method:
<form name="form" action="" method="get">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_GET['subject']; ?>
Using $_POST method:
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_POST['subject']; ?>
Example of using PHP to get a value from a form:
Put this in foobar.php:
<html>
<body>
<form action="foobar_submit.php" method="post">
<input name="my_html_input_tag" value="PILLS HERE"/>
<input type="submit" name="my_form_submit_button"
value="Click here for penguins"/>
</form>
</body>
</html>
Read the above code so you understand what it is doing:
"foobar.php is an HTML document containing an HTML form. When the user presses the submit button inside the form, the form's action property is run: foobar_submit.php. The form will be submitted as a POST request. Inside the form is an input tag with the name "my_html_input_tag". It's default value is "PILLS HERE". That causes a text box to appear with text: 'PILLS HERE' on the browser. To the right is a submit button, when you click it, the browser url changes to foobar_submit.php and the below code is run.
Put this code in foobar_submit.php in the same directory as foobar.php:
<?php
echo $_POST['my_html_input_tag'];
echo "<br><br>";
print_r($_POST);
?>
Read the above code so you know what its doing:
The HTML form from above populated the $_POST superglobal with key/value pairs representing the html elements inside the form. The echo prints out the value by key: 'my_html_input_tag'. If the key is found, which it is, its value is returned: "PILLS HERE".
Then print_r prints out all the keys and values from $_POST so you can peek as to what else is in there.
The value of the input tag with name=my_html_input_tag was put into the $_POST and you retrieved it inside another PHP file.
You can get the value $value as :
$value = $_POST['subject'];
or:
$value = $_GET['subject']; ,depending upon the form method used.
session_start();
$_SESSION['subject'] = $value;
the value is assigned to session variable subject.
For global use, you may use:
$val = $_REQUEST['subject'];
and to add yo your session, simply
session_start();
$_SESSION['subject'] = $val;
And you dont need jQuery in this case.
function get_input_tags($html)
{
$post_data = array();
// a new dom object
$dom = new DomDocument;
//load the html into the object
$dom->loadHTML($html);
//discard white space
$dom->preserveWhiteSpace = false;
//all input tags as a list
$input_tags = $dom->getElementsByTagName('input');
//get all rows from the table
for ($i = 0; $i < $input_tags->length; $i++)
{
if( is_object($input_tags->item($i)) )
{
$name = $value = '';
$name_o = $input_tags->item($i)->attributes->getNamedItem('name');
if(is_object($name_o))
{
$name = $name_o->value;
$value_o = $input_tags->item($i)->attributes->getNamedItem('value');
if(is_object($value_o))
{
$value = $input_tags->item($i)->attributes->getNamedItem('value')->value;
}
$post_data[$name] = $value;
}
}
}
return $post_data;
}
error_reporting(~E_WARNING);
$html = file_get_contents("https://accounts.google.com/ServiceLoginAuth");
print_r(get_input_tags($html));
If its a get request use, $_GET['subject'] or if its a post request use, $_POST['subject']
<form action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
<button type="submit" name="ok">OK</button>
</form>
<?php
if(isset($_POST['ok'])){
echo $_POST['subject'];
}
?>

Categories