Skip to content

Commit

Permalink
Add Database::select method
Browse files Browse the repository at this point in the history
  • Loading branch information
Nofriandi Ramenta committed Aug 5, 2014
1 parent 496a2e4 commit 10d1155
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,36 @@ $name = $result->last('name');

## CRUD helpers

### Select

Selects rows from a table according to a where clause.

Parameters:
- `$table`: The table name.
- `$where`: Where-clause; can contain placeholders.
- `$args`: Array of key-value bindings for the where-clause.

The following:

```php
<?php
$db->select('posts', 'published = :published', array('published' => true));
```

Will execute the SQL:

```
SELECT * FROM `posts` WHERE `published` = 1;
```

The `$where` parameter can also be an array of simple key-value comparisons. The
following is equivalent to the above:

```php
<?php
$db->select('posts', array('published' => true));
```

### Insert

Inserts a row into a table. Returns `true` on success, `false` otherwise.
Expand Down
30 changes: 30 additions & 0 deletions src/Dabble/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,36 @@ public function close()
return false;
}

/**
* A quick and simple way to select all columns from a table according to a
* where clause. The where clauses are all joined with AND.
*
* @param string $table Table name
* @param string $where Where-clause; can contain placeholders
* @param array $args Array of key-value bindings for the where-clause
*
* @return Result|bool
*/
public function select($table, $where = null, array $args = array())
{
if (isset($where)) {
if (is_array($where)) {
$conditions = array();
foreach ($where as $column => $value) {
$conditions[] = is_null($value) ?
"`$column` IS NULL" : "`$column` = :$column";
$args[$column] = $value;
}
$where = implode(' AND ', $conditions);
}
$sql = "SELECT * FROM `$table` WHERE $where";
} else {
$sql = "SELECT * FROM `$table`";
}

return $this->query($sql, $args);
}

/**
* Helper method to insert a row.
*
Expand Down

0 comments on commit 10d1155

Please sign in to comment.