Skip to content

PreparedQuery

sweiguny edited this page Aug 26, 2014 · 2 revisions

A PreparedQuery gives you the opportunity to retrieve data from the database. But not only that, you can also manipulate data. The PreaparedQuery uses SQL.

$query = new TypedQuery("SELECT * FROM `role` WHERE id = ?");

The code above instantiates a TypedQuery object and passes the query-string to the constructor. On calling the constructor the query is actually prepared! Also the kind of query is analyzed (select, update, delete or insert).

The ? indicates, that there is currently no value, but the value will be passed later - on execution.

A TypedQuery provides two public methods:

  • getSingleResult(array $values)
  • getResultList(array $values)

The behavior of both methods depends on the kind of query. On calling one of these methods the query is actually executed on the database with the values passed to the method. The sequence of the values inside the array has to correspond to the sequence of ? within the query string.


getSingleResult()

If the PreparedQuery is a kind of select and its execution resulted in more than one row, this method will return the first row as a POPO. If the execution resulted in just one row, then this one row is returned as POPO as well.

There is a difference when the result set of the execution has just one column. Then the method returns the value of the single column. Here counts the same rule: If there are more than one rows, the first one will be returned.

Examples:

$query = new PreparedQuery("SELECT * FROM `role` WHERE id = ? and name = ?");
$query->getSingleResult(array(1, "admin"));

Returns:
stdClass Object
(
    [id] => 1
    [name] => admin
)
$query = new PreparedQuery("UPDATE `role` SET name = ? WHERE id = ?");
$role = $query->getSingleResult(array("hugo boss", 1));

Returns:
1

getResultList()

This method mostly returns an array with POPO's. But on insert, update and delete statements, the behavior is similar to getSingleResult().


See also: PreparedTypedQuery

Clone this wiki locally