I have HTML stored in a string. The markup contains form input fields called initval and endval which are the value attribute values I need. How can I get them from this string markup?
<form id="compute">
<input type="hidden" name="initval" value="tal:00far" />
<input type="hidden" name="endval" value="utl:80er" />
</form>
Presuming that the structure is very reliably like that, try the following:
$htmlCode = "...";
$matches = array();
if (preg_match_all('/name="(initval|endval)"\s+value="([^"]+)"/', $htmlCode, $matches)) {
$formValues = array_combine($matches[1], $matches[2]);
} else {
// error
}
This assumes only whitespace between the name and value attributes, you'll need to make a small change if it differs. preg_match_all() returns an array with the whole regexp match at [0], and then the individual group matches in their corresponding locations [1] & [2], the array combine takes one as keys, one as values and puts it together so you have an associative lookup to get your results.
If I have got your question right,
In HTML
<form id="compute" action="somefile.php" method="GET">
<input type="hidden" name="initval" value="tal:00far" />
<input type="hidden" name="endval" value="utl:80er" />
<input type="submit" value="Click!">
</form>
Upon clicking submit the data is sent the the php script, where it can be read as
$initval = $_GET['initval'];
$endval =$_GET['endval'];
EDIT: It seems I have got the question wrong, Sorry. :-(
Try Using htmldomlibraries for parsing html.
Related
Started learning PHP today so forgive me for being a noob. I have a simple HTML form where the user inputs 4 strings and then submits.
HTML form
<html>
<head>
<title>EMS</title>
</head>
<body>
<h1>EMS - Add New Employees</h1>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<table>
<tr><td>Enter a NAME:</td><td> <input type="text" name="name"></td></tr>
<tr><td>Enter a PPSN:</td><td> <input type="text" name="ppsn"></td></tr>
<tr><td>Enter a PIN :</td><td> <input type="text" name="pin"></td></tr>
<tr><td>Enter a DOB:</td><td> <input type="text" name="dob"></td></tr>
<tr><td></td><td><input type="submit" value="Add New Employee" name="data_submitted"></td></tr>
</table>
</form>
</html>
I want to implode the 4 elements in the $_POST["data submitted"] array to a string.
PHP
<?php
if (isset($_POST['data_submitted'])){
$employee = implode(",",$_POST['data_submitted']);
echo "employee = ".$employee;
}
?>
Why is it that when I run the project, Input the 4 strings into the form and submit that there is nothing contained within the employee string when its outputed? There is however a value in the employee string when I just implode the $_POST array like so without 'data_submitted'.
$employee = implode(",",$_POST);
The output of the $employee string is now - employee = will,03044,0303,27/5/6,Add New Employee
It contains the name,pps,pin,dob and this ADD New Employee value?
How do I just get the $employee string to contain just the name,pps,pin and dob from the $POST_[data_submitted] array?
If you wish to implode the submitted data, then you need to refer to the specific items, as follows:
<?php
$clean = [];
if (isset($_POST['data_submitted'])){
// one way to deal with possibly tainted data
$clean['name'] = htmlentities($_POST['name']);
$clean['ppsn'] = htmlentities($_POST['ppsn']);
$clean['pin'] = htmlentities($_POST['pin']);
$clean['dob'] = htmlentites($_POST['dob']);
$employee = implode(",",$clean);
echo "employee = $employee";
}
Never use submitted data without first checking to make sure that it is safe to do so. You need to validate it. Since the OP doesn't specify what kind of data the named inputs "ppsn", "pin", "dob" pertain to, this example does a minimum of validation. Each input might require more or something different.
Whether you're new or familiar with PHP, it is a good idea to frequently read the online Manual.
First, you need to know that php will treat value in the format: value="value here" as string.
So, calling implode(",",$_POST['data_submitted']); will return Add New Employee as declared here: <input type="submit" value="Add New Employee" name="data_submitted">.
From your question:
How do I just get the $employee string to contain just the name, pps, pin and dob from the $_POST[data_submitted] array?
Solution
1. Unset the <code>$_POST['data_submitted']</code> index in the $_POST super global variable
2. Implode it
// Unset the $_POST['data_submitted'] index
$post_data = unset( $_POST['data_submitted'] );
// Format the post data now
$format_post_data = implode( ",", $post_data );
// Escape and display the formatted data
echo htmlentities( $format_post_data, ENT_QUOTES );
I am building an HTML form - a simplified, two field version of which is below. The user is meant to enter something like the below string into the first field of the form:
https://www.facebook.com/dialog/feed?app_id=12345&link=http%3A%2F
%2Fbit.ly%2F12345&picture=https://website.com/horse-picture.jpg&name=Headline&
description=Description&redirect_uri=http%3A%2F%2Fwww.facebook.com%2F&
caption=Something
I am trying to split this string so that only the following part of the string is echoed into the second field of the form:
horse-picture.jpg
If the first field is empty, the second field is echoing back its own value. I've marked where the trouble is below. I've seen several threads on using explode, but the part of the string I'm looking to echo back isn't flanked with the same consistent characters, and the length of this string will vary, so preg_match also seems to be not a good option. Having this nested within a conditional is also throwing me off. Would very much appreciate help. Thanks!
<h2>THIS IS AN HTML FORM</h2>
<form action="sharefile.php" method="post">
<label for="decode">FB decode:<br /></label>
<input type="text" id="decoder" name="decoder" size="70" value="" /><br /><br />
<label for="img">Image (e.g. horse-picture.jpg):<br /></label>
<input type="text" id="img" name="img" size="70" value="
<?php if (strlen($_POST['decoder']) > 0)
//THIS IS WHERE THE TROUBLE STARTS
{SOMETHING GOES HERE}
//THIS IS WHERE THE TROUBLE ENDS
else {echo $_POST['img'];}
?>"
<input type="submit" value="Submit!" name="submit" />
</form>
Something like this might work. I believe you want to parse the picture URL, yes?
<?php
function scrub($string) {
// Parse the picture variable.
$matches = array();
$result = preg_match("/picture=([^\&]+)/", $string, $matches);
$url = $matches[1];
// Scrub the picture URL.
$result = preg_replace('/https?:\/\/[^\/]+\//', '', $url);
print_r($matches);
print_r($result);
}
scrub("https://www.facebook.com/dialog/feed?app_id=12345&link=http%3A%2F%2Fbit.ly%2F12345&picture=https://website.com/horse-picture.jpg&name=Headline&description=Description&redirect_uri=http%3A%2F%2Fwww.facebook.com%2F&caption=Something");
/*
Result:
Array
(
[0] => picture=https://website.com/horse-picture.jpg
[1] => https://website.com/horse-picture.jpg
)
horse-picture.jpg
*/
It looks like you're trying to parse URLs. PHP has functions for that, of course, albeit slightly weird functions, but it's PHP, so we expect that:
$url = '.. your massive URL inception ..';
$_url = parse_url($url);
print_r($_url);
parse_str($_url['query'], $query);
print_r($query);
$_url = parse_url($query['picture']);
print_r($_url);
$picture = basename($_url['path']);
var_dump($picture);
Example: http://3v4l.org/GKKmq#v430
Another method. Since this is a URL, first split on the question mark ? and take the second element, the query string. Now split on the ampersands & and loop through them looking for the key/value pair starting with "picture=". Once that is found grab the portion of the element after that many characters (8 characters in "picture="), then split the string on the forward slash / and grab the last element in that resulting array.
If $_POST['decoder'] equals:
https://www.facebook.com/dialog/feedapp_id=12345&link=http%3A%2F%2Fbit.ly%2F12345&picture=https://website.com/horse-picture.jpg&name=Headline&description=Description&redirect_uri=http%3A%2F%2Fwww.facebook.com%2F&caption=Something
Then:
list($d, $q) = explode('?', $_POST['decoder']);
$pairs = explode('&', $q);
foreach ( $pairs as $value ) {
if ( !(strpos($value, 'picture=') === FALSE) ) {
$picture = explode('/', substr($value, 8));
$picture = $picture[count($picture) - 1];
break;
}
}
echo $picture;
Outputs:
horse-picture.jpg
You should do something like this:
<?php echo '<input type="text" id="img" name="img" size="70" value="'.$whatyouwant.'"'; ?>
Hope it helps!
I am doing a project in which as per number getting by GET method, I display dynamic number of HTML Textbox for storing Multiple values. I am giving each textbox unique name+id in ascending manner starting from 1(Like textbox1,textbox2). Now I want that when I click on submit button, it should fire an insert statement which insert all textbox values at once. I know I can do by array, but my question is that how to get all textbox's value in an array and How to perform insert statement?
I have done following code:
Here is PHP Code for submit button:
$schedules = array();
if(isset($_POST['submit']))
{
for($d=1; $d<=$_GET['totalDay'] ;$d++)
{
array_push($schedules,$_POST['txtSchedule'.'$d']);
}
print_r($schedules);
}
Here is the html code:
<form method="post">
<table>
<tr>
<td>Day</td>
<td>Schedule</td>
</tr>
<?php
if(isset($_GET['tour_code']) and ($_GET['totalDay']!=1))
{
$tour_code = $_GET['tour_code'];
$total = $_GET['totalDay'];
$i=0;
do
{
$i=$i+1;
?>
<tr>
<td><?php echo $i;?></td>
<td>
<input name="txtSchedule<?php echo $i;?>" type="text" size="30"/>
</td>
</tr>
<?php
$start = date('Y-m-j',strtotime($start.'+1 days'));
}while($i!=$total);
}
?>
</table>
<input type="submit" name="submit" value="Add Tour Details" />
But I am getting an empty array.
Note: $total is coming through URLString's $GET method.
Below is the output of HTML:
Simplest thing first. You have an error, you can't use
array_push($schedules,$_POST['txtSchedule'.'$d']);
You must use DOUBLE QUOTES on the $d (single quotes won't evaluate d, it will literally read "txtSchedule$d" with a dollar sign, and not actually 0, 1,..., n)
array_push($schedules,$_POST['txtSchedule'."$d"]);
//or no quotes at all
array_push($schedules,$_POST['txtSchedule'.$d]);
(that may sovlve your problems)
But now let's get to how to make an array available to the $_POST object in the processing page via form naming conventions
You're not using array syntax, but you are oh-so close. In PHP, whatever is submitted needs to be of an expected format, and iterating txtSchedule0, txtSchedule1, ...txtScheduleN is not an Array(), but $_POST[] is an array that contains each (given what you've named your input fields, which is missing 1 small thing - square brackets).
What you need to do is be naming your inputs as an array is the array name followed by square brackets (arrayName[]), here is how you create an input array of the name txtSchedule (that way when you print_r($_POST['txtSchedule']) you get an Array())
<input name="txtSchedule[<?php echo $i;?>]" type="text" size="30"/>
I had the same issue when I started in PHP, you were forgetting the square brackets around [<?php echo $i;?>]
Just make sure that if you want to do an iteration over an array of inputs:
for($i=0; $i < count($_POST['txtSchedule']); $i++){
echo "They entered " . $_POST['txtSchedule'][$i] . " in the $i" . "th position";
}
... you have used the <input name="arrayName[$i]"> sytax, or even more simply <input name="arrayName[]"> for it to auto-magically generate an array on submit in the order the inputs were in the HTML page. The naming convention is so important, and since you have it wrong (you used arrayName0, arrayName1, ... arrayNameN instead of arrayName[0], arrayName[1], ... arrayName[n]), it will never be available to you as an array.
if i understand your question correctly you are trying to retrive user input from each textbox and save it in an array?
if so I would use jquery to select all textboxes and loop through them and retrive the value
If you are looking purely at the SQL syntax, then you can just append extra records to insert at the end of your query by providing more value sets:
INSERT INTO myTable (fieldName1, fieldName2) values ("Value1A", "Value1B"), ("Value2A", "Value2B")
If you looking at the PHP logic, then my first suggestion is to use the http POST method instead of GET. Then start with processing the $_POST fields:
$data= array();
foreach($_POST as $key => $value) {
if (preg_match('/^TextBox\d+$/', $key)) {
$data[] = $mysqli->real_escape_string($value);
}
}
The construct the SQL query based on the available data
if (count($data) > 0) {
$sql = 'INSERT INTO `myTable` VALUES("' . implode('"),("', $data).'")';
// log query
// execute query
// process query results
// redirect user to a thankyou page
header('Location: thankyou.php');
}
Note that the code assumes that you have a mysqli connection instance available at $mysqli
Not sure if this is what you are looking for but should give you at least a start..
String []ar=request.getParameterValues("name");
String cmd=request.getParameter("cmd");
if(cmd==null) cmd="";
if(cmd.equals("Submit")){
for(int i=0;i<ar.length;i++) {
insert logic;
<form method="post" action="page3.jsp">
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/><input type="text" name="name"/>
<br/> <input type="submit" value="Submit" name="cmd"/>
</form>
Orignal post http://www.daniweb.com/web-development/jsp/threads/197777/insert-dynamic-textbox-value-in-database
This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}
Sorry if this has been answered somewhere; I'm not quite sure how to phrase the problem to even look for help.
Anyway, I have a form with three text input boxes, where the user will input three song titles. I have simple PHP set up to treat those input boxes as an array (because I may want, say, 100 song titles in the future) and write the song titles to another document.
<form method="post">
<input type="text" name="songs[]" value="" />
<input type="text" name="songs[]" value="" />
<input type="text" name="songs[]" value="" />
<button type="submit" name="submit" value="submit">Submit</button>
</form>
<?php
if (isset($_POST['submit'])) {
$open = fopen("test.html", "w");
if(empty($_POST['songs'])) { }
else {
$songs = $_POST['songs'];
foreach($songs as $song) {
fwrite($open, $song."<br />");
};
};
};
?>
This correctly writes the song titles to an external file. However, even when the input boxes are empty, the external file will still be written to (just with the <br />'s). I'd assumed that the if statement would ensure nothing would happen if the boxes were blank, but that's obviously not the case.
I guess the array's not really empty like I thought it was, but I'm not really sure what implications that comes with. Any idea what I'm doing wrong?
(And again, I am clueless when it comes to PHP, so forgive me if this has been answered a million times before, if I described it horribly, etc.)
you should check each entry:
<?php
if (isset($_POST['submit'])) {
$open = fopen("test.html", "w");
foreach($_POST['songs'] as $song) {
if(!empty($song)) {
fwrite($open, $song."<br />");
};
};
};
?>
Indeed $_POST['songs'] is not an empty array, it's an array of 3 empty strings.
You can use the following to clear out all the empty values:
$song_titles = array_filter($_POST['songs'], function($title) {return (bool) trim($title);});
You could also put some other checks into that callback function (whitelist only alphanumerics and some other characters (spaces, dashes etc)).
If you have a version of PHP older than 5.3 you'll have to define the callback function separately, see http://us2.php.net/manual/en/function.array-filter.php