简体   繁体   中英

Defining a variable inside isset function

I'm trying to save lines by trying to define a variable in isset() . Currently the only way I could make this work is this:

$setpass_accinfo = $dbconn->query("SELECT id,name,password FROM users WHERE id=" . $dbconn->real_escape_string(_GET('id')));
$setpass_accinfo_row = isset($setpass_accinfo->num_rows) ? $setpass_accinfo->fetch_assoc() : false;

So, I'm trying to combine those two lines into one, if you know what I mean. Something like this for example:

$setpass_accinfo = isset(($setpass_accinfo = $dbconn->query("SELECT id,name,password FROM users WHERE id=" . $dbconn->real_escape_string(_GET('id'))))->num_rows) ? $setpass_accinfo->fetch_assoc() : false;

The issue is that it gives me an error about using $setpass_accinfo and I don't know how to fix it or if it's even possible. Any thoughts?

This can get a little messy at times but:

$setpass_accinfo_row = !empty($setpass_accinfo = $dbconn->query("SELECT id,name,password FROM users WHERE id=" . $dbconn->real_escape_string(_GET('id')))) ? $setpass_accinfo->fetch_assoc() : false;

Connot use isset() on the result of an expression
When you use single equal in an if statement, the $variable is assigned the value of the right side of the equal, then the variable is evaluated in the empty() , in this case. And precedence dictates the it is defined before the ternary operation is reached.

You can use this:

$setpass_accinfo_row = $dbconn->query("SELECT ...")->fetch_assoc() ?: false;
  • $dbconn->query() returns mysqli result
  • $dbconn->query()->fetch_assoc() returns:
    • An associative array that corresponds to the fetched row
    • NULL if no row was found
  • The ?: is the shorter form of ternary operator which, in this case, returns the array or false

Note that it does not check if the query executed successfully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM