是否可以嵌套mysqli命令[关闭]

Using the php mysql functions, if I have a query that I know will only return one row from the data table I nest the functions like this:

$myVariable = mysql_fetch_assoc(mysql_query("SOME QUERY"));

Using the mysqli functions I have to have to use two lines of code:

$query = $db->query("SOME QUERY");
$myVariable = $query->fetch_assoc();

Is it possible to condense the two lines into one as I do using the older mysql functions?

Yes you can do it but I wouldn't recommend it:

$myVariable = $db->query("SOME QUERY")->fetch_assoc();

It's a bad idea because you don't get the opportunity to do any error handling. For example:

$myVariable = array();

$result = $db->query("SOME QUERY");
if($result && $result->num_rows == 1)
{
    $myVariable = $result->fetch_assoc();
}

If you nest or chain the calls, you might run into unhandled fatal errors because query() will return false if there was a MySQL error.

If you're looking to tidy up your code or reduce it, you could extend the MySQLi class and add your own method to fetch a single row.

You can chain them:

$myVariable = $db->query("SOME QUERY")->fetch_assoc();

Although both that and your intial mysql_ usage are prone to errors. Neither will handle a failed query particularly nicely.

As a matter of fact, you should not have to condense the two lines into one using older mysql functions, and shouldn't do it with new ones.

When a programmer needs to condense something, they write a function. So you have to.

So, what it have to be

$myVariable = my_function("SOME QUERY");

As you can see,

  • it is shorter and more readable than all these nested/chained/entangled constructs
  • it has error handling, profiling logging and many more
  • if you were using a function already, you won't even had to rewrite your existing code.