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
Related
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>
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.
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 .
I have a script wher users can find exercise from a database, I have checkboxes for the user to find specific exercises the script works fine when a least 1 checkbox is selected from each checkbox group however I would like it that if no checkboxes was selected then it would the results of all checkboxes.
my checkbox form looks like this
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
ect...
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
ect....
<input type="submit" name="sub" value="Generate Query" />
</form>
and here is my script
<?php
if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
//get the function
include ($_SERVER['DOCUMENT_ROOT'] .'/scripts/functions.php');
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
$limit = 14;
$startpoint = ($page * $limit) - $limit;
// Runs mysql_real_escape_string() on every value encountered.
$clean_muscle = array_map('mysql_real_escape_string', $_REQUEST['muscle']);
$clean_equipment = array_map('mysql_real_escape_string', $_REQUEST['equipment']);
// Convert the array into a string.
$muscle = implode("','", $clean_muscle);
$equipment = implode("','", $clean_equipment);
$options = array();
if(array($muscle))
{
$options[] = "muscle IN ('$muscle')";
}
if(array($equipment))
{
$options[] = "equipment IN ('$equipment')";
}
$fullsearch = implode(' AND ', $options);
$statement = "mytable";
if ($fullsearch <> '') {
$statement .= " WHERE " . $fullsearch;
}
if(!$query=mysql_query("SELECT * FROM {$statement} LIMIT {$startpoint} , {$limit}"))
{
echo "Cannot parse query";
}
elseif(mysql_num_rows($query) == 0) {
echo "No records found";
}
else {
echo "";
while($row = mysql_fetch_assoc($query)) {
echo "".$row['name'] ."</br>
".$row['description'] ."";
}
}
echo "<div class=\"new-pagination\">";
echo pagination($statement,$limit,$page);
echo "</div>";
}
}
Im new with php so my code may not be the best. If anyone can help me or point me in the right direction I would be very greatful.
OK - I think I have figured it all out. You were right - the main problem was in your isset and isempty calls. I created some variations on your file, and this shows what is going on. Note - since I don't have some of your "other" functions, I am only showing what is going wrong in the outer parts of your function.
Part 1: validating function
In the following code, I have added two JavaScript functions to the input form; these were loosely based on scripts you can find when you google "JavaScript validation checkbox". The oneBoxSet(groupName) function will look through all document elements; find the ones of type checkBox, see if one of them is checked, and if so, confirms that it belongs to groupName. For now, it returns "true" or "false". The calling function, validateMe(formName), runs your validation. It is called by adding
onclick="validateMe('criteria'); return false;"
to the code of the submit button. This basically says "call this function with this parameter to validate the form". In this case the function "fixes" the data and submits; but you could imagine that it returns "false", in which case the submit action will be canceled.
In the validateMe function we check whether at least one box is checked in each group; if it is not, then a hidden box in the "all[]" group is set accordingly.
I changed the code a little bit - it calls a different script (muscle.php) instead of the <?php echo $_SERVER['PHP_SELF']; ?> you had... obviously the principle is the same.
After this initial code we will look at some stuff I added in muscle.php to confirm what your original problem was.
<html>
<head>
<script type="text/javascript">
// go through all checkboxes; see if at least one with name 'groupName' is set
// if so, return true; otherwise return false
function oneBoxSet(groupName)
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked) {
if (c[i].name == groupName) {
return true; // at least one box in this group is checked
}
}
}
}
return false; // never found a good checkbox
}
function setAllBoxes(groupName, TF)
{
// set the 'checked' property of all inputs in this group to 'TF' (true or false)
var c=document.getElementsByTagName('input');
// alert("setting all boxes for " + groupName + " to " + TF);
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].name == groupName) {
c[i].checked = TF;
}
}
}
return 0;
}
// this function is run when submit is pressed:
function validateMe(formName) {
if (oneBoxSet('muscle[]')) {
document.getElementById("allMuscles").value = "selectedMuscles";
//alert("muscle OK!");
}
else {
document.getElementById("allMuscles").value = "allMuscles";
// and/or insert code that sets all boxes in this group:
setAllBoxes('muscle[]', true);
alert("No muscle group was selected - has been set to ALL");
}
if (oneBoxSet('equipment[]')) {
document.getElementById("allEquipment").value = "selectedEquipment";
//alert("equipment OK!");
}
else {
document.getElementById("allEquipment").value = "allEquipment";
// instead, you could insert code here that sets all boxes in this category to true
setAllBoxes('equipment[]', true);
alert("No equipment was selected - has been set to ALL");
}
// submit the form - function never returns
document.forms[formName].submit();
}
</script>
</head>
<body>
<form action="muscle.php" method="post" name="criteria">
<p><strong>MUSCLE GROUP</strong></p>
<input type="checkbox" name="muscle[]" id="abdominals" value="abdominals"/>Abdominals<br />
<input type="checkbox" name="muscle[]" id="biceps" value="biceps" />Biceps<br />
<input type="checkbox" name="muscle[]" id="calves" value="calves" />Calves<br />
<input type="hidden" name="all[]" id="allMuscles" value="selectedMuscles" />
etc...<br>
<br /><p><strong>EQUIPMENT (please select a least one)</strong></p>
<input type="checkbox" name="equipment[]" id="equipment" value="bands"/>Bands<br />
<input type="checkbox" name="equipment[]" id="equipment" value="barbell" />Barbell<br />
<input type="checkbox" name="equipment[]" id="equipment" value="dumbbell" />Dumbbell<br />
<input type="hidden" name="all[]" id="allEquipment" value="selectedEquipment" />
<br>
<input type="submit" name="sub" value="Generate Query" onclick="validateMe('criteria'); return false;" />
</form>
</body>
</html>
Part 2: what's wrong with the PHP?
Now here is a new start to the php script. It checks the conditions that you were testing at the start of your original script, and demonstrates that you never get past the initial if statements if a check box wasn't set in one of the groups. I suggest that you leave these tests out altogether, and instead get inspiration from the code I wrote to fix any issues. For example, you can test whether equipmentAll or muscleAll were set, and create the appropriate query string accordingly.
<?php
echo 'file was called successfully<br><br>';
if(isset($_POST['muscle'])) {
echo "_POST[muscle] is set<br>";
print_r($_POST[muscle]);
echo "<br>";
if (!empty($_POST['muscle'])) {
echo "_POST[muscle] is not empty!<br>";
}
else {
echo "_POST[muscle] is empty!<br>";
}
}
else {
echo "_POST[muscle] is not set: it is empty!<br>";
}
if(isset($_POST['equipment'])) {
echo "_POST[equipment] is set<br>";
print_r($_POST['equipment']);
echo "<br>";
if (!empty($_POST['equipment'])) {
echo "_POST[equipment] is not empty!<br>";
}
else {
echo "_POST[equipment] is empty!<br>";
}
}
else {
echo "_POST[equipment] is not set: it is empty!<br>";
}
if(isset($_POST['all'])) {
echo "this is what you have to do:<br>";
print_r($_POST['all']);
echo "<br>";
}
// if(isset($_POST['muscle']) && !empty($_POST['muscle'])){
// if(isset($_POST['equipment']) && !empty($_POST['equipment'])){
If you call this with no check boxes selected, you get two dialogs ('not OK!'), then the following output:
file was called successfully
_POST[muscle] is not set: it is empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => allMuscles [1] => allEquipment )
If you select a couple of boxes in the first group, and none in the second:
file was called successfully
_POST[muscle] is set
Array ( [0] => abdominals [1] => calves )
_POST[muscle] is not empty!
_POST[equipment] is not set: it is empty!
this is what you have to do:
Array ( [0] => selectedMuscles [1] => allEquipment )
I do not claim to write beautiful code; but I hope this is functional, and gets you out of the fix you were in. Good luck!
I am trying to make an online calculater where people can calculate using form in my site, people can POST in form and result is GET by url string. Is it safe ?
html
<form id="form1">
<input type="text" name="user_price" size=2/>
<?php echo form_dropdown('selling', $rates);?>
<input type="submit" value="submit">
</form>
php
<?php
if((int)$_GET['user_price']){
echo 'Total '. $_GET['user_price'] * $_GET['selling'];
}else if((string)$_GET['user_price'] OR (array)$_GET['user_price']){
echo 'enter number not characters';
}else{
echo '';
}
?>
Yes, that's perfectly safe, it just doesn't make sense. (int)$_GET['user_price'] casts a value to an integer, it does not mean "if value is an integer".
You're looking for:
if (isset($_GET['user_price'], $_GET['selling']) &&
is_numeric($_GET['user_price']) && is_numeric($_GET['selling'])) {
...
} else {
echo 'Please enter numbers';
}
You could make it much more concise
if (is_numeric($_GET['user_price']) && is_numeric($_GET['selling'])) {
echo 'Total '. $_GET['user_price'] * $_GET['selling'];
} else {
echo 'Something went wrong';
}
Here is how I would code that...
$userPrice = isset($_GET['user_price']) ? $_GET['user_price']) : NULL;
$selling = isset($_GET['selling']) ? $_GET['selling'] : NULL;
if (is_numeric($userPrice) AND is_numeric($selling)) {
echo 'Total '. $userPrice * $selling;
} else {
echo 'enter number not characters';
}
Note that a good habit to get into, if echoing user submitted strings back, to wrap them with htmlspecialchars().
Perfectly safe, but when using GET and POST you should always declare a variable before you do anything with the form data