1

How do I get back only one row in my query search using mysqli_

I've been reading about here:
Here

where it says that I can do a query like this:

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

but it does not work for me.

this is what I have:

$connection= mysqli_connect("localhost", "root", "", "my_db");

using the same principle as the one in the page:

echo $result = $connection->query("SELECT organization FROM organizations_table WHERE status !=0 AND token=".$TOKEN)->fetch_object()->organization;

I suppose fetch_object()->organization; is the name of my table field.

Or is there a better way to do this, not that this way is working for me. I'm using procedural php with mysqli_

learningbyexample
  • 1,527
  • 2
  • 21
  • 42
  • one row is all you'll ever get from a single fetch() call. So... simply DON'T use a loop. call fetch() once, and done. And don't chain DB calls. it assumes that nothing will ever go wrong. run your query, check for failure, THEN fetch data. – Marc B Oct 13 '16 at 22:02
  • `but it does not work for me.` Could you be more specific? – Jonnix Oct 13 '16 at 22:03
  • You may want to check for an sql error with `echo mysqli_error($mysqli);` in your code. – Proger_Cbsk Oct 13 '16 at 22:03
  • i get this error `Fatal error: Call to a member function fetch_object() on boolean in` – learningbyexample Oct 13 '16 at 22:06
  • So there you go. your query failed, and since your code simply ASSUMED success, everything else broke. And note that you're NOT using "procedural mysqli". you're using OOP calls. – Marc B Oct 13 '16 at 22:08
  • @learningbyexample So in your case, your SQL is wrong. Follow Proger_Cbsk's advice and use mysqli_error to see what's wrong. – Jonnix Oct 13 '16 at 22:08
  • Well, what about NOT assigning and echoing in the same time ? `$result = ;` THEN `echo $result;` – Proger_Cbsk Oct 13 '16 at 22:12

2 Answers2

0

You can do it using mysqli_fetch_row(). It will return only one result for your query.

Jobayer
  • 1,221
  • 1
  • 14
  • 22
0

mysql::query, if successful, returns a mysqli_result object, which in turn provides method mysqli_result::fetch_object.

Return Values
Returns an object with string properties that corresponds to the fetched row or NULL if there are no more rows in resultset.

So spelled out

$result = $connection->query("...");
$row = $result->fetch_object();
$org = $row->organization;

can be shortened to

$org = $connection->query("...")->fetch_object()->organization;

if the query doesn't return false, because of some failure, and there are any rows, so fetch_object can return an object.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198