I've just started to study PHP at university and we've been given 10 exercises to do without any real aid we just have to figure it out for ourselves but I can't figure out how to make this work.
I've got a php page with a html table inside that has 10 boxes, in box 5 I have to make a form that allows you to input a four digit integer number or a four letter string and store it in a variable "$x". A user will put the numbers/letters in a box and click on a button labelled "submit" in order to enter the number/letter into the variable.
I made a form from a tutorial in a blank php page as a test and it worked but when I put it inside the HTML code (which is inside the php) I get this error:
Parse error: syntax error, unexpected T_IF, expecting ',' or ';' in Y:\xampp\htdocs\laboneformtest.php on line 33
Below is the code:
<tr>
<td><b>Rectangle 5: input field four digit integer number or four letter string and
store in variable x</b><br /><br />
"if (isset($_POST['name'])) $name = $_POST['name'];
else $name = "(Not Entered)";
echo "
Your name is: $name<br />
<form method="post" action="formtest.php">
What is your name?
<input type="text" name="name" />
<input type="submit" />
</form>
</td>
I realise the form isn't for variable $x yet I just wanted to get this working before I started on that.
PHP code blocks must be delimited with <?php and ?> (if you've got short_tags turned on, <? will work as well.
There is no such thing as a PHP script - there are only files that have PHP code blocks within them, and <?PHP ?> is how you tell the PHP interpreter where it should start executing instead of just outputting.
<?php
if (isset($_POST['name'])) {
$name = $_POST[\"name"\];
} else {
$name = '(Not Entered)';
}
echo "Your name is: $name<br />";
?>
<form>etc......</form>
<?php
if( $_POST['name'] && $_POST['name'] != ""){
$name = urldecode( $_POST['name'] );
}else{
$name = "not set";
}
?>
<table>
<tr>
<td>
<?=$name?>
</td>
</tr>
</table>
<form here>
Related
When I use PHP to set the value of a HTML form input element, it works fine provided I don't have any spaces in the data.
<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? "value = ".$_POST["username"] : "value = \"\""; ?> />
If I enter "Jonathan" as the username, it is repeated back to me as expected. If I enter "Big Ted", however, I only get "Big" repeated back when I submit the form.
Note that the $_POST["Username"] variable is correct; when I echo it using PHP, it is set to "Big Ted".
Quote it. Otherwise the space will just become an attribute separator and everything after spaces will be seen as element attributes. Rightclick page in webbrowser and view source. It should not look like this (also see syntax highlight colors):
<input value=Big Ted>
but rather this
<input value="Big Ted">
Not to mention that this would still break when someone has a quote in his name (and your code is thus sensitive to XSS attacks). Use htmlspecialchars().
Kickoff example:
<input value="<?php echo (isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''); ?>">
<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? "value = '".$_POST["username"]' : "value = ''"; ?> />
You have to wrap the variable result with quotes, so that the browser can know what's the content of the input.
<input type="text" name="username"
<?php echo (isset($_POST['username'])) ? ('value = "'.$_POST["username"].'"') : "value = \"\""; ?> />
Be aware of your quote usage.
As you see its not PHP5 or even PHP question at all.
Basic HTML knowledge is obligatory for one who want to be a PHP user.
And with using templates it looks way more neat:
Getting data part code:
$username = "";
if isset($_POST['username'])) $username = htmlspecialchars($_POST["username"]);
And template code:
<input type="text" name="username" value="<?=$username?>">
If you divide your code to 2 parts it become way more supportable and readable.
just make sure you put the colon after the field for example :
<option value="'.$row['name'].'">
Used quotes and it worked.
On the other side, needed to use the following:
$param=preg_replace('/[^A-Za-z0-9 ]/','', $param);
I have created a simple HTML form containing just one field. When I press submit some PHP code that I have written gets called and outputs text that would include submitted data if everything was working. But no submitted text gets printed by the PHP. The form has been created on a Godaddy HTML page and the form is as follows:
<FORM BORDER="1" action="http://www.bestpro.com.au/wordpress/PHB_action.php"
method="post" enctype="application/x-www-form-urlencoded"
eenctype="multipart/form-data" name="PHBForm" accept-charset="ISO-8859-1"
ienctype="text/plain">
<TABLE>
<TR>
<TD>First name:</TD><TD><INPUT type="text" name="firstname" id="firstname"></TD>
<TD></TD><TD></TD>
<TD> </TD><TD> </TD>
</TR>
<TR>
<TD> </TD><TD> </TD>
<TD> </TD><TD></TD>
<TD> </TD><TD><input type="submit" value="Submit"></TD>
</TABLE>
</FORM>
The PHP code output starts as follows:
This is where we end up.
Using `$_POST["firstname"]` which outputs nothing.
Using `htmlspecialchars($_POST["firstname"])` which also outputs nothing.
Question:
The PHP output doesn't include the value that I entered into the field.
Can anyone see what I am doing incorrectly?
I see nothing wrong here, so I can only assume it is something wrong with how you output it on your PHB_action.php page.
You say that you're placing $_POST['firstname'] on your page, but have you actually made sure to echo or print it to the page?
You can do this like so:
echo $firstname = $_POST['firstname']; // notice the echo placed before
or
$firstname = $_POST['firstname'];
print("$firstname");
EDIT:
I've notice you have put your post data inside of single quotation marks when echoing out to your page.
You must concatenate on your data rather than putting them inside of single quotes when echoing, like so:
echo 'Using' . $_POST['firstname']; // notice the dot in between the string and the post data.
Either that, or you have not installed PHP correctly (or at all) onto your server.
Hope this helps
So, this is pretty straight forward and I have written it up and will explain each bit as i go.
The PHP you need for this is:
<?php
if (isset($_POST['send']))
{
$fname = $_POST['firstName'];
if (!empty($fname))
{
echo "hello $fname";
} else {
echo "Please supply your first name.";
}
}
?>
$_POST['send'] is the name of your submit button, this will be the trigger for your PHP to initiate and run through the rest of the code.
$fname = $_POST['firstName']
This is just where I prefer to store the $_POST as a variable in the event you are going to re use it again it saves time writing the entire thing.
if(!empty)
if the username isn't empty (!empty meaning not empty) then perform the echo of $fname. however if it comes back as empty it will echo the else echo "please supply...;
Now for the form.
<form action="" method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td><input type="submit" name="send"></td>
</tr>
</table>
</form>
Just a straight forward form with a blank action on mine (I prefer to keep the PHP within the same file however I normally relay it back to a Class within a different file.
Each form input (First Name / Submit) must have a name="" value otherwise the PHP cannot read it and run with it.
I hope this makes sense and isn't too puzzling :)
Your input field should be inside tag and method should be post. Like:
<html>
<body>
<Form method=post>
<input id=mytextfield name=mytextfield type=text />
<input type=submit value=Submit />
</Form>
</body>
</html>
I'm a novice at PHP, so I'm having trouble with this task:
In a nutshell, I want to run a query and have the results returned in an array, and then allow the users to choose one selection from the array, and have a numerical value get passed on to another php page to be used in additional computations.
Here's my basic code so far:
<?php
include 'mysql_connect.php';
$Choices = mysqli_query ($server_connect, "SELECT * FROM Database
WHERE FLOOR (Item_number) = '$StockCategory' AND name='$name'")
or die(mysqli_error ($server_connect));?>
<table cellspacing="1" cellpadding="2" width="20%" border="1">
<?php while ($selectionlist = mysqli_fetch_array($Choices)){
$orderchoicenumber++;
$selectnumber = $matchups['Item_number']; ?>
<tr>
<td> <?php echo $selectionlist['size']; ?> </td>
<td> <?php echo $selectionlist['color'];?> </td>
<td> <?php echo $selectnumber;?></td>
<td> <?php echo $orderchoicenumber;?>
<?php }?>
</td></tr>
Enter your selection:
<form name ="selectionprocess" action="precheckout.php" method="POST">
<input type="text" maxlength="2" name="enterselection" >
<input type="hidden" name="selectnumber" value="<?php echo $selectnumber;?>">
</form>
<input type="submit" name="formSubmit" value="Submit" >
and here's the code on the destination page [precheckout.php]:
<?php
$name = isset($_POST["name"]) ? $_POST["name"] : $_SESSION['name'];
$mode = $_POST["select"];
$SelectNumber = $_POST["selectnumber"];
$Item_number = $SelectNumber;
?>
<p>Hello <?php echo $name; ?>!</p> <br>
OK, the item number of what you want is--- <?php echo $Item_number;?>
Of course, this means the number of results from the myfetcharray will vary.
The first aspect works pretty well. In this example, here's the output I receive (in table format):
Enter your selection: _____
4x6 navy 90515.01 1
4x8 mauve 90515.07 2
6x8 auburn 90515.03 3
2x4 black 90515.02 4
5x7 aqua 90515.08 5
The selection number is in the far right column. (The decimal number is the identifying Item Number in my SQL database. I'd like to not display this number in the final program, and even though I suppose I could make users enter in that number instead of a selection number in order to proceed, it's not a very user-friendly approach.)
The problem arises when I try to enter in a selection number (in this case, 1-5). The program successfully carries over a numerical value to the precheckout page [value="<?php echo $selectnumber;?>">], but it's always the final value spit out by the myfetcharray (i.e. in the lowest row). In this example, the output on the next page would be:
Hello, John!
OK, let's see how you did, because this item number is--- 90515.08
...no matter which matchup number was selected.
Ideally, I would like a more user-friendly way of selecting a row, rather than typing in a selection number. I've tried the radio button approach, but the best I could do was to successfully pass along a value of "on" to the next page instead of a numerical value. I'm willing to use other languages, though I don't know if they would play nice with PHP (i.e., Javascript).
Any thoughts on this would be appreciated. Thanks!
First off: a more user-friendly approach could be a dropdown menu: Try this:
<select>
<?php while ($selectionlist = mysqli_fetch_array($Choices)){
$orderchoicenumber++;
$selectnumber = $matchups['Item_number']; ?>
<option value="<?php echo $selectnumber; ?>">
<?php echo $selectionlist['size'] . " " . $selectionlist['color'] . " " . $selectionlist['color'] . " " . $selectnumber . " " . $orderchoicenumber; ?>
</option>
<?php }?>
</select>
All your PHP code is executed on the server when the page loads and any user interaction with the page is 'client side' (on the user's machine) so you're right: it needs another language to update your selectnumber hidden input. jQuery (a javascript library) is your best bet here.
You must already have some javascript on your page to post your form to precheckout.php - can you add that to your question, then I'll be able to guide you on the bits you need to change?
I am trying to write a simple php form but the out put is different from the one I wanted it to be. Does any one see what my mistake is thanks and appreciate it.
The Assignment :
Write a PHP script that checks the message sent from the form and then prints the name of the sender and the message. If the sender name or the message is blank, print ”You didn’t give all required information!” Remove any spaces before or after the user name or message. Remove also any HTML tags to make sure the user can’t alter the guestbook. The used form looks like this:
<form action="guestbook.php" method="get">
Sender: <input TYPE="text" name="name"><br>
Message: <input type="text" name="message"><br>
<input type="submit" value="Send">
</form>
Example output
John: Hello!
**my script:**
<?php
$name = $_GET["name"];
if(isset($_GET['submit'])) {
echo "$name: Hello!";
} else {
echo "You didn’t give all required information!";
}
?>
YOUR PROGRAM DOES NOT OPERATE CORRECTLY
Your program generated the following output:
You didn’t give all required information!
The following output should have been generated:
John: Hello!
The white area indicates correct output from your program.
represents a carriage return
In the comparison of outputs, the output of your program must be exactly the same as the example output.
You have no input named "submit", only one with a type submit, which is what you are looking for. Try using isset($_GET['name']) in the if-statement instead, since that's what you're actually using:
<?php
if(isset($_GET['name']))
{
echo $_GET['name'].": Hello!";
}
else
{
echo "You didn’t give all required information!";
}
?>
You should be aware though that directly outputting user-inputted data like this is very unsafe, creating a very big XSS vulnerability.
if(isset($_GET['submit']))
Should be
if(isset($_GET['name']))
Your PHP should look like the following:
<?php
$name = $_GET['name'];
if($name != ''){
echo "$name: Hello!";
}
else
{
echo "You didn’t give all required information!";
}
?>
Note: I haven't tested this.
In your statement :
if the sender name or the message is blank, print ”You didn’t give all
required information!” Remove any spaces before or after the user name
or message. Remove also any HTML tags to make sure the user can’t
alter the guestbook.
you should have something like this inside of your if statement:
if( isset($_GET['name']) ){
$clean_name = trim(strip_tags($_GET['name']));
echo $clean_name;
}
trim() to remove extra whitespaces before and after of the string and strip_tags() to remove html tag
<form action="guestbook.php" method="get">
Sender: <input type="text" name="name"><br>
Message: <input type="text" name="message"><br>
<input type="submit" value="Send" name="send">
</form>
<?php
if(isset($_GET['send'])) {
$name = trim(strip_tags($_GET['name']));
if($name != ''){
echo "$name: Hello!";
} else {
echo "You didn’t give all required information!";
}
}
?>
I am pretty new to programming and have absorbed some 150 pages of a book. I was going smooth with PHP when the code below bumped me hard. Can anyone explain about the positioning of opening and closing PHP tags.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<p>Thanks for Registering</p>",
"Username: ", htmlentities ($_POST['username']), "<br />",
"Email: ", htmlentities ($_POST['email']), "<br />";
}
else { ?>
<form action = "test.php" method = "post">
<label for = "username">Username: </label>
<input type = "text" name = "username" />
<label for = "email">Email: </label>
<input type = "text" name = "email" />
<input type = "submit" value = "Register" />
</form>
<?php }
?>
What I suppose is that, there should be only one pair of PHP tags:
The opening tag <?php at the very begining of the code above
The closing tag ?> at the closing of the code above
Anything else is hard for me to digest, please help me to understand that why the php tags are there in between the code at very weird positions.
Thank you
As per the manual on PHP tags
When PHP parses a file, it looks for opening and closing tags, which
are which tell PHP to start and stop interpreting the
code between them. Parsing in this manner allows PHP to be embedded in
all sorts of different documents, as everything outside of a pair of
opening and closing tags is ignored by the PHP parser.
Which means the code between the php tags will be echo'd and outside one:
<form action = "test.php" method = "post">
<label for = "username">Username: </label>
<input type = "text" name = "username" />
<label for = "email">Email: </label>
<input type = "text" name = "email" />
<input type = "submit" value = "Register" />
</form>
will be treated as a normal HTML. In the case above PHP checks if the form has been POSTed, and if so, it displays a thank you message. If the HTTP request is not POST, it will display a form for the user to post.
In general it's not good practice to mix HTML and PHP and you should avoid this sort of structure.
The easiest way to think about it is to do what the parser does, that is, replace the content outside of the php tags with echo statements within php tags.
The main benefit of doing it like this is that you don't have to escape the HTML in php strings, plus, if well structured, you can view it pretty well in a WYSIWYG editor
Here's an example of code that is equivalent to what you wrote and doesn't switch out of php mode
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<p>Thanks for Registering</p>",
"Username: ", htmlentities ($_POST['username']), "<br />",
"Email: ", htmlentities ($_POST['email']), "<br />";
}
else {
echo "
<form action = \"test.php\" method = \"post\">
<label for = \"username\">Username: </label>
<input type = \"text\" name = \"username\" />
<label for = \"email\">Email: </label>
<input type = \"text\" name = \"email\" />
<input type = \"submit\" value = \"Register\" />
</form>";
}
?>
The PHP manual does a poor job of explaining what actually happens. The PHP parser definitely does not ignore the text outside the block. Instead the PHP parser turns that text into an echo operation. Don't believe me? You can see for yourself in the source code. In zend_language_parser.y, you will find the following line:
| T_INLINE_HTML { zend_do_echo(&$1 TSRMLS_CC); }
When you see <?php if($condition) { ?><div>...</div><?php } ?> it's exactly equivalent to <?php if($condition) { echo '<div>...</div>'; ?>.
The syntax might look odd, but it's actually very useful in some situation. For example, all our web pages typically share the same header and footer. People often handle this by doing an include('header.html') at the beginning of the script and an include('footer.html') at the end. It's not a very flexible approach. Moreover, you end up with two halves of one HTML document that won't render correctly in a browser.
A better way is to slices up the HTML doc with function declaration:
<?php function printHeader($title = "Default Title", $extraJSScrpts = array(), $extraCSSFiles = array()) { ?>
<html>
<head>
<title>
<?php echo $title; ?>
</title>
</head>
<body>
<div style="position: absolute; left: 150px; top: 35px;">
<?php } ?>
<?php function printFooter() { ?>
</div>
</body>
</html>
<?php } ?>
If you ignore the <?php ... ?>, what you have is a regular HTML doc. Looking at the PHP again, you see I have two functions, printHeader() and printFooter(). Instead of doing includes, all my pages now just call these two functions. Each page can pass optional arguments to deal with any special needs (an extra stylesheet, for example). Should I want to implement different themes on my site, it'd be very straight forward. All I have to do is change which file I include at the beginning to bring in different versions of these functions.
Control structures in PHP (e.g. loops, functions, etc.) can be split across pairs of end tags. Effectively, anything not enclosed in PHP tags is just emitted as though it were being echoed (or captured in the current output buffer, if there is one).
Try this
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "<p>Thanks for Registering</p>",
"Username: ", htmlentities ($_POST['username']), "<br />",
"Email: ", htmlentities ($_POST['email']), "<br />";
}
else {
echo '
<form action = "test.php" method = "post">
<label for = "username">Username: </label>
<input type = "text" name = "username" />
<label for = "email">Email: </label>
<input type = "text" name = "email" />
<input type = "submit" value = "Register" />
</form>';
}
?>
The opening and closing <?php tags are to tell the interpreter which code is php code (and therefore it should interpret) and which code is something else - HTML, CSS, JS etc.
You'll notice this:
echo "<p>Thanks for Registering</p>";
This is a valid PHP statement and is okay to send to the PHP interpreter.
However, later on in the script the author want to output a load more HTML - he could of course do something like this:
echo '<form action = "test.php" method = "post">
<label for = "username">Username: </label>
<input type = "text" name = "username" />
<label for = "email">Email: </label>
<input type = "text" name = "email" />
<input type = "submit" value = "Register" />
</form>';
But instead chooses to tell the interpreter to just ignore all of this HTML content by closing the PHP section with a ?> and output normal HTML.
He needs to finish the else{} block though, so reopens PHP with <?, adds the closing } and then completes with a closing ?>
Note that PHP also provides an alternative syntax for control structures that improves readability when they're employed to control HTML. The following code creates a table with alternating background color from a list of items:
<table style="width: 100%">
<?php foreach($items as $index => $item): ?>
<?php if(!($index & 0x0001)): // even ?>
<tr style="background-color: #FFFFAA">
<td>
<?php echo $item ?>
</td>
</tr>
<?php else: ?>
<tr style="background-color: #AAFFFF">
<td>
<?php echo $item ?>
</td>
</tr>
<?php endif ?>
<?php endforeach ?>
</table>