Jump to content

Test a value from a PHP


Go to solution Solved by Barand,

Recommended Posts

Hi all 

I have value passed into an array using a SQL query which appears to work fine.
The value I want is passed into $usertype
However I then want to test the $usertype for the value in the array.
I know the value is in position [0] in the array but specifying this seems to make no difference anyway

The output from the code below is the screenshot

It recognises I am User Type 2 ($bob) 

However if I test $bob which according to the array is 2 and correctly output as 2.
The test always thinks bob is 1

Anyone got any help on how to test a value in an array?

Code is below 

<?php
    $User  = current_user(); 

    $sql = 'SELECT fk_usertypes_id
            FROM users
            WHERE email=:User';

    $statement = db()->prepare($sql);
    $statement->bindValue(':User', $User, PDO::PARAM_STR);
    $statement->execute();

    $usertype = $statement->fetchAll(PDO::FETCH_ASSOC);

if ($usertype) 
{
        foreach ($usertype as $bob) 
        {
        echo  '<left>' . "UserType " . $bob['fk_usertypes_id'] . '</br>';
        }

}

print_r($bob);

if ($bob=1)
{echo "Hello 1";}
else
{
    echo "Hello 2";
}

?>

<p><a href="index.php">Home</a></p>
<?php view('footer') ?>
 


 

Screenshot 2024-01-16 145225.png

Link to comment
https://forums.phpfreaks.com/topic/317632-test-a-value-from-a-php/
Share on other sites

Thanks again Barand. I was sure had tried that I actually had === in there for a while as I read that too.

Anyway just doing == has fixed the problem however when the user is 1 it now goes automatically to 2 :(

Anything to say if you are 1 echo 1 if you are 2 echo 2

Edited by GregRickshaw
6 minutes ago, ginerjm said:

Show us your new line of code then


print_r($bob);

if ($bob==1)
{echo "Hello 1";}
else
{
    echo "Hello 2";
}

 

Made the change suggested, which did work when the user was type 2 but when the user is type 1 the output is always the else statement Hello 2

Thanks I will add those to my code will come in handy with errors. Great tip

Edited by GregRickshaw

you logic makes no sense. $bob is an array. the comparison with == 1 'works' because a non-empty array is a true value that is loosely equal to 1. your goal should be to test the value in $bob['fk_usertypes_id']

also, is there more than one row of data matching the email address? if there is not, don't use the fetchAll() method and don't use a loop to loop over the data. just fetch the single row of data.

8 minutes ago, mac_gyver said:

you logic makes no sense. $bob is an array. the comparison with == 1 'works' because a non-empty array is a true value that is loosely equal to 1. your goal should be to test the value in $bob['fk_usertypes_id']

also, is there more than one row of data matching the email address? if there is not, don't use the fetchAll() method and don't use a loop to loop over the data. just fetch the single row of data.

Making no sense is correct, I am just dabbling around I'm not trying to do or be anything so apologies as I just don't really know I'm just finding my way.
I have tried testing it as you say but it always the same. I have tried not used the fetchAll() it's always the same

I only looped over the data because I was testing for more than one value but I can remove that.

I will try the things you mention and come back to you. I have also tried in_array function still always ignores it.

 

Here is another way of writing this

$User  = current_user(); // I assume this 'current_user function is something you wrote
$sql = 'SELECT fk_usertypes_id
    FROM users 
    WHERE email=:User';
$statement = db()->prepare($sql);
$parms = array('User'=>$User);
if (!$statement->execute($parms))
{
    echo "Query did not run";
    exit();
}
// You probably don't need a loop here, but here you go
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
    echo "UserType " . $row['fk_usertypes_id'] . '</br>';
}
// this code makes no sense since you are not in the loop here.
/*
if ($bob  == 1)
    echo "Hello 1";
else
    echo "Hello 2";
*/
echo "<p><a href='index.php'>Home</a></p>";
view('footer');        // I HAVE NO IDEA WHAT "view" IS SUPPOSED TO DO FOR YOU

Made some changes to your use of PDO and the way your query results are being processed.  Of course, as already mentioned, you probably only have one results row since the email should be unique (perhaps).

And I'm assuming that 'bob' is representing the sole result value, the usertype id, hence I left it out.

 

  • Like 1
32 minutes ago, ginerjm said:

Here is another way of writing this

$User  = current_user(); // I assume this 'current_user function is something you wrote
$sql = 'SELECT fk_usertypes_id
    FROM users 
    WHERE email=:User';
$statement = db()->prepare($sql);
$parms = array('User'=>$User);
if (!$statement->execute($parms))
{
    echo "Query did not run";
    exit();
}
// You probably don't need a loop here, but here you go
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
    echo "UserType " . $row['fk_usertypes_id'] . '</br>';
}
// this code makes no sense since you are not in the loop here.
/*
if ($bob  == 1)
    echo "Hello 1";
else
    echo "Hello 2";
*/
echo "<p><a href='index.php'>Home</a></p>";
view('footer');        // I HAVE NO IDEA WHAT "view" IS SUPPOSED TO DO FOR YOU

Made some changes to your use of PDO and the way your query results are being processed.  Of course, as already mentioned, you probably only have one results row since the email should be unique (perhaps).

And I'm assuming that 'bob' is representing the sole result value, the usertype id, hence I left it out.

 

Ok that works very nicely. I don't need to echo the value out really, that was just for me to see what was going on.
It works each time. Yes current_user() is a function and gets the email from the login page to know who I am dealing with.

Yes the $bob makes now sense I've removed it now, again it was just my way of finding out what was going on.
Which is why I was trying to test the value in the first place :)

How would I then achieve a test of the value? Rather than showing it on screeen.

So now I have the UserType being set correctly I wanted to do something like if UserType = 1 then do this (go to a page for instance)

if UserType = 2 then do this (go to a different page for example)

Many thanks for your time, effort and help.


 

Place your test logic inside the loop - if there is one.  You should test the # of rows returned and if it is not 1, you have a problem.  If it is only 1, then you can simply do a single fetch and use the returned value in your remaining logic.

Brilliant I got it now works a treat, onwards and upwards

Thank you again for your patience, time and effort.



 

<?php
$User  = current_user(); 
$sql = 'SELECT fk_usertypes_id
    FROM users 
    WHERE email=:User';
$statement = db()->prepare($sql);
$parms = array('User'=>$User);
if (!$statement->execute($parms))
{
    echo "Query did not run";
    exit();
}

while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
    echo "UserType " . $row['fk_usertypes_id'] . '</br>';

if ($row['fk_usertypes_id'] ==1)

{
   echo "Hello 1";}
 
 else

{
    echo "Hello 2";
}


}

?>

<p><a href="index.php">Home</a></p>
<?php view('footer') ?>

Edited by GregRickshaw

1  - Stop using multiple php tags - on and off.  When you have to echo out stuff you don't need to leave php mode unless it is a whole lot of html code.  If your script is well-organized you shouldn't need to do it ever.

2 - Be careful with your use of braces.  Personally I always place them on a line by themselves so that they are clear and the code is easily scanned.  You have an error already in this sample of your 'new' code.

3 - When posting code here be sure to open the code window using the <> icon at the top of the window so that the code sticks out in the forum like my sample did for you.

8 minutes ago, ginerjm said:

1  - Stop using multiple php tags - on and off.  When you have to echo out stuff you don't need to leave php mode unless it is a whole lot of html code.  If your script is well-organized you shouldn't need to do it ever.

2 - Be careful with your use of braces.  Personally I always place them on a line by themselves so that they are clear and the code is easily scanned.  You have an error already in this sample of your 'new' code.

3 - When posting code here be sure to open the code window using the <> icon at the top of the window so that the code sticks out in the forum like my sample did for you.

I will do thank you for the guidance. 
Thank you yes it's a bit messy I have a lot to learn particularly etiquette 
Will do, I'm trying my best to bumble along, I'm not looking to become a PHP developer when I get the POC complete I will be handing it over to the pros. 

Thanks again - take care

17 minutes ago, GregRickshaw said:

Yes current_user() is a function and gets the email from the login page to know who I am dealing with.

your login code should put the user's id (auto-increment primary index) into a uniquely named session variable, such as $_SESSION['user_id']. you would then test if that session variable is set on any page that requires a logged in user. you would query on each page request, using $_SESSION['user_id'], to get any other user data, such as the username, email, access type, ...

25 minutes ago, GregRickshaw said:

I wanted to do something like if UserType = 1 then do this (go to a page for instance)

if UserType = 2 then do this (go to a different page for example)

don't do that. once you have the user's data, just test/use it on a single page to control what content gets displayed on the page and what action the user can perform on that page.

since this query to get the access type will at most match one row of data, don't use a loop at all. just fetch/test the data. i reviewed your previous thread on this forum. you were using a single fetch() statement in it. what happended?

10 minutes ago, GregRickshaw said:

db()->

this implies your db() function creates a new database connection every time it is called. don't do that. a database connection is one of the slowest operations you can perform on a page. your application should create one database connection, then use that single connection for every database operation on the page.

17 minutes ago, GregRickshaw said:

if (!$statement->execute($parms))
{
    echo "Query did not run";
    exit();
}

don't do this. as of php8, the default setting for PDO error handling is to use exceptions for all the database statements that can fail - connection, query, exec, prepare, and execute. with exceptions, any discrete error check logic in your code won't ever get executed upon an error since execution transfers elsewhere. this is one of the great points of using exceptions. your main code will only 'see' error free execution. if execution continues past a statement that can fail, you know the statement was successful without needing conditional logic to test if it was or was not. this simplifies the code, allowing you to remove all the now unnecessary conditional logic.

the only time you should catch and handle a database exception in your code is for recoverable user error, such as when inserting/updating duplicate or out of range user data. for all other error numbers and all other query types, just let php catch and handle any database exception.

19 minutes ago, GregRickshaw said:

fetch(PDO::FETCH_ASSOC)

if you set the default fetch mode to assoc when you make the database connection, you don't need to specify it in each fetch statement, simplifying the code.

 

  • Like 1

I would add the following suggestion regarding this type of logic

if ($row['fk_usertypes_id'] ==1) {
   echo "Hello 1";
} else {
    echo "Hello 2";
}

Just because the value is not 1, you should not assume the value is 2 - even if those are the only expected values. I've seen multiple production issues where such logic was implemented and unexpected conditions caused impactful bugs. If you only expect the value to be 1 or 2, I would do the following.

if ($row['fk_usertypes_id'] == 1) {
   echo "Hello 1";
} else if (($row['fk_usertypes_id'] == 2) {
    echo "Hello 2";
} else {
    //Throw error
    echo "Unhandled error";
}

Although at this point a switch() statement might make more sense.

  • Like 1
10 minutes ago, mac_gyver said:

your login code should put the user's id (auto-increment primary index) into a uniquely named session variable, such as $_SESSION['user_id']. you would then test if that session variable is set on any page that requires a logged in user. you would query on each page request, using $_SESSION['user_id'], to get any other user data, such as the username, email, access type, ...

don't do that. once you have the user's data, just test/use it on a single page to control what content gets displayed on the page and what action the user can perform on that page.

since this query to get the access type will at most match one row of data, don't use a loop at all. just fetch/test the data. i reviewed your previous thread on this forum. you were using a single fetch() statement in it. what happended?

this implies your db() function creates a new database connection every time it is called. don't do that. a database connection is one of the slowest operations you can perform on a page. your application should create one database connection, then use that single connection for every database operation on the page.

don't do this. as of php8, the default setting for PDO error handling is to use exceptions for all the database statements that can fail - connection, query, exec, prepare, and execute. with exceptions, any discrete error check logic in your code won't ever get executed upon an error since execution transfers elsewhere. this is one of the great points of using exceptions. your main code will only 'see' error free execution. if execution continues past a statement that can fail, you know the statement was successful without needing conditional logic to test if it was or was not. this simplifies the code, allowing you to remove all the now unnecessary conditional logic.

the only time you should catch and handle a database exception in your code is for recoverable user error, such as when inserting/updating duplicate or out of range user data. for all other error numbers and all other query types, just let php catch and handle any database exception.

if you set the default fetch mode to assoc when you make the database connection, you don't need to specify it in each fetch statement, simplifying the code.

 

The login code just does that I just built it into a function to call exactly as you said.
 

function current_user() 
{
    if (is_user_logged_in()) {
        return $_SESSION['email'];
    }
    return null;
}

I went this route because I just couldn't work it out how to use the key. Ironically of course my noddy testing and coding took way longer than probably revisiting that properly.

The db function is this? Is this not good way of doing things?
 

function db(): PDO
{
    static $pdo;

    if (!$pdo) {
        $pdo = new PDO(
            sprintf("sqlsrv:server=%s;Database=%s",DB_HOST, DB_NAME),
            DB_USER,
            DB_PASSWORD,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
        );
    }
    return $pdo;
}

Thanks for all your help. Always learning, always looking for better ways. I'm a MSSQL/BI developer/data architect by day,  so all of this is new to me

  • Like 1

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.