Can I make a PHP function to create text input fields? [duplicate] - php

This question already has answers here:
Print string with a php variable in it
(4 answers)
Closed 11 months ago.
So I'm going to be making a couple forms with multiple text input boxes, so I figured making a function to help automate this would be a good idea.
Below is the function I've come up with: however, the results I've gotten seem to be really weird, being a combination of "echo" and a mess of single quotes. Does everything look correct in there? I'm new to PHP, so I'm really sorry if it's an obvious mistake I'm missing.
function makeTextInputField($name)
{
echo '<label for = "<?php $name ?>"> <?php ucfirst($name) ?> </label><input type = "text" name = "<?php $name?>"></input>';
}

You should not use any more tag inside the php
function makeTextInputField($name)
{
echo '<label for = "'.$name.'">'.ucfirst($name).'</label><input type = "text" name = "'.$name.'" />';
}

Working Demo
Because you can insert line breaks in strings in PHP, you can make your function more readable by using variables inside it:
<?php
function makeTextInputField($name) {
$text = ucfirst($name);
echo "
<label for='{$name}'>{$text}</label>
<input type='text' name='{$name}' />
";
}
?>
And whenver you want to use it:
<h1>Welcome</h1>
<?php makeTextInputField('email'); ?>
OUTPUT
<h1>Welcome</h1>
<label for='email'>Email</label>
<input type='text' name='email' />

Your problem is that inside PHP code you're opening new PHP tags, which actually are not required. Try this function and see if it's working for you:
function makeTextInputField($name)
{
echo sprintf('<label for="%s">%s</label> <input type="text" name="%s"></input>', $name, ucfirst($name), $name);
}

Try with sprintf.
function textInput($name)
{
$html = '<label for="%1$s">%2$s</label><input type="text" name="%1$s"/>';
echo sprintf($html, $name, ucfirst($name));
}

<?php
class DeInput
{
protected $_format = '<div>
<label for="%s">%s</label>
<input class="formfield" type="text" name="%s" value="%s">
</div>';
public function render($content,$getFullyQualifiedName,$getValue,$getLabel)
{
$name = htmlentities($getFullyQualifiedName);
$label = htmlentities($getLabel);
$value = htmlentities($getValue);
$markup = sprintf($this->_format, $name, $label, $name, $value);
return $markup;
}
}

Putting PHP code inside quotation marks is somewhat bad practice so I using (.) point to combine strings can be used.
Here is my example:
function makeTextInputField($name) {
echo '<label for="'. $name .'">'.ucfirst($name).'</label>';
echo '<input type="text" name="'.$name .' />';
}

use return intead of echo, and it will be easier to manipulate with result.
Also you can split elements generation into different functions for more flexibility:
function createLabel($for,$labelText){
return '<label for = "'.$for.'"> '.ucfirst($labelText).'</label>';
}
function createTextInput($name,$value,$id){
return '<input type = "text" name = "'.$name.'" id="'.$id.'">'.$value.'</input>';
}
function myTextInput($name,$value,$labelText){
$id = 'my_input_'.$name;
return createLabel($id,$labelText).createTextInput($name,$value,$id);
}
echo myTextInput('email','','Type you email');

function makeTextInputField($name)
{
echo '<label for = "'.$name.'"> '.ucfirst($name).'</label><input type = "text" name = "'.$name.'"></input>';
}
That should work.
You are already in php. So no need for the <?php tags. Concatenate strings together with a .

Related

PHP -- How to replace string value to user input?

Can someone help me to figure out how to replace a defined string value with user input value? I am quite new in PHP programming and could not find an answer. I saw a lot of ways to replace string on the internet by using built-in functions or in arrays, but I could not find out the right answer to my question.
Here is my code:
$text = "Not found";
if ( isset($_GET['user'])) {
$user_input = $_GET['user'];
}
// from here I I tried to replace the value $text to user input, but it does not work.
$raw = TRUE;
$spec_char = "";
if ($raw) {
$raw = htmlentities($text);
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>"; *# displays "Not found"*
} elseif (!$raw == TRUE ) {
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
I appreciate your answers.
Lets run over your code, line by line.
// Set a default value for $text
$text = "Not found";
// Check if a value has been set...
if (isset($_GET['user'])) {
// But then create a new var with that value.
// Why? Are you going to change it?
$user_input = $_GET['user'];
}
// Define a few vars
$raw = TRUE;
$spec_char = "";
// This next line is useless - Why? Because $raw is always true.
// A better test would be to check for $user_input or do the
// isset() check here instead.
if ($raw) {
// Basic sanity check, but $text is always going to be
// "Not found" - as you have never changed it.
$raw = htmlentities($text);
// render some HTML - but as you said, always going to display
// "Not found"
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>";
} elseif (!$raw == TRUE ) {
// This code is never reached.
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
// I have no idea what this HTML is for really.
// Guessing this is your "input" values.
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
Just a guess I think you really wanted to do something more like this:
<?php
// Check if a value has been posted...
if (isset($_POST['user'])) {
// render some HTML
echo '<p style="font-style:bold"> PIN '.htmlspecialchars($_POST['user']).'</p>';
}
?>
<form method="post" action="?">
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>

PHP code for calculator. validated but not working

So I have a calculator coded in PHP and I have validated it but there is a problem with this, its not working. I have used server side validation. Validation works well. But it doesn't do any work,for example, when I give an input like 2+8, it gives an output of 8888. This is very confusing. Please help me out with this. Thanks.
HTML page is here:
<html>
<head>
<title>Calculator</title>
</head>
<body>
<form method = "post" action = "calc.php">
<input type = "text" name = "val_1"/>
<select name="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type = "text" name = "val_2"/>
<input type = "submit" value = "calculate" name = "checker"/>
</form>
</body>
</html>
And here is the PHP code.
<?php
if(isset($_POST['checker'])) {
#Clean all values
function cleanStr($str){
$str = trim($str);
$str = addslashes($str);
$str = htmlspecialchars($str);
return $str;
}
$val_1=cleanStr($_POST['val_1']);
$val_2=cleanStr($_POST['val_2']);
$operator=$_POST['operator'];
function emptyFileds($ar){
if(!is_array($ar)){
echo "It must be an array";
return false;
}
#loop through each field to check for empty values
foreach($ar as $key => $value){
$value = CleanStr($value);
if(empty($value)){
echo $key . " must not be empty";
return false;
}
}
return true;
}
if(!emptyFileds($_POST)){
exit();
}
if($operator==="+"){
echo "Sum is " . $val_1+$val_2;
}
}
?>
Please change the original line
echo "Sum is " . $val_1+$val_2;
to
echo "Sum is " . ($val_1+$val_2);
It's a operator precedence issue as . is executed first. Therefore you append 2 to "Sum is " and then increment the string by 8 which results in this odd behavior.
Also, some nitpicking on your code, I will just name 3 issues:
requesting a parameter with cleanStr() is not a good idea, it's better to use
$val_1 = (int)trim($_POST['val_1']);
as $val_1 will be an integer after that line. This might be important for later development e.g. to compare numbers.
indent correctly, reading your code is hurting my eyes
the whole emptyFileds()thing is unnecessary, simply check whether the 3 parameters are filled or not, it's simple and it's readable.

How to put quotes correctly in this statement

I need to return an input box from a function but i could put the quotes correctly. Any one please help me to solve the error.
<?php
return "
<input style='background-color:#CCC;'type='text' name='contactName' id='contactName' value='".if(isset($_POST['contactName'])) echo $_POST['contactName']."' class='requiredField' />";
use this
<?php
return '
<input style="background-color:#CCC;" type="text" name="contactName" id="contactName" value="'.(isset($_POST['contactName'])?$_POST['contactName']:'').'" class="requiredField" />';
for inline if that will output somthing use this syntax:
( condition ? 'the thing that will return when condition true' : 'the false returned string' )
<?php
if(isset($_POST['contactName'])) {$contactname=$_POST['contactName'];}
return "<input style='background-color:#CCC;'type='text' name='contactName' id='contactName' value='".$contactname."' class='requiredField' />";
?>
Instead of writing in a single line, you can break it instead and return the value.
if(isset($_POST['contactName'])) {
$value = $_POST['contactName'];
} else {
$value = "";
}
$input = '<input style="background-color:#CCC;" type="text" name="contactName" id="contactName" ';
$input .= 'value="'. $value .'" ';
$input .= 'class="requiredField" ';
$input .= '/>';
return $input;
Also i can see that you are assigning a value without processing it. This is not correct.
So, it should be something like:
if(isset($_POST['contactName'])) {
$value = stripslashes($_POST['contactName']);
} else {
$value = "";
}
You can also use any other escape method if you are using PDO.
Another simple solution
<?php
if(isset($_POST['contactName']))
{
return "<input style='background-color:#CCC;'type='text' name='contactName' id='contactName' value='".$_POST['contactName']."' class='requiredField' />";
}
?>

undefined ID in javascript when ID is passed from PHP variable

I've done some searches and I've come up with no clear answer. I'm not a javascript person at all and am pretty clueless. PHP I understand however, and to me this should work. I should also note, that this script used to use document.all for it's javascript, which I've tried to update to getElementById() when possible (since document.all was throwing an error in firebug).
Now for the most part, the page displays fine, albeit without the javascript changes that are supposed to happen.
I must also apologize for the archaic nature of the code, I inherited this code when I took over as internet guy for our gaming club. This code is for the purchase of fictional items using fictional credits.
When I click an item to "buy" it (or maybe not whichever) The background of that row is supposed to turn green, and the credits are supposed to be subtracted from my total account (or reverse if I uncheck the box). Clicking the submit button adds this stuff I clicked to another sheet, and subtracts the actual amount from my account.
Currently I get a "tr615 is undefined" error This is the PHP generated code for the element as shown below.
If someone can help me figure this out it would fantastic. I just can't seem to find an answer after a few days of searching google and here.
PHP Snippet of relevent code: (we use custom functions on our site ie: entry)
For instance say $id=615
<?php
while (list ($id, $name, $class, $desc, $range, $damage, $cost,$hide) = entry ($items) )
{
if ($hide =='0')
{
$JavaScriptArrayParms .= '"' . $id . '",';
$list .= $id . ',';
?>
<tr id="tr<?php echo $id; ?>"> //Thus tr615 for this example
<td>
<input type="checkbox" name="chk<?php echo $id; ?>" onclick="updateStoreTable(this.form, this, <?php echo $id; ?>)" />
<input type="hidden" name="cost<?php echo $id; ?>" value="<?php echo $cost; ?>" />
</td>
<td><?php echo $name; ?></td>
<?php if (! in_array($catid, $noclass)){ echo "<td>$class</td>";}?>
<td><?php echo $desc; ?></td>
<?php if (! in_array($catid, $norange)){ echo "<td>$range</td>";}?>
<td><?php echo $damage; ?></td>
<td><?php echo $cost; ?></td>
</tr>
<?php
}
}
?>
</table>
<input type="hidden" name="list" value="<?php echo $list; ?>" />
<input type="button" value="Purchase!" onclick='validatePurchase(this)' />
<input type="reset">
</form>
Relevant JS: (which used to be document.all.store... or just document.all.. in some cases. I hope I fixed it the right way)
<script language="javascript">
var startmoney = <?php echo $currMoney; ?>;
function canAfford(t,id)
{
if(t.checked) return;// don't touch if checked for buying.
//alert("canAfford("+t+","+id+");");
//t.disabled = false;
eval("document.store.getElementByID(foo).disabled = false;");
eval("document.store.getElementByID(foo).checked = false;");
eval("document.getElementByID(tr"+id+").style.background = '#000000';");
}
function cantAfford(t,id)
{
//alert("cantAfford("+t.disabled+","+id+")-- "+t+";");
//alert("before disable");
//t.disabled = true;
eval("document.store.getElementByID(chk"+id+").disabled = "+true+";");
//alert("After disable");
eval("document.store.getElementByID(chk"+id+").checked = false;");
eval("document.getElementByID(tr"+id+").style.background = '#555555';");
}
function getCost(id)
{
return eval("document.store.getElementByID(cost"+id+").value");
}
function buying(t,id)
{
eval("document.getElementByID(tr"+id+").style.background = 'green';");
document.store.credits.value -= getCost(id);
}
function notbuying(t,id)
{
eval("document.getElementByID(tr"+id+").style.background = '#000000';");
var creds = new Number(document.store.credits.value);
var cost = new Number(getCost(id));
document.store.credits.value = (creds + cost);
}
function updateStoreTable(f,t,id)
{
var ids = new Array(<?php echo $JavaScriptArrayParms; ?>);
if(t.checked)
buying(t,id);
else
notbuying(t,id);
for(i = 0; i<ids.length; i++)
{
cost = new Number(getCost(ids[i]));
creds = new Number(f.credits.value);
//alert("COST: " +(cost)+"\nCREDITS: "+creds+"\nID: "+ids[i]);
// alert("'"+ (cost) + "' > '" + (creds) +"'\n"+(eval(cost > creds)));
// alert("f.chk"+ids[i]+".checked");
if(eval("f.chk"+ids[i]+".checked")) { continue; } //ignore already carted items
if(eval(cost > creds))
cantAfford(eval("f.chk"+id),ids[i]);
else
canAfford(eval("f.chk"+id),ids[i]);
}
}
1st issue:
it has to be getElementById()
(a lower-case d at the end)
2nd:
When using eval, the code will be evaluated as:
document.getElementById(tr615).style.background = '#000000';
..what will force the error, because the tr615 is not enclosed by quotes, so javascript expects a variable tr615.
the line must look like this:
eval("document.getElementById('tr"+id+"').style.background = '#000000';");
But: Why do you use eval here, this can be done without eval:
document.getElementById('tr'+id).style.background = '#000000';

Working with strings and variables from html forms to php

I have been struggling with a problem working in both html and php.
in my html, i have a form tag that includes:
<input type="text" name="car1" size="4" value="" /> car1
In my php, i have this:
$car1 = 'my favorite car is ' . $_POST['car1'];
echo $car1;
I am trying to figure out a way so that when the user does not input anything into the car1 field in html, echo $car1; will print nothing or blank but when the user does input something, $car1 will echo my favorite car is $car1.
I tried using if(empty() and if(isset() but i am having issues to make it work for some reason.
Any ideas to do this properly? thanks for the help!
if(!empty($_POST['car1'])){
$car1 = 'my favorite car is ' . $_POST['car1'];
echo $car1;
}
Try:
if ($_POST["car1"] !== "") {
$car1 = "my favourite …";
} else {
$car1 = "";
}
As simple as:
if (!empty($_POST['car1'])) {
echo 'my favorite car is ' . htmlentities($_POST['car1']);
}
See here which values are regarded as empty. If you want more control, use something like:
if (isset($_POST['car1']) && $_POST['car1'] !== '')
You should
always check whether keys in $_POST are !empty or isset before using them
always HTML escape user supplied data for output
use labels:
<input type="text" name="car1" size="4" id="car1Input" value="" />
<label for="car1Input">car1</label>
if(isset($_POST["car1"]))
$car1 = "my favorite car is $_POST["car1"]";
else
$car1 = "";
return $car1 //if function or
echo $car1; //if general

Categories