Paul Ruocco Paul Ruocco - 1 month ago 5
PHP Question

Select everything with a statement, then echo specific rows

I have a select statement that grabs a full table from a database.

if ($select = $db -> prepare("SELECT service_id, service_name, service_cost FROM services"))
{
$select -> execute();
$select -> bind_result($service_id, $service_name, $service_cost);
$select -> fetch();
$select -> close();
}


(I know I can use
query
instead of
prepare
in this example.)

Outputs

service_id | service_name | service_cost
1 Artwork 80.00
2 Printing 60.00
3 Binding 20.00
4 Finishing 30.00


So now that I have all of the data from the services table at my disposal, I want to be able to echo certain things in certain places. Let's say I want to echo the service with the ID of 2 which is Printing somewhere on my page and maybe the cost of Printing further down my page. Is there a way of doing this without having to write two new statements with
WHERE id=?
just to get those?

Something like
echo $service_name(2)
where 2 is the ID?

Does something similar to this exist?

What is the best practice to accomplish what I am trying to do?

Answer

A solution is this:

if ($select = $db -> prepare("SELECT service_id, service_name, service_cost FROM services"))
{
    $select -> execute();
    $select -> bind_result($service_id, $service_name, $service_cost);
    $select -> fetch();
    while ($stmt->fetch()) {
        if($service_id==2)       
        {
             printf("%s %s\n", $service_name, $service_cost);
        }
    }
    $select -> close();
}

but maybe you want to make it like this (Assuming id is unique):

function print_query_variable($id, $variable_name)
{
if ($select = $db -> prepare("SELECT service_id, service_name, service_cost FROM services WHERE service_id=$id"))
{
    $select->execute();
    $select->bind_result($service_id, $service_name, $service_cost);
    $select->fetch();
    $select->fetch();
    $select->close();
    return $$variable_name;
}

}
Comments