How to create HTML button based on condition? - php

I am using following code:
<?PHP
if ($_Session['WorkMode'] == 'New' || $_Session['WorkMode'] == "")
echo "<input id='Submit' name='Submit' value='Submit' type='button'>";
else
echo "<input id='Update' name='Update' value='Update' type='button'>";
?>
Is this the correct way to render buttons?

If it works, then yes it's one correct method. Another way, using a ternary if statement might be:
<?PHP $button = $_SESSION['WorkMode'] == 'New'
|| $_SESSION['WorkMode'] == '' ? "Submit" : "Update"; ?>
<input id="<?php echo $button;?>" name="<?php echo $button;?>"
value="<?php echo $button;?>" type='button' />
Really it's a matter of personal preference and clarity. I prefer to write HTML as HTML (not as a PHP string) and echo variables into that HTML using PHP tags. Some might not like to use this method. If you have PHP short tags switched on you can even use <?=$button;?>

This is totally valid and readable.
If the number of lines of code is important to you, you could also do:
<?php $action = ($_Session['WorkMode'] == 'New' || $_Session['WorkMode'])? "Submit" : "Update" %>
<input id="<?php echo $action ?>" name="<?php echo $action ?>" value="<?php echo $action ?>" type="button" />
My PHP is a bit rusty so I might be off on the syntax, but you get the idea.
If you use a framework such as cakephp or symphony you can use their helpers to generate buttons more easily.

Basically, yes you can do it this way. Depending on the size of your application and on your programming experience you might want to consider to start using a templating system (e.g. Smarty). This way you could seperate php code and html markup.
Best wishes,
Fabian

It should be
<?PHP
if ($_Session['WorkMode'] == 'New' || $_Session['WorkMode'] == "")
echo "<input id='Submit' name='Submit' value='Submit' type='button'/>";
else
echo "<input id='Update' name='Update' value='Update' type='button'/>";?>

The better way of doing this is using a template system, ou simply separate the layout code from logic:
view.php:
<?php if ($new): ?>
<input id='Submit' name='Submit' value='Submit' type='button'>
<?php else: ?>
<input id='Update' name='Update' value='Update' type='button'>
<?php endif; ?>
So, $new variable is sended by the logical code (controller):
controller.php:
$new = ($_Session['WorkMode'] == 'New' || $_Session['WorkMode'] == "");
include("view.php")
This is a better way to doing what you want :).
Don't forget that is a good practice to also support internacionalization on view.

Depending on the behaviour you want from your buttons, you might consider changing their type to submit.
EDIT
It seems from the responses that your code is functional. However, you say that the PHP code is coming out behind the buttons.
This implies to me that the file is not being parsed by the PHP parser.
RPK: Is your web server serving other PHP files correctly?

Related

php button call a php function

I have that code to create a button
$button = "<input type='submit' id='liga' value='liga'>";
echo $button;
I have the php function
function liga(){
....}
as I do so by clicking the button it calls the function?
Using html this code works, but I really need use the php button, how can I make it?
<input type="submit" name="liga" value="liga" />
if (isset($_REQUEST['liga'])) {
liga();
} elseif (isset($_REQUEST['desliga'])) {
desliga();
}
This little snippet will take an array with the index being the name of the button and the value as the label the button should have. It will then make a button for each element of the array.
<?php
$foo = array('name'=>'label', 'name2'=>'label2');
foreach ($foo as $k=>$v)
echo "<input type=\"submit\" name=\"$k\" value=\"$v\" />\n";
?>
You can also put the PHP variable right inside the HTML code using <?=...?>:
<input type="submit" name="<?= $myPhpVar ?>" value="<?= $myOtherPhpVar ?>" />
Or you can put complicated expressions (or whole programs) using the typical <?php...?> tags inside HTML brackets - whatever it echod becomes the content of that html tag:
<input type="submit" name="<?php echo $myPhpVar; ?>" value="<?php echo "LABEL: ".$myOtherPhpVar; ?>" />
I found a solution
echo "<input type='submit' name='liga' value='Liga'>";
echo "<input type='submit' name='desliga' value='Desliga'>";

how to properly handle php undefined index

I have a script where a user can input some text, view it, and change it. It looks like that:
if(isset($_POST['change']))
{
$text = $_POST['text'];
echo"
<form method='post' action='datei.php'>
<p>You wrote: $text</p>
<input name='text' type='hidden' size='21' value='$text'>
<input name='submit' type='submit' value='Change'>
</form>";
}else
{
$text = $_POST['text'];
echo"
<form method='post' action='datei.php'>
<p>Write some additional Information</p>
<input name='text' type='text' size='21' value='$text'>
<input name='change' type='submit' value='View'>
</form>";
}
When I load the page the first time, I get the following notification
Notice: Undefined index: text in ...
I found two solutions how to fix the problem:
Ignore Notifications
Use isset()
If I would use isset I would have to change two lines from above to:
if(isset($_POST['text']))$text = $_POST['text'];
and
<input name='text' type='text' size='21' value='"; if(isset($_POST['text'])) echo $text; echo"'>
Since my original form has more then 20 input fields, this would make the code less readable and more likly for erros when editing the code. Is there any better way to get around the notification that I currently miss?
First be sure that you define all the variables before using them, like
$text = false;
Plus, checking that a variable is set is always a good practice. Not to mention that you shouldn't be using $_POST directly.

Passing data between PHP webpages from a dynamically generated list

I have a PHP code which generates a dynamic list inside a form like the following, note that the list is built dynamically from database:
echo '<form name="List" action="checkList.php" method="post">';
while($rows=mysqli_fetch_array($sql))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='hidden' name='SessionID' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
What I need is to POST the data corresponding to the user choice when he clicks on the button for that row to another page.
If we use hyperlinks with query strings there will be no problem as I'll receive the data from the other page using a GET request and the hyperlinks would be static when showed to the user.
Also I need to obtain the user input from a textbox which is only possible with POST request.
Simply from the other page (checkList.php) I need these data for further processing:
$SessionID=$_POST['SessionID'];
$Code=$_POST['code'];
As I have a while loop that generates the fields, I always receive the last entry form the database and not the one corresponding to the line (row) that the user chosed from the LIST.
I'm going to recommend that you clean up the names of variables so that your code can
at least tell us what it's supposed to do. It should be rare that someone looks at your code
and has a lot of trouble trying to see what you're trying to accomplish :P, ESPECIALLY when you need help with something ;]. I'm going to try some things and hope that it makes doing what you want easier to comprehend and perhaps get you your answer.
It's good to try your best to not echo large amounts of HTML unnecessarily within a script , so firstly I'm going to remove the
echos from where they are not necessary.
Secondly, I'm going to use a mysql function that returns an easier to process result.
$user = mysqli_fetch_assoc($sql)
Third, I don't know if form having a name actually does anything for the backend or frontend of php, so I'm
just going to remove some of the extra crust that you have floating around that is either invalid HTML
or just doesn't add any value to what you're trying to do as you've presented it to us.
And yes, we "note" that you're building something from the database because the code looks like it does =P.
I'm also sooo sad seeing no recommendations from the other answers in regard to coding style or anything in regard to echoing html like this :(.
<?php while($user = mysqli_fetch_assoc($sql)): ?>
<form action="checkList.php" method="post">
<input type='password' name='code' value='<?php echo $user['code'] ?>' />
<input type='hidden' name='SessionID' value='<?php echo $user['id'] //Whatever you named the field that goes here ?>' />
<input type='submit' value='Take Survey' />
</form>
<?php endwhile; ?>
i not sure this is correct
echo '<form name="List" method="post">';
while($rows=mysqli_fetch_array($result))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='button' value='Take Survey' onclick=show($rows[0])>";
echo "<br>";
}
and javascript
<script>
function show(id)
{
alert(id);
window.location="checkList.php?id="+id;
}
</script>
On checkList.php
$id=$_GET['id'];
echo $id;
You can just check in checkList.php whether $_POST['code'] exists and if exists retrieve $_POST['SessionID'] which will be generated from database. But one thing, if You have all hidden fields in one form, they all will be sent, so You need to think how to correct that - maybe seperate forms for each hidden field, submit button and maybe other POST fields.
And afterwards, You will be able to get data in the way You need - $SessionID=$_POST['SessionID'];
I suppose it is the easiest way to solve that.
You can try something like this:
while($rows=mysqli_fetch_array($sql))
{
$index = 1;
echo "<input type='password' name='code' id='code'>";
//Attach $index with SessionID
echo "<input type='hidden' name='SessionID_$index' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
On checkList.php
<?php
$num = explode('_', $_POST['SessionID']);
$num = $num[1];
//in $num you will get the number of row where you can perform action
?>
$form = 1;
while($rows=mysqli_fetch_array($sql))
{
echo '<form name="List_$form" action="checkList.php" method="post">';
echo "<input type='password' name='code' id='code_$form'>";
echo "<input type='hidden' name='SessionID' id='SessionID_$form' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
echo '</form>';
$form++;
}

How to pass a value with the same PHP file?

I want to pass the same boolean value "isProvena" several times in two PHP files. The first time I pass the value from utilitizer.php to hraprint.php by using the codes as follows:
if ($_POST['type'] == 'printphys' || $_POST['type'] == 'printprovenahpa')
{
echo "<form action='/content/822' method=post>";
echo "<input type=hidden name=filename value='$filename'>";
if($_POST['type'] == 'printprovenahpa') {echo "<input type=hidden name=isProvena value='1'>";}
echo "<input type=hidden name=content value='";
if ($_POST['type'] == 'printphys') echo 751;
else if ($_POST['type'] == 'printprovenahpa') echo 520;
echo "'>";
echo "<input type=submit value='Start Job'></form>";
}
And then I get the value "isProvena" from hraprint.php and post(get) again:
$isProvena = false;
extract($_REQUEST, EXTR_IF_EXISTS);
$isProvena = (boolean)$isProvena;
<form action="/content/822" method="GET">
<input type="hidden" name="isProvena" value="<?php echo ($isProvena) ? '1' : '0' ?>" />
<tr>
<td><label for="showOnlyScreening">Print Only Screenings:</label></td>
<td><input id="showOnlyScreening" type="checkbox" name="showOnlyScreening" value="1" <?php echo ($isProvena) ? 'checked="checked"' : ''?>/></td>
</tr>
<tr>
</table>
</form>
And post again:
<form action="/content/822" method="POST">
<input type="hidden" name="isProvena" value="<?php echo ($isProvena) ? '1' : '0' ?>" />
</table>
And I do the judgement here:
if($isProvena){
.........
}
The reason I need to post(get) several times is that there are several page redirect action happens in the same PHP file(hraprint.php). When I was trying to get the value which is supposed to be 'true' from if($isProvena){} and execute the function, I failed.
Anyone can help me to have a look and tell me what is wrong?
It would be easier if you simply use sessions for that. Sessions are made specifically for that purpose - passing variables easily from one page to another.
And it is not yet established in the last code block of your answer that $isProvena already exists because I do not see any extract() there.
P.S. Use the $_POST and $_GET variables instead of extracting the $_REQUEST. The code is vulnerable to the problems caused by register_globals

Problem in sending values between pages in PHP

I want to send data from one page to the other via a form in PHP. In the initial page I have included the following PHP script that generates an input form with hidden fields. The names of these hidden fields are generated by the PHP:
<?php
echo "<form class='available-form' name='available_os' method='get' action='process-results.php'>";
echo "<input type='hidden' name='$software'></input>";
echo "<input type='hidden' name='$version'></input>";
echo "<input type='submit' name='available-button' value='Find Available Libraries for this Software'></input>";
echo "</form>";
?>
In the second page, named process-results.php, I would like to get the names of these hidden fields via the $_GET method but of course using $_GET[$software] and $_GET[$version] wouldn't work...Can someone tell me if there is a solution to this issue or if there is a better alternative? Thanks in advance
Instead of
"<input type='hidden' name='$software'></input>";
you should use
"<input type='hidden' name='software' value='".$software."'></input>";
for each. This way, you can use $_GET['software'] to retrieve the value. Do this for each of your hidden inputs.
I think you may want something like:
<form ... >
<input type="hidden" name="software" value="<?php echo $software ?>" />
<input type="hidden" name="version" value="<?php echo $version ?>" />
</form>
and then
$_GET['software'];
$_GET['version'];
I'm not sure what you're trying to accomplish, but this looks odd to me. Isn't the below code more of what you're looking for?
<?php
echo "<form class='available-form' name='available_os' method='get' action='process-results.php'>";
echo "<input type='hidden' name='software' value='$software'></input>";
echo "<input type='hidden' name='version' value='$version'></input>";
echo "<input type='submit' name='available-button' value='Find Available Libraries for this Software'></input>";
echo "</form>";
?>
That way you will get a query string in form of ?software=yoursoftwarename&version=yourversion and it will be available via $_GET["software"] and $_GET["version"] on the next page.
You could iterate over each of the items in the $_GET array on process-results.php. The problem is that the keys for the value will be whatever $software and $version are set to on the first page. Try something like this:
foreach($_GET as $key=>$string) {
// Do stuff with them
}
Add
enctype="multipart/form-data"
To the tag... so it looks like
<form enctype="multipart/form-data" method......
If you really need to have the dollar-sign inside the name, escape it:
echo "<input type='hidden' name='\$software'>";
or put the string in single-quotes:
echo '<input type="hidden" name="$software">';
Otherwise PHP is looking for a variable named "$software", if you look inside the browser-source you will see that the name-attributes are empty(except you're having those variables defined somewhere).

Categories