PHP: Session variable does not increase in first iteration - php

I've written a short PHP programm which shows two pictures. With 2 radio buttons, you have to choose one and then you have to click the submit button. Then, the page saves the vote for the picture you have chosen and then shows the next two pictures.
I use a session variable to store, which images have to be showed.
Unfortunately, the variable is not increased after the first click on the "next" button. After, it works perfectly well.
What is wrong?
Here is my code:
<?php
session_start();
if (isset($_SESSION['image_nr'])) { /* If there is already a value set */
$x = $_SESSION['image_nr'];
echo $x;
}
else {
$_SESSION['image_nr'] = 1; /* Set to 1 */
$x = $_SESSION['image_nr'];
}
include('sql/db_connect.php');
include('sql/queries.php');
if($x == 9){
increaseParticipants();
$_POST['submit']='';
$_SESSION['image_nr'] = 1;
session_unset($_SESSION['image_nr']);
header( "Location: thankyou.php" );
}
?>
<html>
<header>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" language="JavaScript" src="functions.js"></script>
</header>
<body>
<form action= "" method = "post">
<div class='content' id='image1'><?php if($x == 1){echo"<img src='images/image_1.jpg' width='380'><br>Image 1";}?></div>
<div class='content2' id='image2'><?php if($x == 1){echo"<img src='images/image_2.jpg' width='380'><br>Image 2";}?></div>
<div id='bottom'>
<input type='radio' name='radio' id='radio1' value='<?php echo $x; ?>' onchange="enableButton()"> Image <?php echo $x; ?> <br>
<input type='radio' name='radio' id='radio2' value='<?php echo ($x+1);?>' onchange="enableButton()"> Image <?php echo $x+1; ?><br>
<input type="submit" id="button" name= "submit" value="Next" onclick="saveClick()" disabled />
</div>
<?php
if (isset($_POST['submit']) && $_POST['submit']!='') {
if(isset($_POST['radio'])) {
$image = $_POST['radio'];
increaseClicks($image);
$x = $x+2;
}
$_SESSION['image_nr'] = $x;
$next = getNext($image);
echo '<script type="text/javascript">'
, 'changeImage('.$next.');'
, '</script>'
;
$_POST['submit']='';
}
?>
</form>
</body>
</html>
Here are the JS functions:
function enableButton(){
document.getElementById("button").disabled = false;
}
function changeImage(next){
var firstpart = "<img src='images/image_";
var secondpart = ".jpg' width='380'><br>Bild"+next;
var inHtml = firstpart.concat(next, secondpart);
document.getElementById("bild1").innerHTML = inHtml;
var secondpart = ".jpg' width='380'><br>Bild"+(next+1);
var inHtml = firstpart.concat((next+1), secondpart);
document.getElementById("bild2").innerHTML = inHtml;
}
And the queries (I know that these are deprecated)
<?php
function getClicks ($image){
$q1 = "SELECT clicks from tbl_clicks WHERE ID_bild=".$image;
$rq1 = mysql_query($q1);
$return = mysql_fetch_array($rq1);
$number_of_clicks = $return['clicks'];
return $number_of_clicks;
}
function getClicksAll (){
$q1 = "SELECT ID_bild, name, clicks from tbl_clicks";
$rq1 = mysql_query($q1);
return $rq1;
}
function increaseClicks ($image){
$clicks = getClicks($image);
$clicks = (int)$clicks;
$clicks = $clicks + 1;
echo "this are the clicks: ".$clicks;
$q2 = "UPDATE tbl_clicks SET clicks = ".$clicks." WHERE ID_bild = ".$image;
mysql_query ($q2);
}
function getNext ($image){
$q3 = "SELECT next from tbl_clicks WHERE ID_bild=".$image;
$rq3 = mysql_query($q3);
$return = mysql_fetch_array($rq3);
$next = $return['next'];
return $next;
}
function getParticipants(){
$q4 = "SELECT participants from tbl_participants";
$rq4 = mysql_query($q4);
$return = mysql_fetch_array($rq4);
$participants = $return['participants'];
return $participants;
}
function increaseParticipants(){
$participants = getParticipants();
$q5 = "UPDATE tbl_participants SET participants = ".($participants+1);
mysql_query ($q5);
}
?>

Related

autocomplete does not display accurate answer it displays all options

I have a page where i have to display district drop down on selection of state dropdown. and then display postoffices dropdown on selection of distirict dropdown. then a autocomplete places input box on selection of postoffice dropdown.
i completed it successfully. but the autocomplete input box of places does not display options as per entered keywords, weather it displays all options what ever keyword is entered.
below is my php page :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="js/jquery-ui.css">
<script src="js/jquery.js"></script>
<script src="js/jquery-ui.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
$r = file('app_data/in.txt');
$states = array();
foreach($r as $value){
$x = explode("\t",$value);
//$india[] = array('pin'=>$x[1], 'place' => $x[2], 'state' => $x[3], 'dist' => $x[5] );
$states[] = $x[3];
}
$states = array_unique($states);
sort($states);
echo '<select id="state">';
foreach($states as $state){
echo "<option> $state </option>";
}
echo '</select>';
foreach($_POST as $post){
echo $post;
}
echo '<select id="dist">';
echo '</select>';
echo '<select id="postoffice">';
echo '</select>';
?>
<script>
$('#state').focusout(function (){
$.get('func-get-dist.php',{'state' : $(this).val()},function(data){
$('#dist').html(data);
});
});
$('#dist').focusout(function (){
$.get('func-get-dist.php',{'state' : $('#state').val(),'dist' : $(this).val()},function(data){
$('#postoffice').html(data);
});
});
$('#postoffice').focusout(function (){
var postoffice = $(this).val();
$('#tags').autocomplete({
source : ("func-get-dist.php?postoffice="+postoffice),
});
});
</script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
<div id="test">
<div id="test1">
</div>
</body>
</html>
below is my html-get-dist.php page :
<?php
if(isset($_GET['postoffice']) && !empty($_GET['postoffice'])){
$postoffice = $_GET['postoffice'];
$r = file('app_data/in.txt');
$places = array();
foreach($r as $value){
$x = explode("\t",$value);
if(strtolower($x[7]) == $postoffice){
$places[] = strtolower(trim($x[2]));
}
}
$places = array_unique($places);
sort($places);
echo json_encode($places);
}elseif(isset($_GET['state']) && !empty($_GET['state'])){
if(isset($_GET['dist']) && !empty($_GET['dist'])){
$state = $_GET['state'];
$dist = $_GET['dist'];
$r = file('app_data/in.txt');
$posts = array();
foreach($r as $value){
$x = explode("\t",$value);
if(($x[3] == $state) && ($x[5] == $dist)){
//echo $x[6].'-'.$x[7].'-'.$x[8].'<br>';
$posts[] = $x[7];
}
}
$posts = array_map('strtolower',$posts);
$posts = array_unique($posts);
sort($posts);
foreach($posts as $postoffice){
echo '<option>'.$postoffice.'</option>';
}
}else{
$state = $_GET['state'];
$r = file('app_data/in.txt');
$dists = array();
foreach($r as $value){
$x = explode("\t",$value);
if($x[3] == $state){
$dists[] = $x[5];
}
}
$dists = array_unique($dists);
sort($dists);
foreach($dists as $dist){
echo '<option>'.$dist.'</option>';
}
}
}
?>
You compare the userinput with the entire value, try to do the comparison with the same number of characters as the user entered:
foreach($r as $value){
$x = explode("\t",$value);
$charCount = strlen($postoffice);
if(strtolower(substr($x[7], $charCount)) == strtolower($postoffice)){
$places[] = strtolower(trim($x[2]));
}
}
Edit: It took me some time to figure it out but I think I have solution. There are 2 mistakes in your code:
in js you get the value of the select with var postoffice = $(this).val();, but .val() returns the selected index of the selectbox, not the selected text.
you compare the selected postoffice with $x[7], this is the 8th tab separated column in you data, if my count is correct you only have 7 columns there.
So my guess is that here you compare undefined with 0 and that returns true:
if(strtolower($x[7]) == $postoffice){
To solve this get the value in js like this:
var postoffice = $("option:selected", this).text();
... and use the correct index in the php comparison.

Passing information using post method without session variables

I will admit immediately that this is homework. I am only here as a last resort after I cannot find a suitable answer elsewhere. My assignment is having me pass information between posts without using a session variable or cookies in php. Essentially as the user continues to guess a hidden variable carries over all the past guesses up to that point. I am trying to build a string variable that holds them all and then assign it to the post variable but I cannot get anything to read off of the guessCounter variable i either get an undefined index error at the line of code that should be adding to my string variable or im just not getting anything passed over at all. here is my code any help would be greatly appreciated as I have been at this for awhile now.
<?php
if(isset($_POST['playerGuess'])) {
echo "<pre>"; print_r($_POST) ; echo "</pre>";
}
?>
<?php
$wordChoices = array("grape", "apple", "orange", "banana", "plum", "grapefruit");
$textToPlayer = "<font color = 'red'>It's time to play the guessing game!(1)</font>";
$theRightAnswer= array_rand($wordChoices, 1);
$passItOn = " ";
$_POST['guessCounter']=$passItOn;
$guessTestTracker = $_POST['guessCounter'];
$_POST['theAnswer'] = $theRightAnswer;
if(isset($_POST['playerGuess'])) {
$passItOn = $_POST['playerGuess'];
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$guessTestTracker = $_GET['guessCounter'];
$theRightAnswer = $_GET['theAnswer'];
}
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['playerGuess'])) {
if(empty($_POST['playerGuess'])) {
$textToPlayer = "<font color = 'red'>Come on, enter something(2)</font>";
}
else if(in_array($_POST['playerGuess'],$wordChoices)==false) {
$textToPlayer = "<font color = 'red'>Hey, that's not even a valid guess. Try again (5)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if(in_array($_POST['playerGuess'],$wordChoices)&&$_POST['playerGuess']!=$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>Sorry ".$_POST['playerGuess']." is wrong. Try again(4)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
if($_POST['playerGuess']==$wordChoices[$theRightAnswer]) {
$textToPlayer = "<font color = 'red'>You guessed ".$_POST['playerGuess']." and that's CORRECT!!!(3)</font>";
$passItOn = $_POST['guessCounter'].$passItOn;
}
}
}
}
$_POST['guessCounter'] = $passItOn;
$theRightAnswer=$_POST['theAnswer'];
for($i=0;$i<count($wordChoices);$i++){
if($i==$theRightAnswer) {
echo "<font color = 'green'>$wordChoices[$i]</font>";
}
else {
echo $wordChoices[$i];
}
if($i != count($wordChoices) - 1) {
echo " | ";
}
}
?>
<h1>Word Guess</h1>
Refresh this page
<h3>Guess the word I'm thinking</h3>
<form action ="<?php echo $_SERVER['PHP_SELF']; ?>" method = "post">
<input type = "text" name = "playerGuess" size = 20>
<input type = "hidden" name = "guessCounter" value = "<?php echo $guessTestTracker; ?>">
<input type = "hidden" name = "theAnswer" value = "<?php echo $theRightAnswer; ?>">
<input type = "submit" value="GUESS" name = "submitButton">
</form>
<?php
echo $textToPlayer;
echo $theRightAnswer;
echo $guessTestTracker;
?>
This is a minimal functional example of what you need to do. There are still a couple of minor bugs (like duplicate entries in the history), but I've left these as an exercise for you. Treat this as a starting point and build up what you need from it.
I've added comments to explain what's happening, so hopefully it is clear to you.
$answer = null;
$history = [];
$choices = ['apple', 'grape', 'banana'];
$message = '';
// check if a guess has been made.
if (!empty($_POST) && !empty($_POST['guess'])) {
// check if previous guesses have been made.
if (!empty($_POST['history'])) {
$history = explode(',', $_POST['history']);
}
// check guess.
if (!empty($_POST['answer']) && !empty($_POST['guess'])) {
// check guess and answer are both valid.
if (in_array($_POST['guess'], $choices) && isset($choices[$_POST['answer']])) {
if ($_POST['guess'] == $choices[$_POST['answer']]) {
// correct; clear history.
$history = [];
$message = 'correct!';
} else {
// incorrect; add to history and set previous answer to current.
$history[] = $_POST['guess'];
$answer = $_POST['answer'];
$message = 'incorrect!';
}
} else {
// invalid choice or answer value.
}
}
}
if (empty($answer)) {
// no answer set yet (new page load or correct guess); create new answer.
$answer = rand(0, count($choices) - 1);
}
?>
<p>Guess the word I'm thinking:</p>
<p><?php echo implode(' | ', $choices) ?></p>
<form method="POST">
<input type="hidden" name="answer" value="<?php echo $answer; ?>">
<input type="hidden" name="history" value="<?php echo implode(',', $history); ?>">
<input type="text" name="guess">
<input type="submit" name="submit" value="Guess">
</form>
<p><?php echo $message; ?></p>

Issue with Checkboxes and Javascript, PHP

I am struggling with the following PHP and JavaScript codes to have 2 sets of check-boxes filtering a range of data obtained from a MySQL database.
Here is the code:
<script type="text/javascript">
//http://jsbin.com/ujuse/1/edit
$(function() {
$("input[type='checkbox']").on('change', function() {
var boxes = [];
// You could save a little time and space by doing this:
var name = this.name;
// critical change on next line
$("input[type='checkbox'][name='"+this.name+"']:checked").each(function() {
boxes.push(this.value);
});
if (boxes.length) {
$(".loadingItems").fadeIn(300);
// Change the name here as well
$(".indexMain").load('indexMain.php?'+this.name+'=' + boxes.join("+"),
function() {
$(".indexMain").fadeIn('slow');
$(".loadingItems").fadeOut(300);
});
} else {
$(".loadingItems").fadeIn(300);
$(".indexMain").load('indexMain.php', function() {
$(".indexMain").fadeIn('slow');
$(".loadingItems").fadeOut(300);
});
}
});
});
</script>
<?php
function echoCheckboxSet($header, $divClass, $columnName, $setName) {
include ("connection.php");
$checkboxes = $con -> prepare("SELECT DISTINCT $columnName FROM item_descr ORDER BY $columnName ASC");
$checkboxes->execute();
?>
<div class="bgFilterTitles">
<h1 class="filterTitles"><?php echo $header;?></h1>
</div>
<div class="<?php echo $divClass; ?>">
<?php
while ($box = $checkboxes->fetch(PDO::FETCH_ASSOC)):
$boxColumnName = str_replace('_',' ',$box[$columnName]);
?>
<input type='checkbox' class='regularCheckbox' name='<?php echo $setName; ?>' value='<?php echo $box[$columnName]; ?>' />
<font class='similarItemsText'><?php echo $boxColumnName; ?></font>
<br />
<?php
endwhile;
?>
</div>
<?php
} // end of echoCheckboxSet
// Call our method twice, once for colors and once for prices
echoCheckBoxSet("COLOR", "colors", "color_base1", "color[]");
echoCheckBoxSet("PRICE", "prices", "price", "price[]");
?>
Then I am perfectly getting my check-boxes but when clicking on any of them they don't do anything.
My indexMain.php retrieves the values like this:
$colors = $_GET['color[]'];
echo "TEST".$colors[1];
$colors = explode(' ', $colors);
$parameters = join(', ', array_fill(0, count($colors), '?'));
$items = $con -> prepare("SELECT * FROM item_descr WHERE color_base1 IN ({$parameters})");
$items ->execute($colors);
$count = $items -> rowCount();
----------------- Adding the echo:
echo "<div>Showing ".$count."items</div>";
while($info = $items->fetch(PDO::FETCH_ASSOC))
{
echo "<div name='item' id='".$info['color_base1']."' class='itemBox'><div class='showItem'><a href='items_descr.php?itemId=".$info[id_item]."'><img class='itemImage' alt='' src='images/$info[imageMid].jpg'></img></div><br />";
echo "<div class='indexItemText'><font class='similarItemsText'><a href='items_descr.php?itemId=".$info[id_item]."'>".$info[name]."</a><font class='price'> - $".$info[price]."</div></div>";
$row_count++;
if ($row_count % 2 == 0)
{
echo "<br />"; // close the row if we're on an even record
}
}
Any idea of what could be going on?
The problem is when you build the query in your JS function:
'indexMain.php?'+this.name+'=' + boxes.join("+")
This sends color[]=Brown+Grey instead of color[]=Brown&color[]=Grey. A correct (but dirty) way to this is:
'indexMain.php?'+this.name+'=' + boxes.join('&' + this.name + '=')
You could try to use jQuery.param() ( http://api.jquery.com/jQuery.param/ ) to get a nicer code.
Also, in PHP, the checkbox values are available in the array $_GET['color'] (not $_GET['color[]']).
Edit: Sorry, read too quickly.
Answer: As you expect everywhere to use strings, use color instead of color[] in your JS and PHP code.

Using jQuery to load a PHP Page in a div

I have this script:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
$('.filterMonth').change(function(){
alert('ijijiji');
$.ajax({
url: 'ajax/filterMandays.php',
//type: 'GET',
success: function(data){
//data is returned back
$('#mandayTable').html(data);
}
});
});
</script>
and this html:
<select name ="filterMonth">
<?php
$array_month = array("January","February","March","April","May","June","July","August","September","October","November","December");
foreach($array_month as $key => $month)
{
$value_month = $key+1;
echo "<option value = '$value_month'>$month</option>";
}
?>
</select>
-
<select name = "filterYear" onChange = "filter(filterMonth.value, filterYear.value)">
<?php
$curYear = date('Y');
for($i = 1990; $i<=$curYear+10; $i++)
{
if($i == $curYear)
{
echo "<option value = '$i' selected = 'selected'>$i</option>";
}
else
{
echo "<option value = '$i'>$i</option>";
}
}
?>
</select>
</td>
</tr>
</br>
</br>
<tr>
<div id="mandayTable"></div>
and this php page:
<?php
include("all.php");
$q = "SELECT md.mandays_id,md.employeenum,md.month,md.year,md.required_man_days,d.firstname,d.lastname
FROM tbl_mandays md,tbl_employee_details d
WHERE md.active = '1'
AND md.employeenum = d.employeenum
AND md.month = '10';";
$res = $db->Execute($q);
echo "<table border = 1>";
echo "<tr><th>Employee Number</th><th>First Name</th><th>Last Name</th><th>Month-Year</th><th>Required Man Days</th><th>Edit/Delete</th></tr>";
while($rows = $res->FetchRow())
//for($i=0;$i<5;$i++)
{
//iterating through // check if employee
// // if(isset($row[])) { }
$mandays_id = $rows[0];
$empnum = $rows[1];
$month_year = $rows[2] ."-" .$rows[3];
$required_man_days = $rows[4];
$firstname = $rows['month'];
$lastname = $rows[6];
//echo approvers here are not taken
//<a href=\"view_team.php?id=".$empnum."\" -> for someone to view the people beneath them (like org tree)
echo "<tr><td>".$empnum . "</td><td>".$firstname ."</td><td>".$lastname ."</td><td>" . $month_year ."</td><td>" .$required_man_days . "</td><td width = \"200\" align = \"center\"><a href = 'edit_mandays.php?mandays_id=$mandays_id');'>Edit/Delete</a></td></tr>";
}
echo "</table>";
?>
the script should basically load the php page in the div in the html once the "filterMonth" has been changed. but it doesn't work.
what seems to be the problem? :(
The selector in your jQuery is $('.filterMonth') but your select box doesn't have the filterMonth class. You need to change it to $('select[name=filterMonth]').
In order for the jQuery selector to contain your select, you need to make sure that it runs after the Select element is in the DOM (ie: lower down the HTML), or run your JavaScript once the document has finished loading, for example:
<script type='text/javascript' src='js/jquery-1.4.4.mi.js'></script>
<script type='text/javascript'>
jQuery(function() {
// do your DOM selections here, this function only runs once the document is loaded
});
</script>

javascript for onClick not executing?

ok maybe i must put all my code:
<?php
include('header_application.php');
$obj_clean->check_user();
$limit = 10;
if(!isset($_GET['page']))
$page = 1;
else
$page = $_GET['page'];
$from = (($page * $limit) - $limit);
$msg = "";
if (isset($_GET['unblock']))
{
$code = $obj_clean->unblockUser($_GET['unblock'],$_GET['code']);
if ($code == "error")
{
$msg = "Could not delete message!";
}
else
{
$msg = "You have unblocked ".$code;
}
}
//Get dynamic data required for this page from the database
$users = $obj_clean->getContacts($_SESSION['user_id'], $from, $limit);
$rows = $obj_clean->getContactsCount($_SESSION['user_id']);
include ("header.php");
?>
<div class="innerContainer">
<head>
<script type="text/JavaScript">
function yesnolist(val)
{
var e = confirm('Do you want to send a free chat request?');
if (e == true)
{
window.location.href = "http://www-rainbowcode-mobi/confirmfreechat.php";
//window.location('http://www-rainbowcode-mobi/confirmfreechat.php');
return true;
}
else
return false;
}
</script>
</head>
<span class="headings2">CONTACTS</span>
<?php if (isset($msg) && !empty($msg)) echo "<br/><font color='red'>".$msg."</font>"; ?>
<br/><br/>
<?php
if (count($users) > 0)
{
echo "<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
foreach ($users as $user)
{
//Breaks the unique code into 3 parts so that the numeric part can be a different colour
$codeLength = strlen($user['unique_code']);
$firstPartLength = $codeLength - 5;
$uniqueCode3 = substr($user['unique_code'], -2);
$uniqueCode2 = substr($user['unique_code'], -5, 3);
$uniqueCode1 = substr($user['unique_code'], 0, $firstPartLength);
echo '<tr>';
echo '<td>';
echo '<a class="charcoal_link" style="line-height: 20px;" href="'.ADDRESS.'view_profile.php?id='.$user['profile_id_contact'].'">'.$uniqueCode1.'<span class="pink_text">'.$uniqueCode2.'</span>'.$uniqueCode3.'</a>';
$requestor_id = $_SESSION['user_id'];
$profile_id = $user['profile_id_contact'];
$rel1 = $obj_clean->hasRelation($requestor_id,$profile_id);
$rel2 = $obj_clean->hasRelation($profile_id,$requestor_id);
if($rel1 && $rel2)
{
echo " ";
//echo 'Free Chat';
echo 'Free Chat';
}
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "You have no contacts yet";
}
?>
</div>
<?php include("footer.php"); ?>
hope this will help better
Free Chat
should be:
Free Chat
try this:
function yesnolist()
{
if (confirm('Do you want to send a free chat request?'))
window.location = "http://www-rainbowcode-mobi/confirmfreechat.php";
}
.
.
.
<a href="#" onClick="yesnolist()">
I'd assume changing the URLs to valid domains might help things, so try:
window.location.href = "http://www.rainbowcode.mobi/confirmfreechat.php";
window.location('http://www.rainbowcode.mobi/confirmfreechat.php');
function yesnolist()
{
var e = confirm('Do you want to send a free chat request?');
if (e == true)
{
window.location = "http://www-rainbowcode-mobi/confirmfreechat.php";
return true;
}
else
return false;
}
and
<label onClick="return yesnolist();">Free Chat</a>
You can not pass onclick event on (a href="") tag because href part redirects the page and after that the javascript redirect part is called.
Or
(a href="#" onclick="return yesnolist();")Free Chat(/a)

Categories