/ mysqli

Get a Single Value from MySQL Database in One Line of PHP

It always bothered me that it takes 17 steps to do a MySQL query (ok, that's slightly exaggerated), even when you only need the value of one field of one row. This may be common knowledge, but I didn't realize you could chain functions in PHP. I'm not sure why I never thought of doing that before (I've chained function tons of times in other languages), but by fetching an object instead of an associative array as I usually do, it's simple to grab a single value from a MySQL database. Using MySQLi, and assuming that $mysqli is the database object, here's the code to get the value of name from the table contacts where the ID is 5 in a single line:

$name = $mysqli->query("SELECT name FROM contacts WHERE id = 5")->fetch_object()->name;  

And that's it! Pretty simple, eh? It's worth noting that if the query fails (i.e. malformed SQL), $mysql->query() returns a boolean with the value false, so you'll get an error such as:

Fatal error: Call to a member function fetch_object() on a non-object in /Users/cameron/Sites/index.php on line 51