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
Related
i'm trying to find a way to erase the text screen from my calculator when you press the +/- button so it acts more like a real calculator.
i'm pretty new to php (a week or two) so i'm still learning but i cant figure this out.
the php file returns html code where in i have a <input type='text' named result value='$value'>
(calculator screen).
and a series of submit buttons with a name and value of 1,2,3,+,...
when i press a button a char gets added to the string in result.
when i press on the '=' button it reads the string with eval();
and calculates it.
iv'e tried with a function but i cant figure it out some ideas or tips would be very much welcome.
$value = '';
if(isset($_GET['result']))
$value.=$_GET['result'];
if(isset($_GET['1']))
$value .='1';
if(isset($_GET['2']))
$value .='2';
//and so on ...
if(isset($_GET['+']))
$value .='+';
if(isset($_GET['-']))
$value .='-';
if(isset($_GET['='])){
eval('$result = '.$value.';');
$value = $result;}
return "<form action='index.php' method='get'>
<br><input type='text' name='result' value='$value'><br>
<input type='submit' name='1' value='1'>
<input type='submit' name='2' value='2'>
//and so on ...
(the rest of the html code is loaded somewhere else)
This PHP code below will execute JavaScript code to clean the input field,
echo"<script>document.getElementsByName('result')[0].value = '';</script>
This should resolve your question but i have to tell you that PHP isn't suitable choice to make a web calculator, You need to use JavaScript to make a real calculator without refreshing the page.
Please copy this code below to an HTML file and try it so you can get an idea how it works.
First Number
<input type="text" id="firstNumber" value="6" /><br>
Second Number
<input type="text" id="secondNumber" value="5" /><br>
Result
<input type="text" id="result" /><br>
<button type="button" onclick="Calculate();">Calculate</button>
<script>
function Calculate(){
let firstNumber;
let secondNumber;
firstNumber = document.getElementById("firstNumber").value;
secondNumber = document.getElementById("secondNumber").value;
document.getElementById("result").value = Number(firstNumber) + Number(secondNumber);
// "Number" is to tell javascript its a number not a string/text,
// without "Number" it will concat both numbers
}
</script>
You should use brackets for your conditions, especially if you nest them:
if(isset($_GET['result'])) {
$value .= $_GET['result'];
}
And your indentation makes it look like Python, someone reading it would mistake it for a condition nested in another condition and believe that your if(isset($_GET['2'])) is true only if if(isset($_GET['1'])) is also true.
A switch is a better solution here (and even better for the operators since you probably only have four of them), but in any case, you should assign each term of your operation in a single variable.
So this is my code for the first_name. I have no clue why it does not work whenever I add an entry.
First Name: <input type="text" name="first_name" value="<?php function convertString($first_name){
$first_name=htmlentities(strip_tags($first_name));
$lowercaseFName = strtolower($first_name);
$ucFName = ucwords($lowercaseFName);
return $ucFName;} ?>"/> // I changed it with echo but nothing changed.
My code doesn't change the format of the text.I tried inputting in all caps and it will show as is. Am I missing something or doing it wrong?
The inputted text if all in capital must still be shown as Camel Case format in the table, like this:
First Name: MARIA YLONA (in the form)
First Name: Maria Ylona (in the table) - this is another .php file for viewing of the data entries
Seeing you didn't post your html form or how it's used, am submitting the following as a successful piece of code and using !empty() against a POST array with form tags and an isset() for the submit input.
Btw, functions and variables assignments should be used seperately than in inputs/form elements.
Create a function, then pass it inside the input with the parameter.
<?php
function convertString($first_name){
$first_name=htmlentities(strip_tags($first_name));
$lowercaseFName = strtolower($first_name);
$ucFName = ucwords($lowercaseFName);
return $ucFName;
}
if(isset($_POST['submit'])){
if(!empty($_POST['first_name'])){
$first_name = $_POST['first_name'];
}
}
// here initialize $first_name to something meaningful
?>
<form method="post">
First Name: <input type="text" name="first_name" value="<?php echo(convertString($first_name)) ?>"/>
<input type="submit" name="submit" value="Submit">
</form>
Footnotes:
In regards to what Marc mentioned about McDonald's -> mcdonald's -> Mcdonald's and my MacDonald in comments...
Consult the following here on Stack which may prove to be useful:
Given upper case names transform to Proper Case, handling "O'Hara", "McDonald" "van der Sloot" etc
Data Cleanup, post conversion from ALLCAPS to Title Case
You mention the use of a database, but haven't posted relative code and would be beyond the scope of the question.
To clarify what aynber meant in the comments:
<?php
function convertString($first_name){
$first_name=htmlentities(strip_tags($first_name));
$lowercaseFName = strtolower($first_name);
$ucFName = ucwords($lowercaseFName);
return $ucFName;
}
// here initialize $first_name to something meaningful
?>
First Name: <input type="text" name="first_name" value="<?php echo(convertString($first_name)) ?>"/>
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);
}
}
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.
I've just discovered the email-address-saving form on my website does not work on Opera and Internet Explorer (7 at any rate), and possibly other browsers. Works fine with Firefox. Unfortunately I'm not a developer and no longer have any contact with the guy who wrote the code for the form so I've no idea how to fix it. I assume the problem has something to do with the code below:
<?php
$str = '';
if (isset($_POST['submit']))
{
if(!eregi("^[[:alnum:]][a-z0-9_.-]*#[a-z0-9.-]+\.[a-z]{2,4}$", $_POST['email'])) {
$str = "<span style='color: red'>Not a valid email address</span>";
} else {
$file = 'emails.txt';
$text = "$_POST[email]\n";
if (is_writable($file)) {
if (!$fh = fopen($file, 'a')) {
exit;
}
if (fwrite($fh, $text) === FALSE) {
exit;
}
fclose($fh);
}
header('Location: thankyou.html');
}
}
?>
and then the body bit:
<form action="index.php" method="post">
<input type="text" name="email" style="width: 250px;" />
<input type="image" src="img/button-submit.png" name="submit" value="Submit" style="position: relative; top: 5px; left: 10px" />
</form>
<?php echo $str ?>
Anybody feeling pity for a helpless non-dev and have an idea what's not working here?
This is being caused by the fact that the submit input is of type 'image'. On submit, IE7 only returns the x and y coords of the click.
This should do the trick:
Replace:
if (isset($_POST['submit']))
With:
if (isset($_POST['submit']) || isset($_POST['submit_x']))
It is a browser based issue
in your form, you have used <input type="image" />
IE doesn't pass name/value pairs for image type input, instead it only sends the key_x/value_x and key_y/value_y pairs
you probaly want to use <input type="submit" /> as replacement/addition, since this is completely supported on all types of browsers (think also about text browsers please, i still use them.)
Unfortunately, the error, if any at all, is going to be between the Browser and the server, not PHP. If you could provide some details like the HTML form that isn't working in IE7, then we may be able to help out more.
Your form element is self-closed. Remove the trailing / in the opening tag and it should work. (Er, it might work. Either way, there shouldn't be a trailing slash.)
Assuming that the php in your code is in the same file as the form ... you might try adding the name of your php file to the form's action.
<form action="" method="post">
... becomes ...
<form action="name_of_php_file" method="post">
Include a hidden field in your form that will only be valid and present if you submit the form. Something like:
<input type="hidden" name="checkemail" value="1" />
Then, in your PHP, change the if-condition to check for this particular variable:
<?php
$str = '';
if (isset($_POST["checkemail"]))
{
//-- rest of your code
}
?>
This will allow you to keep the image as the submit button and work across browsers which differ in how they send the value, if at all, of the name of image type buttons.
I know this doesn't fix your problem, but I don't like the line:
$text = "$_POST[email]\n";
Is that not bad practice? I haven't used PHP for years, but I think you should change it to
$text = $_POST['email'] . "\n";
or something like that. Using $_POST[email] without the quotes around the array key causes PHP to first look for a constant named 'email'. Only after not finding it will it convert email to a string and then pull the value out of the associative array. Just wasted CPU power.