0

I need a function for returning an array of services which each contains an id and a name. I've been looking in the mysqli documentation, but cannot verify if there exists smarter solution than this:

function getServices() {
    $services = array();

    $stmt = $this->db->prepare('SELECT id, name FROM services WHERE client_id=?');
    $stmt->bind_param("i", $this->clientId);
    $stmt->execute();
    $stmt->bind_result($id, $name);
    while ($stmt->fetch()) {
        $service = array();
        $service['id'] = $id;
        $service['name'] = $name;
        $services[] = $service;
    }
    $stmt->close();

    return $services;
}

It seems a bit cumbersome that I have to build the resulting array myself. Is there a way to let mysql build the array using the selected columns?

2
  • I don't see any reasons why cannot this code be used. Even if the mysql-built version exists (which I doubt, but I'm not sure, I always used this way), there is no need to change. Commented Feb 5, 2012 at 11:58
  • @19greg96 - OP is using mysqli, not mysql Commented Feb 5, 2012 at 12:02

2 Answers 2

2

I don't use mysqli, but from inspecting the docs, I believe this should work:

$stmt = $this->db->prepare('SELECT id, name FROM services WHERE client_id=?');
$stmt->bind_param("i", $this->clientId);
$stmt->execute();

$result   = $stmt->get_result();
$services = $result->fetch_all( MYSQLI_ASSOC );

$stmt->close();

return $services;

Thus using:
1. mysqli_stmt::get_result()
2. mysqli_result::fetch_all()

It is for PHP >= 5.3.0.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your solution. Sadly my server is running PHP 5.2 so the get_result method does not exist.
@DennisMadsen: Sorry to hear that. In that case you could perhaps extend mysqli_stmt and implement it yourself, if you think it's worth the effort. Or, indeed, use PDO, in stead of mysqli if you think it's worth the effort.
1

Switch to PDO, and you have the option of

PDOStatement::fetchAll()

1 Comment

Seconded. You can pass fetch argument $stmt->fetchAll(PDO::FETCH_ASSOC) to return an associative array. Lots of other options here: php.net/manual/en/pdostatement.fetchall.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.