I am doing a tictactoe on php for homework, and I am stuck on the logic that changes from player to player, as it always put a X on the cell and never changes to O whenever the submit button is hit. My question is about how to make it work.
What I have so far for this is:
$position = filter_input(INPUT_GET, 'Position');
$player = "C_$position";
//Problem
if(!isset($_SESSION[$player])){ //Also tried the function empty before using !isset
$_SESSION[$player]="X";
}
if($_SESSION[$player]=="X"){
$_SESSION[$player]="O";
}
if($_SESSION[$player]=="O"){
$_SESSION[$player]="X";
}
//END PROBLEM
I've been looking for answers and I found this Initialize the variable only once in php however it doesn't work as I applied it to my php code. If anyone got a solution I would totally appreciate it.
Use an else rather than another if because with the second if you revert to the original value. Currently you run into a TRUE conditional chain, every conditional is met so you end up with the last conditional's value. A rough demo of your code can be seen here, https://3v4l.org/Lv7CK.
This should correct your logic.
$position = filter_input(INPUT_GET, 'Position');
$player = "C_$position";
if(empty($_SESSION[$player]) || $_SESSION[$player]=="O"){
$_SESSION[$player]="X";
} else {
$_SESSION[$player]="O";
}
This should set the player to X if the session isn't set or if the current player is O, otherwise it sets the player to O (this assumes there are only two values for $player if there are multiples use an elseif, or possibly a switch).
Let me first say I've spent a day reading three google pages of articles on this subject, as well as studied this page here.
Ok, here's my dilemma. I have two functions. Both called upon via AJAX. This first one assigns a value to the variable and the second one uses that variable. Both functions are triggered by two separate buttons and need to stay that way. The AJAX and the firing off of the functions work fine, but the variable isn't passed. Here is my code:
if( $_REQUEST["subjectLine"] ) //initiate first function
{
$CID = wpCreateChimpCampaign();
echo $CID; //this works
}
if( $_REQUEST["testEmails"] ) //initiate second function
{
echo $CID; //does not return anything but should contain "apple"
wpSendChimpTest($CID);
}
function wpCreateChimpCampaign () //first function
{
$CID = "apple";
return $CID;
}
function wpSendChimpTest ($CID) //second function
{
echo $CID; //does not return anything but should contain "apple"
}
I'm open to using a class but I haven't had much luck there either. I was hoping to solve this issue without using classes. Thanks for the help in advance!
If you are making 2 separate calls to this file, it may be helpful for you to visualise this as being 2 functions in 2 totally separate files. Although they exist in the same PHP file, because they used called in different calls, they don't retain the value of the variable $CID. Once the file has run, the variable is destroyed and when you call the file again, the value is null again.
So you need to store that variable between calls. You can either store it in a database or store it in a session variable.
So call session_start(); at the beginning of the file, then rather than use $CID, just use $_SESSION['CID'];
I'm not sure where the hold up is. The code you have will work:
$CID = wpCreateChimpCampaign(); // returns 'apple'
wpSendChimpTest($CID); // echos 'apple'
The code looks fine, but are you certain that all requirements are being met so both functions execute?
In other words are you supplying values for both $_REQUEST["subjectLine"] and $_REQUEST["testEmails"]?
so. i've been trying to update the password. randomly generated. but. if i refresh the database, nothing happens. what's wrong with my code?
this is my controller:
function create_password()
{
$this->load->model('members_model');
$newRow = array(
'name' => $this->input->post($a);
'value' =>
);
$this->membership_model->passchange($newRow);
}
this is my model:
function passchange()
{
$this->db->select();
$this->db->from('membership');
$this->db->where('security_answer',$this->session->userdata('security_answer'));
$q=$this->db->get();
if($q->num_rows() > 0) {
$data = array();
foreach($q->result() as $row) {
$data['result']=$row;
$this->db->where('email_address', $this->session->userdata('email_address'));
$this->db->update('membership', 'password');
}
return $data;
}
}
and this is my view:
<?php echo form_open('login/create_password')?>
<?php $this->load->view('includes/header');
$CI =& get_instance();
$CI->load->model('membership_model');
$result = $CI->membership_model->passchange();
foreach($result as $row) {
}
?>
Your Email Address is: <?php echo $row->email_address;?> <br/>
<?php
$a = random_string('alnum', 6);
?>
Your password is: <?php echo $a; "<br/>"?>
<p align="right"><?php echo anchor('login/signin', 'Back to Login Page'); ?></p>
the password in my database is blank. it is not updating. please help. thank you in advance! :)
Marishka you really really need to watch those tutorials I gave you before continuing this process. You're going to get to a point where your application is so badly messed up it will be nearly impossible to fix.
Almost everything you're doing there shows bad practices, not the least of which is stop loading the CI instances and getting data from the model in the view.
Here are the problems with your code as it stands.
You're creating an array of $newRow using a post value you're not getting because you aren't posting anything. Creating a variable in a view does not automatically post it back, to post data to a controller it needs to be in a form and that form needs to have an action to call the controller function.
$a isn't going to equal anything because random_string isn't a php function that I know of, it looks like something you just pulled out of the middle of a tutorial without reading how it was created, so $a is going to be null, even if it were posted back to the controller it would still have no value to insert into the database.
In your model that you're passing the $newRow to you're never actually getting the $newRow into the function.
This has nothing to do with it not working but you're basing which record to update on the security answer? The possibility of numerous users having the same answer makes this a horrendous idea.
As was previously said the second parameter in active records update function should be an array. So to understand what that function is doing it breaks down like this.
$this->db->update ($tableToUpdate, $arrayOfValuesToUpdate);
The array of values are key pairs so for password you'd have an array like the following:
$arrayOfValuesToUpdate = array(
'nameOfPasswordFieldInYourDB' => 'value you want to set the password to'
);
I really get the feeling you're trying to learn CI from various examples and tutorials and you really do need to just stop and look at the nettuts tutorials I linked you before from step one. Your practices are terrible and your understanding of what you're actually doing is low enough that you're just copying and pasting and not getting what it is that's supposed to actually be happening. The Nettuts tutorials will give you that base understanding you need to do these things properly.
The error lies here
$this->db->update('membership', 'password');
This method gets array as second parameter
$data['password'] = $newpassword;
$this->db->update('membership', $data);
Also use this method
echo $this->db->last_query();
to see what query has been run recently. And dont forget to use where instruction with update instruction. Read the userguide again it is very helpful
https://www.codeigniter.com/userguide2/database/active_record.html
I hope these lines would explain the question:
//in javascript
function foo(sessionName){
var u = "test.php?q="+sessionName+"&r="+parseInt(Math.random()*9999999);
xmlHttpObj.open("get", u, true);
xmlHttpObj.send();
}
//in php
$q = $_GET['q'];
unset($_SESSION[$q]);
Like you see, I don't want any value returned, I just want to unset the specific session.
You don't ever have to return a value, if you access and run the script it will do it's job. The problem will be that you will have no way of knowing if it succeeded, so it's best to return a success/failure value in general. However, since unset() doesn't actually return a value there is no need in this case.
Yes, this works. I suppose your problem is a typo in the variable name?
var u = "test.php?q="+sessionName+"&r="+parseInt(Math.random()*9999999);
^
$n = $_GET['n'];
^
It is probably better to still return a value indicating wether it worked or not. Even though this code should work just fine.
Adding this to the end of your script will give you an indicator wether it worked or not.
if (isset($_SESSION[$n])) {
echo 'success';
}
else {
echo 'fail';
}
I have a strange problem with my cake (cake_1.2.0.7296-rc2).
My start()-action runs twice, under certain circumstances, even though only one request is made.
The triggers seem to be :
- loading an object like: $this->Questionnaire->read(null, $questionnaire_id);
- accessing $this-data
If I disable the call to loadAvertisement() from the start()-action, this does not happen.
If I disable the two calls inside loadAdvertisement():
$questionnaire = $this->Questionnaire->read(null, $questionnaire_id);
$question = $this->Questionnaire->Question->read(null, $question_id);
... then it doesn't happen either.
Why?
See my code below, the Controller is "questionnaires_controller".
function checkValidQuestionnaire($id)
{
$this->layout = 'questionnaire_frontend_layout';
if (!$id)
{
$id = $this->Session->read('Questionnaire.id');
}
if ($id)
{
$this->data = $this->Questionnaire->read(null, $id);
//echo "from ".$questionnaire['Questionnaire']['validFrom']." ".date("y.m.d");
//echo " - to ".$questionnaire['Questionnaire']['validTo']." ".date("y.m.d");
if ($this->data['Questionnaire']['isPublished'] != 1
//|| $this->data['Questionnaire']['validTo'] < date("y.m.d")
//|| $this->data['Questionnaire']['validTo'] < date("y.m.d")
)
{
$id = 0;
$this->flash(__('Ungültiges Quiz. Weiter zum Archiv...', true), array('action'=>'archive'));
}
}
else
{
$this->flash(__('Invalid Questionnaire', true), array('action'=>'intro'));
}
return $id;
}
function start($id = null) {
$this->log("start");
$id = $this->checkValidQuestionnaire($id);
//$questionnaire = $this->Questionnaire->read(null, $id);
$this->set('questionnaire', $this->data);
// reset flow-controlling session vars
$this->Session->write('Questionnaire',array('id' => $id));
$this->Session->write('Questionnaire'.$id.'currQuestion', null);
$this->Session->write('Questionnaire'.$id.'lastAnsweredQuestion', null);
$this->Session->write('Questionnaire'.$id.'correctAnswersNum', null);
$this->loadAdvertisement($id, 0);
$this->Session->write('Questionnaire'.$id.'previewMode', $this->params['named']['preview_mode']);
if (!$this->Session->read('Questionnaire'.$id.'previewMode'))
{
$questionnaire['Questionnaire']['participiantStartCount']++;
$this->Questionnaire->save($questionnaire);
}
}
function loadAdvertisement($questionnaire_id, $question_id)
{
//$questionnaire = array();
$questionnaire = $this->Questionnaire->read(null, $questionnaire_id);
//$question = array();
$question = $this->Questionnaire->Question->read(null, $question_id);
if (isset($question['Question']['advertisement_id']) && $question['Question']['advertisement_id'] > 0)
{
$this->set('advertisement', $this->Questionnaire->Question->Advertisement->read(null, $question['Question']['advertisement_id']));
}
else if (isset($questionnaire['Questionnaire']['advertisement_id']) && $questionnaire['Questionnaire']['advertisement_id'] > 0)
{
$this->set('advertisement', $this->Questionnaire->Question->Advertisement->read(null, $questionnaire['Questionnaire']['advertisement_id']));
}
}
I really don't understand this... it don't think it's meant to be this way.
Any help would be greatly appreciated! :)
Regards,
Stu
Check your layout for non-existent links, for example a misconfigured link to favicon.ico will cause the controller action to be triggered for a second time. Make sure favicon.ico points towards the webroot rather than the local directory, or else requests will be generated for /controller/action/favicon.ico rather than /favicon.ico - and thus trigger your action.
This can also happen with images, stylesheets and javascript includes.
To counter check the $id is an int, then check to ensure $id exists as a primary key in the database before progressing on to any functionality.
For me it was a JS issue.
Take care of wrap function with jQuery that re-execute JS in wrapped content!
You might want to try and find out where it comes from using the debug_print_backtrace() function. (http://nl.php.net/manual/en/function.debug-print-backtrace.php
Had the same problem, with a certain action randomly running 2-3 times. I tracked down two causes:
Firefox add-on Yslow was set to load automatically from it's Preferences, causing pages to reload when using F5 (not when loading the page from the browser's address bar and pressing Enter).
I had a faulty css style declaration within the options of a $html->link(); in some cases it would end up as background-image: url('');, which caused a rerun also. Setting the style for the link to background-image: none; when no image was available fixed things for me.
Hope this helps. I know this is quite an old post, but as it comes up pretty high in Google when searching for this problem, I thought it might help others by still posting.
Good luck
Jeroen den Haan
I had a problem like this last week.
Two possible reasons
Faulty routes (DO check your routes configuration)
Faulty AppController. I add loads of stuff into AppController, especially to beforeFilter() and beforeRender() so you might want to check those out also.
One more thing, are where are you setting the Questioneer.id in your Session? Perhaps that's the problem?
Yes, it occurs when there is a broken link in the web page. Each browser deals with it variously (Firefox calls it 2x). I tested it, there is no difference in CakePHP v1.3 and v2.2.1. To find out who the culprit is, add this line to the code, and then open the second generated file in you www folder:
file_put_contents("log-" . date("Hms") . ".txt", $this->params['pass'] ); // CakePHP v1.3
file_put_contents("log-" . date("Hms") . ".txt", $this->request['pass'] ); //CakePHP v2.2.1
PS: First I blame jQuery for it. But in the end it was forgotten image for AJAX loading in 3rd part script.
I had the same problem in chrome, I disabled my 'HTML Validator' add on. Which was loading the page twice
I was having a similar issue, the problem seemed to be isolated to case-insensitivity on the endpoint.
ie:
http://server/Questionnaires/loadAvertisement -vs-
http://server/questionnaires/loadavertisement
When calling the proper-cased endpoint, the method ran once -whereas the lower-cased ran twice. The problem was occurring sporadically -happening on one controller, but not on another (essentially the same logic, no additional components etc.). I couldn't confirm, but believe the fault to be of the browser -not the CakePHP itself.
My workaround was assuring that every endpoint link was proper-cased. To go even further, I added common case-variants to the Route's configuration:
app/config/routes.php
<?php
// other routes..
$instructions = ['controller'=>'Questionnaires','action'=>'loadAvertisement'];
Router::connect('/questionnaires/loadavertisement', $instructions);
Router::connect('/QUESTIONNARIES/LOADADVERTISEMENT', $instructions);
// ..etc
If you miss <something>, for example a View, Cake will trigger a missing <something> error and it will try to render its Error View. Therefore, AppController will be called twice. If you resolve the missing issue, AppController is called once.