JeanneD4RK
JeanneD4RK

Reputation: 333

Convert mysqli result to string directly

I'm trying unsuccessfully to convert a single result query to string without having to write 3 lines and assign twice the same variable.
It works but I find it dirty.

Let me explain :

$request = $db->query("SELECT service_label FROM services WHERE id='".$infos['service']."'");  
$service = $request->fetch_assoc();
$service = $service['service_label'];

service.id is unique so it will always return only 1 result.
Constraints are made so $infos['service'] will ALWAYS be in the services table, therefore the query cannot fail.

I would like to end up with sort of :

$service = toString($db->query("SELECT service_label FROM services WHERE id='".$infos['service']."'"));  

Is this possible ? Thanks

Upvotes: 4

Views: 17892

Answers (2)

Hazem Mohamed
Hazem Mohamed

Reputation: 564

Try this:

    $service = $db->query("SELECT service_label FROM services WHERE id='".$infos['service']."'")->fetch_object()->service_label

Upvotes: 2

sectus
sectus

Reputation: 15454

Something like this?

$request = current($db->query("SELECT service_label FROM services WHERE id='".$infos['service']."'")->fetch_assoc());

Upvotes: 3

Related Questions