0

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?

  • Have you tried condensing them yourself? – Jimbo Jun 24 '13 at 10:56
  • You cloud simply use `mysqli_query` etc. (not beautiful but wokring). Maybe (not tested) you could use `$db->query("...")->fetch_assoc();` – Le_Morri Jun 24 '13 at 10:57
  • @Jimbo yes, I had tried myself, but after a few variations that didn't work I thought I'd ask people who may have done it before. I've only started looking into mysqli today. – AndrewDFrazier Jun 24 '13 at 11:00
  • Not sure why this was closed as "not constructive". Seems a valid question to me. Voted to reopen. – MrCode Jun 24 '13 at 11:24

3 Answers3

1

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.

Community
  • 1
  • 1
bcmcfc
  • 25,966
  • 29
  • 109
  • 181
1

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.

MrCode
  • 63,975
  • 10
  • 90
  • 112
  • Thanks, chaining was what I was looking for, as also mentioned by @Le_Morri. As I said, I use it when I know that there is only one record to be returned. – AndrewDFrazier Jun 25 '13 at 10:24
-1

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.
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345