I have more GET variables. I want the variables to be added after clicking. And after clicking again I want them to be removed from GET. I am a beginner and I don't know how to do it.
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url=$_SERVER[QUERY_STRING];
if(!empty($url)){
$url="&".$url;
}
?>
<form action="" method="GET">
<?php
foreach($tab_array as $key => $val){
?>
<?php echo $key;?>
<?php
}
?>
</form>
Someone will help?
Sorry for my bad English...
Code
<?php
$tab_array['name1']=1;
$tab_array['name2']=2;
$tab_array['name3']=3;
$tab_array['name4']=4;
$url='?'; // this will call the current url
// $_GET is the array your submitted data will be strored in - initially empty []
?>
<form method='GET'><!-- you actually don't need a form, since only input, textarea, etc get submitted -->
<?php
// save current state, so you can modify it for every possible click
$current_get = $_GET;
foreach($tab_array as $key => $value) {
$new_get = $current_get;
// check if the current key is already in your set ($new_get)
if (array_key_exists($key, $new_get)) { // it is, so remove
unset($new_get[$key]);
} else { // it is not, so add
$new_get[$key] = $value;
}
// build your query_string (from $new_get array)
$query_string = http_build_query($new_get);
// you can use variables in string when its encapsulated in double quotes: "text $var"
echo "<a href='$url$query_string'>$key</a>";
// more readable:
// echo "<a href='{$url}{$query_string}'>{$key}</a>";
// not need but looks better :P
echo '<br />' . PHP_EOL;
}
?>
</form>
A little more
there is a shortcut for <php echo $var ?> which is just <?= $var ?>
Links
array_key_exists
unset
http_build_query
Related
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 3 years ago.
I am new to PHP and working on an assignment. I'm almost finished but feel like I'm beating my head against the wall with this last step.
The user chooses a survey and then answers 10 questions. After the 10th question is answered, they are redirected to the results.php page which should display their questions and answers.
I know that I need to use a foreach loop but this is my first time working with them. I've finished multiple sites to get an understanding of how they work but the examples are not helping me to understand how to make it work in my assignment.
Right now I get this when I run the file:
Parse error: syntax error, unexpected 'endforeach' (T_ENDFOREACH), expecting end of file in C:\xampp\htdocs\sandbox\HW4\results.php on line 38
When I remove the endforeach, I'm told that $answer within the echo is undefined.
I've run out of ways to change my loop. Nothing works. Some help would be appreciated. I apologize if I include code that is not relevant to my problem.
With little understanding of PHP, I'm not quite sure what I need to include and what I don't. I'm including code from my survey.php file that includes the array session and my code from the results file that should contain my foreach loop.
Thank you for your time.
$isPostBack = filter_input(INPUT_POST, 'submitButton') !== NULL;
if ($isPostBack) {
// This is what happens if there is a postback.
$choose_survey = filter_input(INPUT_POST, 'choose_survey', FILTER_VALIDATE_INT);
if ($choose_survey !== NULL) {
// Check the value of $choose_survey and then set 'survey' accordingly, e.g.
// These numbers are the keys to the arrays with the list of surveys
switch ($choose_survey) {
case 0:
$_SESSION['survey'] = $survey0;
break;
case 1:
$_SESSION['survey'] = $survey1;
break;
case 2:
$_SESSION['survey'] = $survey2;
break;
default:
break;
}
$_SESSION['answers'] = array();
$_SESSION['number'] = 1;
} else {
// A survey is not selected because it was already chosen.
// get the value from the radio button.
$answer = filter_input(INPUT_POST, 'answer', FILTER_DEFAULT);
if ($answer == NULL) {
echo '<p>Please select an answer before clicking Submit.</p>';
} else {
$question_key = filter_input(INPUT_POST, 'question_key', FILTER_VALIDATE_INT);
$question = $_SESSION['survey'][$question_key];
// this will be used later to display the answers/results
$_SESSION['answers'][$question] = $answer;
unset($_SESSION['survey'][$question_key]);
// This is adding 1 to the question number unless session number is 10
if ($_SESSION['number'] == 10) { // if = to 10 then we redirect to next page.
header('Location: results.php');
} else { // If number is less than 10, we add 1
$_SESSION['number'] += 1;
}
}
}
} else {
// This is what happens if there is no postback.
}
?>
results.php file
<br /> <p>Thank you for participating in the survey!</p>
<html lang="en">
<head>
<title>Survey Results</title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<form action="logout.php">
<p>Here are your results</p>
<input type="submit" id="submit" value="Logout" />
</form>
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer) ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php endforeach; ?>
</section>
</body>
did you loaded the session_start() on your file? If not this may not enable to save your sessions that you are setting. Also on your results.php you can change your code to:
<?php foreach($_SESSION['answers'] as $question => $answer){ ?>
<p>
<?php echo $answer."<br/>"; ?>
</p>
<?php }
?>
Hope this helps!
I am not sure, but maybe you could place <?php session_start();?> at the beginning of your results.php to make your script able to work with $_SESSION variable?
Also try to var_dump($_SESSION); as in result.php, just in case.
I surprised that nobody noticed the syntax error in the foreach.
If you want to use the endforeach style, you can change your code like this (this is called Alternative Syntax):
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer): ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php endforeach; ?>
</section>
Or if you want to use PHP-way to make a foreach, you can write it like this:
<section>
<?php foreach ($_SESSION['answers'] as $question => $answer) { ?>
<p>
<?php echo "$answer <br/>"; ?>
</p>
<?php } ?>
</section>
However, for cleaner HTML & PHP code, I suggest you to write it like this:
<section>
<?php
foreach ($_SESSION['answers'] as $answer) {
echo "<p>$answer</p>" . PHP_EOL;
}
?>
</section>
Note that I removed unused $question variable.
Update 2
I'll just leave this here for future references. But this is the solution I created with all the help I got here. Thanks!
<script>
function Refresh() {
location.reload();
}
</script>
<?php $number = $_SESSION["page_id"]; ?>
<?php
if (isset($_SESSION['page_id']) && !empty($_SESSION['page_id'])) {
echo do_shortcode('[RICH_REVIEWS_SHOW category="page" num="all" id="'. $number .'"]');
session_destroy();
echo ('<button class="btn btn-0001" onclick="Refresh()">Show All</button>');
}
else{ echo do_shortcode('[RICH_REVIEWS_SHOW num="all"]'); }
;
?>
Update
So I'm trying to just do a simple echo to see if the session is set using this code:
<?php if(isset($_SESSION['page_id']) && !empty($_SESSION['page_id'])) {
echo 'Set and not empty, and no undefined index error!');
};?>
But doing this breaks my page, I just get a blank page? How do I check if the session is set? When I do a echo of the session using this code:
<?php echo $_SESSION["page_id"]; ?>
It does output the correct session value?? What am I doing wrong?
I have a sessions saved with PHP and I'm using this so that the page ID from Wordpress is echo-ed in a shortcode do_shortcode('');
This is what my code looks like:
<?php $number = $_SESSION["page_id"]; ?>
<?php echo do_shortcode('[RICH_REVIEWS_SHOW category="page" num="all" id="'. $number .'"]'); ?>
<?php echo do_shortcode_all('[RICH_REVIEWS_SHOW category="page" num="all" id="all"]'); ?>
<?php echo $shortcode ;?>
<?php echo $shortcode_all ;?>
Now, what I would like to do is IF the page_id is not stored in the session it should echo all. So how do I go about this?
I found this code, and I think its something I need... But I'm not that great a programmer/coder...
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>
So, if I where to put these two together I would get something like this
<?php
$number = $_SESSION["page_id"];
// Evaluates to true because $var is empty
if (empty($number)) {
echo $shortcode_all ;
}
// Evaluates as true because $var is set
if (isset($number)) {
echo $shortcode ;
}
?>
Am I in the right direction?
Solution
<?php
if (isset($_SESSION['page_id']) && !empty($_SESSION['page_id'])) {
echo('Set and not empty, and no undefined index error!');
};
?>
What am I supposed to feel from the missing (?
If you are using wordpress then you should use the session_start(); in wp-config.php file so please first put in you wp-config.php at top and then check.
<?php
$number = $_SESSION["page_id"];
// Evaluates to true because $var is empty
if (empty($number) || $number=='') {
echo $shortcode_all ;
}else{
echo $shortcode ;
}
?>
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.
I have a form where you can select a radio button and it should transfer what was selected to the next page. My problem is that no matter which radio button you choose it always transfers the value associated last radio button over instead of the one you chose.
So if I choose Around the World it carries 5 with it instead of 10
I am required to use the GET method.
Here is my code:
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
}
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}
This is the code for the next page:
echo "<b>$sub</b><br />";
echo "Base Total: $ $s_value/mon x $month months <br />";
Yes I have omitted a lot of things, because everything else in my code is fine.
I tried doing this as well, adding in an unset() statement but it didnt work. It completely deleted the value variable....
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
foreach($title as $sub=>$s_value) {
echo "$sub $$s_value";
echo '<input type="radio" name="sub" value="', $sub,'">';
echo "<br>";
unset($s_value);
}
//I also tried putting the unset here//
if (empty($_GET["sub"])) {
} else {
$sub = sub_input($_GET["sub"]);
}
if (empty($_GET["s_value"])) {
} else {
$s_value = sub_input($_GET["s_value"]);
}
if (isset($title['sub'])){
$valid=false;
}
You need to change the names of your variables $s & $s_value within the foreach loop. The foreach loop is setting these variables and they are then being accessed outside of the foreach loop if either of the GET values is empty such that there is no GET value to replace the contents of the variable. Therefore, it always uses 5 as the value because that is the last $s_value that you set.
In summary, changing $s & $s_value within the foreach loop to something like $key & $value respectively will fix your problem with the array value. Alternatively, you could unset them after the foreach loop but before the if statements.
In your current code, you just happened to switched the values on the loop. 10, 7, 5 are inside the elements, while the names Around The world... etc are inside the keys. You just need to switch them. Consider this example:
<?php
$title = array("Around the World"=>"10","Coast to Coast"=>"7","The Big City"=>"5");
if(isset($_GET['submit'], $_GET['sub'])) {
$sub = $_GET['sub'];
$name = array_search($sub, $title);
echo '<script>alert("You selected '.$name. ' => '.$sub.'");</script>';
}
?>
<form method="GET" action="index.php">
<?php foreach($title as $key => $value): ?>
<input type="radio" name="sub" value="<?php echo $value; ?>" /> <?php echo $key; ?> <br/>
<?php endforeach; ?>
<br/>
<input type="submit" name="submit" value="Submit" />
</form>
Hey guys, I've gotten as far as my code below, but I am trying to create an AJAX search form that is 'safe' on my wordpress blog, by detecting the session variable or a cookie or something
<?php
#session_start();
If (!array_key_exists(‘authed’, $_SESSION))
{
include ‘not_authed.inc’;
exit();
}
// go about your business.
?>
and i'm trying to add that to this:
<?php
function checkValues($value)
{
// Use this function on all those values where you want to check for both sql injection and cross site scripting
//Trim the value
$value = trim($value);
// Stripslashes
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
// Convert all <, > etc. to normal html and then strip these
$value = strtr($value,array_flip(get_html_translation_table(HTML_ENTITIES)));
// Strip HTML Tags
$value = strip_tags($value);
// Quote the value
$value = mysql_real_escape_string($value);
return $value;
}
mysql_connect ("mysql.*****.com", "****","$*****") or die (mysql_error());
mysql_select_db ("***********");
$term = checkValues($_REQUEST['val']);
$term = mysql_real_escape_string($term);
$sql = mysql_query("select * FROM patient_db WHERE id_number = '$term'");
if($row = mysql_fetch_array($sql)) {
echo "<img src=\"******\" class='leftfloat' border=0>";
echo '<p>';
echo '<br /> ID Number: ' .$row['id_number'];
echo '<br /> Name: ' .$row['Name'];
echo '<br /> Exp. Date: ' .$row['exp_date'];
echo '<br /> DOB: ' .$row['dob'];
echo '</p>';
//echo "<a href='******' title='Printer Friendly Version' alt='Printer Friendly Version'><img src=\"*****\" class='rightfloat' border=0 height=33 width=33></a>";
} else {
echo "<img src=\"*****\" height=50 width=50 class='leftfloat' border=0>";
print "<h1>USER ID <br/>NOT FOUND</h1><br />";
print "<strong>OOPS!! THIS COULD BE AN ERROR</strong><br />";
print "<br />";
print "<div>*****</div>";
}
?>
The problem you are going to have is that the AJAX request is a separate session / cookie as it is a completely different process not tied into to the browser.
So how do you go about authenticating someone? A Token of sorts. So you would create a hash, which would need to be stored in the database for the user, which can be regenerated upon login etc. Then you would use this token to validate that user and allow the AJAX submission to work.
Hopefully that gets the ball rolling for you. So in your AJAX push script you would just appened a variable to the GET or POST data called token and then check it on the receiving PHP script. There are other ways of doing it, this is just one that I know of :)