How do I dynamically append something to a variable in PHP? - php

I have a form like so:
<?php if (isset($_POST['artist'])) {
// do something
} ?>
<form name="admin_on_artist_<?php echo $artist->ID; ?>" action="" method="POST">
<p class="artist-negative">
<label for="artist"><input type="checkbox" name="artist_<?php echo $artist->ID; ?>" id="artist_<?php echo $artist->ID; ?>"> Check this?</label>
</p>
<button type="submit">Update</button>
</form>
On the page in question, this form is shown many times in a foreach loop. However, when I submit any given form, it updates all of the forms, which is not what I want.
How can I append the $artist->ID to $_POST['artist'] so that I get something like:
$_POST['artist_1'] to match the checkbox attributes?

You could pair your foreach that generates the frontend form markup with a foreach that processes the form submission. Something like:
<?php
$regex = '/^artist_([0-9]+)$/'
foreach (array_keys($_POST) as $key) {
if (preg_match($regex,$key,$matches)) {
$artistId = (int)$matches[1];
// do something with $_POST[$key] according to $artistId
}
}
This works for a single field submission or a multiple field submission.
Alternatively, you could do something on the frontend in JS (as #smith suggests in the comments) to ensure the form submission always has the same, well-known keys, populating a hidden form with the current submission. With this approach you would have to add another field to the form that contains the ID.

The solution for this was much simpler than I was able to grasp at first, but basically I just had to do this, the key difference between this and my original question being the first two lines:
<?php $artist_form_id = 'artist_'.$artist->ID;
if (isset($_POST[$artist_form_id])) {
// do something
} ?>
<form name="admin_on_artist_<?php echo $artist->ID; ?>" action="" method="POST">
<p class="artist-negative">
<label for="artist"><input type="checkbox" name="artist_<?php echo $artist->ID; ?>" id="artist_<?php echo $artist->ID; ?>"> Check this?</label>
</p>
<button type="submit">Update</button>
</form>

Related

Multiple buttons inside single php form

So i have this loop that shows data from my database, each of the rows will create a button that will be used later for activating/deactivating user. Now my problem is after clicking the button the output from the action.php is something like this
action.php?course_action=1&action=activate&course_action=2&action=activate&course_action=3&action=activate&course_action=4&action=activate&course_action=5&action=activate&course_action=6&action=activate&course_action=7&action=activate&course_action=8&action=activate
it looks like after pressing the button it stores all the value from input, the expected output is something like this only
action.php?course_action=1&action=activate
I completely forgot how to use php or just an excuse. Anyways hope you guys share some knowledge
<form action="db_connection/action.php" method="get">
<?php
$learningcenters = json_decode(learningCenters());
foreach ($learningcenters as $obj) {
echo '<tr>
<td>'.$obj->lc_id.'</td>
<td class="txt-oflo">'.$obj->lc_name.'</td>
<td>'.$obj->lc_emailadd.'</td>
<td>'.$obj->lc_contactnum.'</td>
<td class="txt-oflo">'.$obj->lc_datereg.'</td>
<td><span class="text-success">'.$obj->lc_timereg.'</span></td>
<td>
<input type="hidden" name="course_action" value='.$obj->lc_id.'>
<input type="hidden" name="action" value="activate"/>
<input type="submit" class="act-user" value="Activate User"></input>
</td>
</tr>';
}
?>
</form>
A submit button with a name attribute is included into the form data when it is clicked. To manage a caption differing from the value, use the button element. There should be no reason to prevent additional form data from being sent.
To be more conform to PHP as an embedded language, you should frequently close <?php tags rather than generating HTML outputs from strings. This also helps you to develop an MVC or similar pattern.
To get additional data per button click being sent, consider a composed string format, e.g. : as a delimiter.
<?php
var_dump($_GET);
?>
<form>
<?php
foreach ([3,5,6] as $id)
{
?>
<button name="action" type="submit" value="activate:<?php echo $id;?>">Activate</button>
<?php
}
?>
</form>
You can even use array parameters. This approach also enables you to perform an action on multiple items selected by checkboxes at once.
<?php
var_dump($_GET);
if(isset($_GET['action']) && is_array($_GET['action']))
foreach ($_GET['action'] as $id => $action)
echo "<div>$id: $action</div>"
?>
<form>
<?php
foreach ([3,5,6] as $id)
{
?>
<button name="action[<?php echo $id;?>]" type="submit" value="activate">Activate</button>
<?php
}
?>
</form>

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>

PHP: url parameters

i have a question about formatting the URL parameters in php
page 1 can have these 2 url
http://somewhere.com/page1.php?foo=1
and
http://somewhere.com/page1.php
now on page 1, when i click a button, i want it to redirect to its self but with an additional parameters in the URL like so
http://somewhere.com/page1.php?foo=1&bar=2
or
http://somewhere.com/page1.php?bar=2
depending on the current url. How can i do this in php?
thanks,
Vidhu
First, check if a certain $_GET parameter is set, using isset.
If it is, echo a certain link. If not, echo a different link.
if( !isset($_GET['bar']) ){
echo 'link';
}
else{
echo 'link';
}
You can do a simple get system, So you will need to check if ?foo=1 is set if it is you can echo its content. If you want to show content for bar=2 check if its set and echo its content. This is just a simple way there more ways though.
The following form will submit to the same url with parameters added.
<form action="<?php echo "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>" method="get">
<?php
// Iterate through our query string and add each key value pair as a hidden input
foreach ($_GET as $key => $value)
{
?>
<input type="hidden" name="<?php echo $key; ?>" value="<?php echo $value; ?>"/>
<?php
}
?>
<!-- new parameter to add -->
<input type="hidden" name="foo" value="1"/>
<input type="submit"/>
</form>
Simply you can do with $_SERVER['PHP_SELF']
For example
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="get">
<input type="hidden" name="foo" value="1"/>
<input type="submit"/>
</form>
Here the htmlentities() is used to avoid PHP_SELF exploitation as a security precaution
If you wish to avoid hidden input fields you can append the query parameters like action="<?php echo $_SERVER['PHP_SELF']; ?>?foo=1&bar=2"
I'm using these PHP functions to help me build urls correctly:
parse_str()
parse_url()
http_build_query()
http-build-url()
Example:
<?php
function add_parameters($parameters) {
parse_str($_SERVER['QUERY_STRING'], $old_parameters_as_array);
return $_SERVER['PHP_SELF'].'?'.http_build_query(array_merge($old_parameters_as_array, $parameters));
}
echo 'Link';

Two forms with multiple submit buttons in single PHP file

I am trying to write a dynamic form using PHP. I'd like to have a single webpage that contains two forms:
The upper form allows to search for an element in the mysql database, e.g., for a name
The lower form shows the data that is associated with this name in the database
If I press on the "Search" button of the upper form, then the the lower form is shown and the text fields are filled with data from the database that belong to this name. If I change the user name to some other value and press again "Search", then the data that is associated with the new record is shown and so on.
The lower form also has a button "Update" which allows to transfer changes made to the text boxes (in the lower part) to the database.
Now, I have the following problem: In my script I set initially the value of name (from the upper form) to "". When I then press the "Search" button, then the lower part of the form is shown and the corresponding data is shown in the lower part. When I then press the "Update" button, then the text field associated with name is set to the empty string. This is because in my script I set initially name to the "". I'd like that in this case the data entered in the upper form is not changed, i.e., it stays the same.
I guess, I am missing something here. There is probably an easy solution for this and I am doing something fundamentally wrong. It'd be great if you could help me.
That's what I tried... I deleted lots of details, but I guess that can give you an idea what I am trying to do. Notice that the whole code is in the file update.php.
<?php
function search_bus($mysql, $name)
{
// do some stuff here...
}
function update_bus($mysql, $b_id)
{
// do some stuff here...
}
// some global variables
$b_id = 0;
$username = ""; // username of business
// get b_id that corresponds to username
if (isset($_REQUEST['search']))
{
$b_id =0; // business id
if (isset($_POST['user']))
{
$username = $_POST['user'];
$b_id = search_bus($mysql, $username);
}
}
elseif(isset($_REQUEST['update']))
{
update_bus($mysql, $b_id);
}
?>
<h2>Search:</h2>
<form name="search_bus" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="submit" value="Suchen" name="search"/>
</form>
<?php
if($b_id != 0)
{
?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<-- some form follows here -->
<?php
}
?>
I think what you're missing is to create a HTML Hidden field to keep the value of Name variable.
<input type="hidden" name="name" value="<?php print $nameVar ?>" />
Add this input to both forms so you can keep the value no matter what button the user clicks.
Hope this helps.
Adding code to verify the
<h2>Search:</h2>
<form name="search_bus" method="post"
action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<input type="submit" value="Suchen" name="search"/>
</form>
<?php if($b_id != 0) { ?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];>">
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<-- some form follows here -->
<?php } ?>
Dont initialize $b_id if it already comes into the http request.
if (!isset($_POST['b_id']))
{
$b_id = 0;
}
else
{
$b_id = $_POST['b_id'];
}
This way you can alway remember the last selected value of b_id.
Hope this can help you.

Searching for Array Key in $_POST, 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

Categories