I have been looking at this for a while now, and looking at all similar questions but I can't find anything that solves my problem.
So I'm working in main't html and php building a pretend shopping site on my own server. This is just for my own educational purposes, so basically it's just for fun.
This is only the third time I've done anything with html or php, so there is a lot I still don't understand and this project might have gotten a little bigger than I intended.
I have a page where the 'user' signs in from, and from there I used the session to bring the data they put in (username and such) to make a very simple greeting. That has worked mostly. The only problem there is if I refresh the new page too much sometimes it disappears.
Main problem is in the new page. I have a form for items in the store, where the user can choose an amount they want to buy. However when the submit button is pressed my check shows that the form is empty, and I don't understand why. I've messed with it a bunch, started from using $_POST to $_GET but that didn't help.
This is the start of my php which checks for things from the previous page.
<?php
//start session
session_start();
//check is post variables exist, if it does assign it
if (isset($_POST['username'])) {
$name = $_POST['username'];
$_SESSION['usersname'] = $name;
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
$_SESSION['useremail'] = $email;
}
if (isset($_POST['password'])) {
$password = $_POST['password'];
$_SESSION['userpassword'] = $password;
}
$username = $_SESSION['usersname'];
$useremail = $_SESSION['useremail'];
$userpassword = $_SESSION['userpassword'];
Then the item list looks something like this.
<!--- List of all items and how many they want --->
<nav class="col-1">
<p> Shopping List </p>
<br/>
<form action="index.php" method="GET" name="items">
<table class="table1">
<tr><th>WEAPONS</th></tr>
<tr><td class="td1">
<br/>
<img class="disc" src="images/wand.png"></img><br/>
Item Name: Butterfly Wand<br/>
Price: $50.00<br/>
<input type="number" name="wandNum" min="0" style="width: 50px"/>
<br/>
<?php $wandprice = 50.00; ?>
</td></tr>
<tr><td class="td1">
<br/>
<img class="disc" src="images/sword.png"></img><br/>
Item Name: Normal Sword<br/>
Price: $20.00<br/>
<input type="number" name="swordNum" min="0" style="width: 50px"/>
<br/>
<?php $swordprice = 20.00; ?>
</td></tr>
<tr><td class="td1">
<br/>
<img class="disc" src="images/Bow_and_Arrows.png"></img><br/>
Item Name: Normal Bow<br/>
Price: $12.00<br/>
<input type="number" name="bowNum" min="0" style="width: 50px"/>
<br/>
<?php $bowprice = 12.00; ?>
</td></tr>
</table>
<input type="submit" id="orderButton" name="order" value="Order"/>
</form>
</nav>
Finally I wanted to put all the items and their information into an array somehow to store them. I'm not sure if this is the best way to achieve it either. I haven't gotten to this part because the form above keeps coming up empty. Even if I type in a value for every item.
if (isset($GET['items'])) {
$wandnum = $_GET['wandNum'];
$swordnum = $_GET['swordNum'];
$bownum = $_GET['bowNum'];
This just checks to see if the value is over 0...I think..then hopefully it will put the values in the array.
if ($wandnum > 0) {
$wand = array ("Butterfly Wand", $wandprice, $wandnum);
$items[] = array_push($wand);
}
if ($swordnum > 0) {
$sword = array ("Normal Sword", $swordprice, $swordnum);
$items[] = array_push($sword);
}
if ($bownum > 0) {
$bow = array ("Normal Bow", $bowprice, $bownum);
$items[] = array_push($bow);
}
}
?>
I can't get it past the if statement though because apparently it's not set. I don't have an IDE for html or php (any good free ones with debugging would be great) I ran the code through my command line and I ran fine. I just can't figure out why there are no values. My other page ran fine, so I'm not sure why this one is giving me trouble.
You need to add at the beginning:
<?php
if(isset($_GET['order'])) {
if (isset($_GET['items'])) {
$wandnum = $_GET['wandNum'];
$swordnum = $_GET['swordNum'];
$bownum = $_GET['bowNum'];
if ($wandnum > 0) {
$wand = array ("Butterfly Wand", $wandprice, $wandnum);
$items[] = array_push($wand);
}
if ($swordnum > 0) {
$sword = array ("Normal Sword", $swordprice, $swordnum);
$items[] = array_push($sword);
}
if ($bownum > 0) {
$bow = array ("Normal Bow", $bowprice, $bownum);
$items[] = array_push($bow);
}
}
}
Related
For the last couple of days I have been having an issue where my PHP code will not get the text from a form text box that has worked for 7 or 8 years. Has anyone else has this issue or is there something that may need to be running that isn't?
My PHP form is a username textbox and password textbox and submit button
this is the code that is going to the die because the username isn't being set:
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
} else {
die('User is blank'); //$username = "";
}
this error is going to my error_log
PHP Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 4 in /home/
I know I know... no mysqli
form html:
<form method="post" onsubmit="return vloginform(this);"
action="https://www..com/php_include/processlogin.php"
name="loginform">
<div id="pleft">
<div class="uandp">Username: </div><div class="inputbox"><input type="text"
name="username" maxlength="30" class="buttonsboxes" style="width: 180px;" />
</div>
<div class="uandp">Password: </div><div class="inputbox"><input
type="password" name="password" maxlength="30" class="buttonsboxes"
style="width: 180px;" /></div>
</div>
<div id="pright">
<p><input class="buttonsboxes" type="submit" value="login" name="submit"
id="submit" /><input class="buttonsboxes" type="reset" value="reset"
name="reset" id="reset" /></p>
</div>
Not sure how you are fetching the records but using mysql_fetch_array instead of manually fetching every column value will fix this issue. Try analysing the result before fetching it. If result is empty, skip fetching.
Something like this:
$result = mysql_query("SELECT * FROM tablename");
if (!$result || !mysql_num_rows($result)) {
die('No records.');
}
while ($row = mysql_fetch_array($result)) {
// Your code goes here
}
Just use the tag required in the textbox or if you are using the $_POST VARIABLE.
POST:
if(isset($_POST['username'])) {
$username = $_POST['username'];
} else {
die('User is blank'); //$username = "";
}
You might want to use $_REQUEST variable instead of $_SESSION variable because whenever the data is transferred from a form to php page, it is transferred in $_REQUEST variable not in $_SESSION variable.
Use can do something like:
if(isset($_REQUEST['username'])) {
$username = $_REQUEST['username'];
} else {
die('User is blank'); //$username = "";
}
UPDATE
As per your code, you are using post method to send the data, so you should you $_POST variable to get the data from the form:
$username = $_POST['username'];
and you can check whether it is empty or not by writing following line of code:
if ($username == null) {
die('User is blank'); // if username = "", this line will be executed
} else {
// do the required task...
}
I just tried the function - isset($_REQUEST['username']) and isset($_POST['username']) also, but it is not giving the desired result. But I have got above code to work.
Hope this helps:)
I know that this can be a silly question, but I'm really going mad.
I'm new at PHP and I would like to create a form like this
where the user enters his name and a review of the restaurant, and when the button is clicked the data have to be added below the other reviews in the page. I tried this code in HTML to create the form
<form action="aggRecensione.php" method="post">
<p class="noIndent">Nome: <input type="text" name="nome"></p>
<p class="noIndent">Recensione</p>
<textarea name="recensione" rows="3" cols="40"></textarea>
<input type="submit" value="Aggiungi recensione" name="pulsanteRecensione" onclick="location.href='aggRecensione.php';">
</form>
and this code in PHP (aggRecensione.php)
<?php
$nome = $_POST('nome');
$testo = $_POST('recensione');
echo "<p class=\"noIndent\">Recensione di $nome:</p>";
echo "<p>$testo</p>";
?>
but the PHP one doesn't work. I've never managed buttons before and all the tutorials I found didn't help me. What am I doing wrong?
Almost good, but maybe you can try
<?php
$nome = $_POST['nome'];
$testo = $_POST['recensione'];
echo "<p class=\"noIndent\">Recensione di $nome:</p>";
echo "<p>$testo</p>";
?>
That because the content of $_POST is an array and array keys are indicated by the brackets []
Also remove the onclick="location.href='aggRecensione.php';"
And to be sure the user really hits the button you can also add this
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$nome = $_POST['nome'];
$testo = $_POST['recensione'];
echo "<p class=\"noIndent\">Recensione di $nome:</p>";
echo "<p>$testo</p>";
}
?>
http://php.net/manual/en/reserved.variables.post.php
Remove this
onclick="location.href='aggRecensione.php';"
This will call the page as get method.
And change this two line.
$nome = $_POST['nome'];
$testo = $_POST['recensione'];
How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.
e.g I have a page with a form:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
The engine that handles the form is external, but required in the page:
require_once 'form_engine.php';
form_engine.php checks the input,
$success = "true";
$errorMessage = " ";
$name = $_POST['name'];
if ( $name == '') {
$errorMessage = 'Please enter your name';
$success = false;
}
else (if $success = true) {
// do something with the data
}
The form page contains the result:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>
Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?
You need something like this:
if (!isset($_POST['name']))
instead of
if ( $name == 'name')
UPDATE
Try this, it should give you the idea:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
Note: leaving out the action attribute will just submit the form to the current page
Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.
You can use redirect on php side:
header('Location: www.mysite.com/index.php');
You seem to be a little confused in terms of the exact process that occurs in terms of rendering a page, as do some of those commenting. You do not need to use sessions to solve this problem. There is no need to store anything server-side between page requests because the user's browser with retain everything that you need, at least for this situation. My guess is the others took you mentioning an "external engine" and thought that the form would be submitting away to a different site/page.
form loops
Below is a diagram showing a typical form request loop:
You do not have to do this, as coding is as much about personal preference to anything else, but typically people will design their form to submit back to the same URI that generated it — as you seem to be doing in your example, by leaving the action attribute blank. By doing this, as long as you embed everything you wish to pass back to the server side within the form — each time the user submits — that information will be resent and be available in PHP.
Obviously you need to be wary of what information might constitute as sensitive, as this data should only ever be written into markup if your requests are protected by HTTPS/SSL. You should also filter/escape any user input to prevent markup injection into your site. You can prevent many problems by using htmlentities, however this can cause issues depending on the values you are trying to capture from the user. Because you are using double quoted HTML attributes (the right way to do them ;) I have not set the ENT_QUOTES option.
back to the point
So in the above loop the user will be shown the form for the first time, and after any subsequent submit, which means that each time your PHP notices that there is an error you can just add your message into the page flow. The trick with this kind of system is what exactly do you do once the form is fully complete. To get out of the loop most people will use a header location call:
<?php
require_once 'form_engine.php';
$name = !empty($_POST['name']) ? trim($_POST['name']) : '';
$name = htmlentities($name);
if ( $success ) {
header('location: next-step.php');
exit;
}
?>
<form action="" method="post">
<input type="name" value="<?php echo $name; ?>" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<?php
if ( $errorMessage ) {
echo "<p>$errorMessage</p>";
}
?>
form engine repairs
You should also rectify your form_engine.php as per my comments above and Shekhar Joshi's answer, although I would keep the header code outside of your engine logic, and leave that decision to the code that requires in the engine — as the above does.
may be, you are looking for this! the header() method.
$success = true;
$errorMessage = " ";
$name = $_POST['name'];
if(isset($_POST['name'])) {
if ( $_POST['name'] == '') {
$errorMessage = 'Please enter your name';
$success = false;
header('Location: www.something.com/some.php');
}
else if ($success == true) {
// do something with the data
}
}
I'm genuinely stuck on something VERY irritating. After a couple of hours of trying everything I know I've ended up here to see if anyone can help. Here's the general idea.
I want one certain page to be available with a password sent via a form. There is no user, and the password will not change. This should be easy, right!
I've got a form which submits with the method set to post, and the action set to $_SERVER['PHP_SELF']. The plan is, when the password variable I've pre-defined matches what is typed in the form, one set of content shows on the page, when it doesn't you get a different set of content (a form).
Here's what's weird. When looking at a print_r I see whatever I submit in the form in the array, but when I put the right password in the array fills, then empties quickly. I see this on the page reload. It completely empties itself. Even stranger, the 2nd time I do this, it works. What am I missing here? I'd love to know!
Many thanks, and Merry Christmas.
---- some code ----
The form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
Some PHP from the top of the file;
$pass = '12846565488374';
if($_POST['pass']){ $login = $_POST['pass']; } else { $login = 'empty'; }
if($login != $pass) { $show = 0; } elseif($login == $pass){ $show = 1; }
----- solved ------
Turns out this was a JS plugin reloading the page without me knowing.
Try:
if(isset($_POST['pass']) AND $_POST['pass'] == $pass) {
$show = 1;
} else {
$show = 0;
}
Copied from the comment below:
PHP can't update anything after the page is loaded from the server... You can only use refresh or JS/AJAX to change the content. It would be much easier if you uploaded the whole page somewhere.
Try:
<?PHP
if(isset($_POST['pass'])
{
$pass = '12846565488374';
($_POST['pass'] == $pass)? $show = 1 : $show = 0;
echo $show;
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
<?PHP
}
?>
<?php
if (isset($_POST['pass']))
{
if ($_POST['pass'] == $pass)
{
$show = 1;
echo $show;
}
else
{
$show = 0;
echo $show;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<label for="pass" id="pass">Password:</label>
<input type="text" name="pass" id="pass" />
<input type="submit" name="submit" value="Yes" />
</form>
perhaps something like this?
the purpose for the echo is to show when the correct password is entered, $show changes to 1 and when wrong, changed to 0
Edit:
Your Parameters Checking for $show
<?php
if (isset($show) AND $show === 1)
{
echo "The Variable Is Set To 1";
}
elseif (isset($show) AND $show === 0)
{
echo "The Variable Is Set To 0";
}
?>
This is tested and working with your code.
Thank you for your help everyone - as Matanya said, it was indeed a Javascript issue that was reloading the page. It's a music player and it was placed the "true" part of the IF statement. I don't understand why it has this effect, but at least I know. I thought the error would be in my PHP. Here's the player in question: SCM Music Player http://scmplayer.net
Thanks again.
This is pretty specific and I have not found an answer yet.
I am writing a script to check if a name is already input into the SQL server using JQuery $.POST.
The front end looks like this:
register.php
<div id="container" class="container">
<div id="wrapper" class="wrapper">
<div id="title" class="title">
Welcome to Taskar!
</div>
<div id="login" class="login">
<form method="post" action="registermembers.php">
<div id="exists">
Register Your Company Below:
</div>
<input type="text" id="company" name="company" value="Company Name"/> <br />
<br />
<input type="text" id="password" name="password" value="Default Password"/> <br />
<input type="submit" name="submitcompany" value="Submit" />
</form>
<script>
$(document).ready(function() {
$('#company').keyup(function() {
var $company = $(this).val();
var $reg = $('#exists').html();
$.post('include/reg_post.php', { company: $company, reg: $reg }, function(company) {
$('#exists').html(company);
});
});
});
</script>
</div>
</div>
</div>
The backend code looks like this:
reg_post.php
<?php
include 'include/db.php';
$reg = $_POST['reg'];
$company = $_POST['company'];
$email_hash = $_COOKIE['email_hash'];
$password = $_COOKIE['password'];
$sql = "SELECT * FROM taskar_employee WHERE (company = '$company')";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) <= 1){
echo $reg;
} else {
echo "This Company Already Exists!";
} ?>
Now, the problem I am having is, when I am testing this, it works fine all the way up to when I type in a company name that is in the database. It shows me that the company is already registered. When I press backspace or type another letter, it still tells me the company still exists, though it obviously would not.
It seems that the if statement wants to stop the $.post feature from continuing after it gets the opposite statement?
What do you guys think?
Your problem lies in the way you're using your $reg variable.
$reg contains the HTML contents of the #exists div, so it's "Register your Company Below:" to begin with. But, once you've hit a company name that does exist, you replace that HTML with "This Company Already Exists!". From that point on, $reg, on both the JavaScript and PHP sides, is always "This Company Already Exists!" (since you always pass $reg in your POST).
It would probably be much easier if the contents of that div weren't passed to or handled by the PHP code at all. It'd be simpler if your PHP script just returned "1" if the company existed, and "0" if not (or some other equally simple flags).
Then, on the JavaScript side, you could just do:
$.post('include/reg_post.php', { company: $company }, function(exists) {
var message;
if (exists === '1') {
message = 'This Company Already Exists!';
}
else {
message = 'Register Your Company Below:';
}
$('#exists').html(message);
});
You're passing $('#exists').html(); to be returned in the event that the company is not found. The problem is, in the event that the company is found, you replace the html within #exists. Then the next time you call the post you pass this text back along so in this case:
if(mysql_num_rows($result) <= 1){
echo $reg;
} else {
echo "This Company Already Exists!";
}
your $reg is now set to This Company Already Exists! so regardless of what happens you're going to return that text.