I'm setting $_SESSION['showroom'] to 'active' when a particular page in Wordpress is displayed:
if(get_the_ID()==6470||get_the_ID()==252){
$_SESSION['showroom']='active';
}
I then set 2 arrays of pages to check against. If the next page displayed is NOT in one of these arrays, $_SESSION['showroom'] gets changed to 'inactive'.
$allowed_templates = array('template-A.php',
'template-B.php',
'template-C.php',
'template-E.php',
'template-G.php');
$allowed_ids = array(6470,252);
$template_name = get_page_template_slug();
$page_id = get_the_ID();
if(in_array($template_name,$allowed_templates)==false && in_array($page_id,$allowed_ids)==false){
$_SESSION['showroom']='inactive';
}
The if statement works most of the time, but sometimes my $_SESSION['showroom'] changes to inactive EVEN though one of the arrays is returning true! After several hours of testing I am unable to locate where the problem is. Echoing out the two parts of the if statement ALWAYS gives me 2 trues or 1 true + 1 false, but never 2 falses:
if(in_array($template_name,$allowed_templates)==false){echo 'TFALSE';}
if(in_array($template_name,$allowed_templates)){echo 'TTRUE';}
if(in_array($page_id,$allowed_ids)==false){echo 'IFALSE';}
if(in_array($page_id,$allowed_ids)){echo 'ITRUE';}
What am I missing here?
Thanks in advance for any help!
EDIT: Have continued testing and found the following anomaly:
if(in_array($template_name,$allowed_templates)==false && in_array($page_id,$allowed_ids)==false){
$_SESSION['showroom']='inactive';
echo 'SET TO INACTIVE';
}
The if statement changes $_SESSION['showroom'] to 'inactive' but DOES NOT echo out 'SET TO INACTIVE'!
There's something strange going on here!
Problem solved. My code was fine. Two missing images files were causing WordPress to crash my sessions. Took 10 hours to find out but happy I found it. Thanks to everyone for their help.
You can try the following;
if(!in_array($template_name,$allowed_templates) && !in_array($page_id,$allowed_ids)){
$_SESSION['showroom']='inactive';
}
Edit: lets try and break it down further... similar to your examples
if(!in_array($template_name,$allowed_templates){
echo "not in templates,";
}
if(!in_array($page_id,$allowed_ids)){
echo "not in ids,";
}
if(!in_array($template_name,$allowed_templates) && !in_array($page_id,$allowed_ids)){
echo "not in both\n";
}
then see if we get a result with not in templates,not in ids, but no trailing not in both
The problem is pure logical. Lets look at this statement:
if (in_array($template_name,$allowed_templates)==false && in_array($page_id,$allowed_ids)==false)
Which translates to "If the template is not valid AND page is not valid"
This means that both statements needs to be fulfilled in order to mark session as inactive. What if the template is fine, but the page is not valid? That definitely should be marked as inactive as well.
By changing the statement to read "If the template is not valid OR page is not valid", we cover up the invalid cases. Because either of them counts as an invalid state, and thus, only one of them needs to be false in order for everything to be false. (the OR-statement)
So code-wise it would be
if (in_array($template_name,$allowed_templates)==false || in_array($page_id,$allowed_ids)==false)
And you are set.
As and addition. I would structure the code as you noted works. Which is more logical. That is, mark it as inactive whenever it's should be treated as inactive, in all other cases mark it as 'active'. Or vice-versa.
Related
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).
I ran into an issue that I am not able to figure out. I have a page that I want to add an image of "Verified" or "Unverified". The code I have is the following:
PHP
if($listing['priority']==0 {
$header->set('ver_status,'<img src="images/icon_unverified.png"/>');
} else {
$header->set('ver_status,'<img src="images/icon_verified.png"/>');
}
HTML
<?php echo $ver_status; ?>
For some reason when I run the page in my website, that variable comes up empty.
The database contains a listing table, and the table contains a priority field which the default value is 0. Unless a customer updates information, which automatically changes to priority field value to 1, all profiles state "unverified"
The $header is the variable assigned to the template
All priority codes at 0 should show the unverified image. All others 1-5 shold show the veriried image.
I did this in a different page and it worked fine. That code was:
if (config['language'] == 2) {
$header->set('language_flag','<img src="images/flags/Spanish.png" />');
} else {
$header->set('language_flag','<img src="images/flags/English.png" />');
}
where code 2 was Spanish and code 1 was English.
Is there something missing in my code that I am not seeing? I am not getting any error messages, just empty values.
You appear to be missing a close paren in your if statement. If that's copied and pasted directly out of your code, that could be causing issues - it should also be causing error messages, but you may have those turned off.
If it's just a typo from copying your code into SO, of course, this is unhelpful.
The variable comes up empty because there isn't one. If you want to retrieve an image through echoing a variable's value, simply type
if($listing['priority']===0){
$ver_status='<img src="images/icon_unverified.png">';
}else{
$ver_status='<img src="images/icon_verified.png">';
}
What you're doing in your code is setting an object's key, but when you're trying to get that same key, you're not referencing it correctly. echo $header->ver_status is how you should retrieve the value if you don't want to use a normal variable. I suggest reading http://php.net/manual/en/language.types.object.php
To note, you have a typo in your code as well. t('ver_status,' is an open string.
Also to note, there is no need for a slash in an tag unless you're using XML.
I currently have a list of users in my mysql database. One of the columns is "type". I am trying to display certain data if type is equal to admin. If type is equal to anything else, it should just echo an error message.
Unfortunately, I have tried multiple methods but it just does not seem to be working out for me. Can anyone help me get this to work properly?
This is what I have, but obviously I am doing something wrong....
<?php
$usertype = $_SESSION['type'];
if ($usertype == "admin" ){
?>
admin stuff only goes here
<?
}
else
{
echo "not priveleged usertype";
}
?>
EDIT:
The following code works when displaying via username, however, I need content displayed by usertype, not the username.
<?php
if($_SESSION['user']['username'] == "oneoftheadminusernames" )
{
?>
Each page has to start with
<?php
#session_start();
?>
otherwise, php does not "see" the sessions contents. So that's probably it.
The # prevents the php error: A session has already been started... by the way.
Now, every page that uses the session must have this directive at the top.
At least, in a quick example, that reproduces your error perfectly.
If you are saving each logged in users type field in $_SESSION['type'] variable than the code you are writing is correct. Or if you are storing type in another variable than you that variable to check.
i have an idea like add a field EnableFlag in the table. if enablee flag is set to 1 consider it as a admin else as a User;
Hey guys,
PHP and MySQL newguy here. Wrote this php file which display the content of a row relative to the ID stated in the URL ( eg row 3 is file.php?id=3 ), heres the source: http://pastie.org/1437017
If I goto an id to which the relative row does not exist (eg .php?id=99999999999999), what do I put to in to get it to redirect to another page or echo 'FAIL'. I though about using the if command, but couldn't figure out the syntax. I also looked around the web, but no avail.
Thanks guys
You have the following line:
$name=mysql_result($result,$id,"name");
If there is no row with the id $id, $name will be false. You could therefore do the following:
if (!$name) {
header('Location: http://yoururl.com');
die();
}
Better yet would be to modify your query to this:
$query="SELECT * FROM likes where id=$id";
and then do
if (!$num) {
header('Location: http://yoururl.com');
die();
}
where $num is the number of row returned, as set in your existing code.
Edit As noted elsewhere in this question, it is probably better to serve a 404 Not Found page with appropriate content, rather than redirecting to another page. I can just about imagine a situation where redirection is appropriate, but if your redirection page says "item not found", this is the wrong approach.
I'd redesign your query to something like
SELECT * FROM table WHERE id = $id;
where $id is the $_GET value - sanitised of course.
if that query returns any results (mysql_num_rows($result)==1)
then you know a valid record has been found. If not, the id doesn't exist, so you can throw an error/redirect.
mysql_num_rows() gives you the number of rows in your select, so if that value is 0, you know there isnt any row with that given id.
if (mysql_num_rows($result)==0){
echo "There are no rows with this id";
}else{
// Your normal code
}
I'm probably going to make myself look like a fool with my horrible scripting but here we go.
I have a form that I am collecting a bunch of checkbox info from using a binary method. ON/SET=1 !ISSET=0
Anyway, all seems to be going as planned except for the query bit. When I run the script, it runs through and throws no errors, but it's not doing what I think I am telling it tom which is updating the specified fields within the DB.
I've hard coded the desired values into the query and it DOES update the DB. Relying on the variables I believe I've established and am then calling upon in the query does NOT update the DB.
I've also tried echoing all the needed variables after the script runs and exiting right after so I can audit them... and they're all there. Here's an example.
####FEATURES RECORD UPDATE
### HERE I DECIDE TO RUN THE SCRIPT BASED ON WHETHER AN IMAGE BUTTON WAS USED
if (isset($_POST["button_x"])) {
### HERE I AM ASSIGNING 1 OR 0 TO A VAR BASED ON WHTER THE CHECKBOX WAS SET
if (isset($_POST["pool"])) $pool=1;
if (!isset($_POST["pool"])) $pool=0;
if (isset($_POST["darts"])) $darts=1;
if (!isset($_POST["darts"])) $darts=0;
if (isset($_POST["karaoke"])) $karaoke=1;
if (!isset($_POST["karaoke"])) $karaoke=0;
if (isset($_POST["trivia"])) $trivia=1;
if (!isset($_POST["trivia"])) $trivia=0;
if (isset($_POST["wii"])) $wii=1;
if (!isset($_POST["wii"])) $wii=0;
if (isset($_POST["guitarhero"])) $guitarhero=1;
if (!isset($_POST["guitarhero"])) $guitarhero=0;
if (isset($_POST["megatouch"])) $megatouch=1;
if (!isset($_POST["megatouch"])) $megatouch=0;
if (isset($_POST["arcade"])) $arcade=1;
if (!isset($_POST["arcade"])) $arcade=0;
if (isset($_POST["jukebox"])) $jukebox=1;
if (!isset($_POST["jukebox"])) $jukebox=0;
if (isset($_POST["dancefloor"])) $dancefloor=1;
if (!isset($_POST["dancefloor"])) $dancefloor=0;
### I'VE DONE LOADS OF PERMUTATIONS HERE... HARD SET THE 1/0 VARS AND LEFT THE $estab_id TO BE PICKED UP. SET THE $estab_id AND LEFT THE COLUMN DATA TO BE PICKED UP. ALL NO GOOD. IT _DOES_ WORK IF I HARD SET ALL VARS THOUGH
mysql_query("UPDATE thedatabase SET pool_table='$pool', darts='$darts', karoke='$karaoke', trivia='$trivia', wii='$wii', megatouch='$megatouch', guitar_hero='$guitarhero', arcade_games='$arcade', dancefloor='$dancefloor' WHERE establishment_id='22'");
###WEIRD THING HERE IS IF I ECHO THE VARS AT THIS POINT AND THEN EXIT(); they all show up as intended.
header("location:theadminfilething.php");
exit();
THANKS ALL!!!
I recommend you to use something like:
$fields = array('pool', 'darts', 'karaoke', 'trivia', ...);
foreach ( $fields as $field ) {
$$field = isset($_POST[$field]) ? 1 : 0;
}
instead of 20 lines of ifs.
Your columns are ENUM or int type ? If int - drop apostrophes.
Your code could really use some error checking. Make sure you have activated the displaying of errors in your script.
In your testing environment add this at the top of your main script for instance (if you haven't done something equivalent already):
error_reporting( E_ALL | E_STRICT );
ini_set( 'display_errors', 1 );
Then (although not dependant on the above) make sure you probe the result of the query with something like:
if( false === mysql_query( 'UPDATE ...etc' ) )
{
echo 'query failed with error:' . mysql_error();
}
My guess is it will fail with the error that your column name karaoke is mispelled. But there may be more errors.
Also, hsz' suggestions are spot on (though probably not the root of your problem). Makes for easier to maintain code, and significantly reduces code.
Firstly, construct the sql query string in a variable and then pass it to mysql_query(), comment out the header() line and print out the query for debugging. For example:
...
$sql="UPDATE thedatabase SET pool_table='$pool', darts='$darts', karoke='$karaoke', trivia='$trivia', wii='$wii', megatouch='$megatouch', guitar_hero='$guitarhero', arcade_games='$arcade', dancefloor='$dancefloor' WHERE establishment_id='22'";
print("$sql");
mysql_query($sql);
//header("location:theadminfilething.php");
exit();
...
Secondly, even tho you are exiting the script, its good practice to always match your braces. You are missing the end brace for the if statement at the end of your code.
The value of the $sql variable output you can see if it works by executing it 'manually' thru phpmyadmin or the command line. What happens?