I have a basic math question that the user has to answer before they can send an email:
$first_num = rand(1, 4);
$second_num = rand(1, 4);
$send = #$_POST['send'];
if($send){
//The user's answer from the input box
$answer = #$_POST["answer"];
if($answer == $first_num + $second_num) {
//Do stuff
}
else {
$error_message = "You answered the question wrong!";
}
}
I answer the question correctly (unless my first grade math is off!) yet it says I have the question wrong. I am not sure what the issue is but I imagine it is something to do with the fact that php executes immediately when the page is loaded and so new numbers are generated as soon as the user presses the submit button? Or am I way off? If that is the case, what can be done to solve this?
The problem is that you are setting your values every time your script is called. So when you post your form, two new values are set and they are likely not the same values as when you called the script the first time to show the form.
You should store your variables in a session and retrieve these values when you process your post request.
Something like:
session_start();
if (!isset($_SESSION['numbers']))
{
$_SESSION['numbers']['first'] = rand(1, 4);
$_SESSION['numbers']['second'] = rand(1, 4);
}
...
if ($answer == $_SESSION['numbers']['first'] + $_SESSION['numbers']['second']) {
//Do stuff
/**
unset the variables after successfully processing the form so that
you will get new ones next time you open the form
*/
unset($_SESSION['numbers']);
...
Note that you will need to use the session variables everywhere where you are using your own variables right now.
You should include the two numbers as hidden form inputs in your HTML, and then do the math with the entries in your $_POST array.
Make your code start like this instead:
$first_num = $_POST["first_num"];
$second_num = $_POST["second_num"];
Related
I have a form sender which is posting a value of 6 to another form receiver. What I'm trying to achieve is store the posted value from sender into a variable in the receiverthen increment the variable it every time the sender posts. Then print the updated variable
This is what I have tried to do
$val= $_POST['val'];
$limit = 6 + $val;
echo $limit;
Im getting the result as 12. But what I want is
After first post result = 12
After second post result = 18
On and on...
NB:$_POST['val'] = 6;
session_start();
$limit = 6;
if(!isset($_SESSION['lastLimit'])) {
$_SESSION['lastLimit'] = 0;
}
if(!empty($_POST)) {
$_SESSION['lastLimit'] = $_SESSION['lastLimit'] + $limit;
$postedValue = $_POST['val'] + $_SESSION['lastLimit'];
echo $postedValue;
}
Because the web is stateless i.e. scripts do not remember anything that happened the last time a page/form was executed the receiver script does not remember anything from the last time it was run.
But dont panic, there is a way. Its called a SESSION and you can store data in the session which will then be available the next time this user connects to your site. In PHP you use it like this. The session is linked to this specific connection to a specific user.
receiver.php
<?php
// must be run at top of script, before any output is sent to the new form
session_start();
// did the form get posted and is the variable present
// or replace POST with GET if you are using an anchor to run the script
if ( $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['val']) {
if ( isset($_SESSION['limit'] ){
// increment the limit
$_SESSION['limit'] += (int)$_POST['val'];
} else {
// initialize the limit
$_SESSION['limit'] = (int)$_POST['val'];
}
echo 'Current value of limit is = ' $_SESSION['limit'];
} else {
// something is not right
// direct this user to some basic page like the homepage or a login
header('Location: index.php');
}
You need an intermediate layer to store the value.
Available options:
1) Global static value
2) session
3) file
4) database
I would recommend global value or session, as they data you want to store isn't that huge and would meet the requirements easily.
I would not write the syntax to store it in session as a number of people have already mentioned it. I just wanted to clarify the problem scenario and possible solutions.
You can store $limti into global varibale .
global $val;
$val += $_POST['val'];
$limit = 6 + $val;
echo $limit;
Got action with one waiting for parameter , and to run this action I need always one param. But also in this action I doing validation for other form and after this my first variable always disappears.
How I can keep this $var after isValid?
public function myAction(){
if ($this->getRequest()->isPost() || $this->getRequest()->getParam('number')){
//this is where got my number
$number = $this->getRequest()->getParam ('number');
//and use to display site.
if ($this->getRequest()->isPost()){
if($commentForm->isValid($this->getRequest()->getPost())){
//if I get Valid data I do upload or etc.
} else {
//but if form is inValid won't display everything one more time.
//but **$number is now Null**.
$this->view->data = $tUser->getCommentAndUserByTelephone($number);
$this->view->commentForm = $commentForm;
}
}
}
}
How I can keep this $number without repost?
You can try storing it with sessions.
http://www.w3schools.com/php/php_sessions.asp
$_SESSION['numbers'];
Pass that number to view $this->view->number = $number; and resend it instead of a new number. Simple!
There was a great article posted by CSS-Tricks.com describing how to create a poll using PHP and a MySQL database. I've followed this and created a nice poll for myself. I noticed in the comments a mentioning of using AJAX to show the results on the same page instead of a completely separate page.
I am wondering what is the best way to display PHP Poll results on the same page?
UPDATE:
The answer is really simple. In fact, CSS-Tricks' poll without AJAX in my opinion is more difficult since it requires a database. This one does not!
The complete tutorial for creating a poll with PHP and AJAX is can be viewed here:
http://www.w3schools.com/php/php_ajax_poll.asp
I just wanted to clarify how to set the arrays up for more than two poll options. First you get the "database" (i.e. text file, not MySql).
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);
Then you put the data in an array:
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
//if multiple options
$array = explode("||", $content[0]);
$option1array = $array[0]; //note: these values can be text values also. If text value, nothing changes with this part of the code.
$option2array = $array[1];
$option3array = $array[2];
$option4array = $array[3];
Store Data in "database"
if ($vote == 'option1')
{
$option1array = $option1array + 1;
}
if ($vote == 'option2')
{
$option2array = $option2array + 1;
}
if ($vote == 'option3')
{
$option3array = $option3array + 1;
}
if ($vote == 'option4')
{
$option4array = $option4array + 1;
}
Then, output your results. For file structure and AJAX script, see the complete tutorial.
You have two options:
1) Use ajax just as you suggested in your question, when you submit the vote via ajax, get the results back as the response.
2) Get the results before the vote is submitted, it will still need to be submitted via ajax if you want to stay on the same page. But instead of using ajax to get back the results, since you have the results prior to the vote you could just add one vote to the appropriate selection choice, then use Javascript / CSS to change the results from hidden to displayed.
okay here is my code :
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php $i++; ?>
}
i'm still learning about this whole php and javascript thing, and i know there are many things that i still had to work to to improve my understanding to this both language. that's why i really need your help in this
i'm trying to get the while iteration to work so i can compare the variable from javascript with variable from php which took the value from database. the php variable ('$mfr' and '$mto'), as you can see, is an array. now i want it to look at every element of both and if it meets the condition then it will update the variable 'comp' and stop the whole while iteration
but the problem is the '$i' variable doesn't do the iteration thing. it runs only once so my '$mfr' and '$mto' value doesn't go anywhere. how can i fix this so i can compare the javascript value with the php '$mfr' and '$mto' value?
your help would be much appreciated, thank you :)
EDIT
well, it is actually a function of custom validation for jqgrid.
and i do know that php is a server-side and javascript is a client-side language theoretically, though i don't really know it is practically
what i'm actually trying to do is when a user input a value and submit it, the system will check whether the value that was entered are between value of 'fromid' and 'toid' column of a table in database
here is my full code of the function
function checkid(value)
{
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php echo $i++; ?>
}
if (comp != 'T')
{
return [true, "", ""];
}
else
{
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
while this is how i got the '$mfr' and '$mto' variable
<?php
$db=new database($dbtype, $dbhost, $database, $dbuser, $dbpassword, $port, $dsn);
$db->query("select fromid, toid from CORE_ID");
$i = 0;
while($row = $db->get_row())
{
$mfr[$i] = $row[fromid];
$mto[$i] = $row[toid];
$i++;
}
?>
if theres any better way to do this, then please do tell me
Typically, PHP is for server side logic and JS is for client side logic. If you want to send a value from JS to be processed in PHP, you'll probably need to use something like AJAX, which jQuery makes pretty easy with jQuery.ajax().
Getting the client value to be processed is the difficult part. Once you can do that, rewriting your code logic in full PHP should not be difficult.
EDIT: If I'm misunderstanding where variable value comes from, please say so!
EDIT 2: It looks like you want to have client input compared to server side data. JS will not have access to your PHP variables unless they are specifically sent there. Likewise, you can send your JS value to the server for validation in the PHP.
In your case, you could use JSON to send send the JS your validation dates. Assuming you don't have too many dates, it will probably be faster than sending a value to the server and waiting for a response.
I found a good example of using JSON at another post. You can send an array like:
<?php
$xdata = array(
'foo' => 'bar',
'baz' => array('green','blue')
);
?>
<script type="text/javascript">
var xdata = <?php echo json_encode($xdata); ?>;
alert(xdata['foo']);
alert(xdata['baz'][0]);
// Dot notation can be used if key/name is simple:
alert(xdata.foo);
alert(xdata.baz[0]);
</script>
For your code, you could put $mfr and $mto into a single 2D array. Here is how your new JS might look, assuming xdata contains $mfr and $mto:
function checkid(value) {
var co = 0, comp = '', i = 0, nrows = xdata.mfr.length;
while (co < nrows) {
if ((parseInt(value) >= xdata.mfr[i]) && (parseInt(value) <= xdata.mto[i])) {
comp = 'T';
break;
}
co++;
i++;
}
if (comp != 'T') {
return [true, "", ""];
} else {
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
You have a loop in your Javascript, not your PHP. So the PHP is only going to get executed once. You need to rethink your approach. Without knowing what the script is supposed to actually achieve it's difficult to provide working code, but you at least need to put the loop into the PHP instead of the Javascript.
Before I can answer you should understand what's going on exactly:
PHP is being executed on the server, then sends back the result (HTML and Javascript) to the client (the browser).
Javascript is being executed on the client side. So this only starts after PHP is completely done. For this reason you can't mix Javascript and PHP.
Check the source of the page, then you'll see exactly what the server returns (what HTML/Javascript PHP generates) and you'll get a better insight of what happens.
Now, if you understand this, you may be able to solve your own problem. I don't exactly know what you want to do, but I can advice you that if you need Javascript to check values from the database, you should generate Javascript using PHP that defines these values in the Javascript like for example this:
var my_js_var = <?=$my_php_var?>
var another_var = <?=$another_one?>
Now they are defined in Javascript and you can use them (and check them).
When you have a large database it can become inefficient to do it like this and you might want to look into a technology called AJAX, which allows Javascript to do a request to the server and get back data from a PHP script.
You would also want to do this if there's data involved you don't want to be publicly viewable (because everyone can look into the source of your page.
I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!