Version: v2.4.0
select
Retrieve data from a table.
select($table, $columns)
table [string]
The name of the table to query.
columns [array/string]
The column or columns to retrieve.
select($table, $columns, $where)
table [string]
The name of the table to query.
columns [array/string]
The column or columns to retrieve.
where [array] (optional)
The WHERE clause used to filter the result set.
select($table, $join, $columns, $where)
table [string]
The name of the table to query.
join [array]
The join definitions used to combine related tables. Omit this parameter if no joins are required.
columns [array/string]
The column or columns to retrieve.
where [array] (optional)
The WHERE clause used to filter the result set.
Return Value
[array] An array containing the retrieved rows.
You can use
* for the columns parameter to retrieve all columns. However, explicitly specifying only the required columns is recommended for better performance and readability.$data = $database->select("account", [
"user_name",
"email"
], [
"user_id[>]" => 100
]);
// Example result:
// array(
// [0] => array(
// "user_name" => "foo",
// "email" => "foo@bar.com"
// ),
// [1] => array(
// "user_name" => "cat",
// "email" => "cat@dog.com"
// )
// )
foreach ($data as $item) {
echo "User: " . $item["user_name"] . " - Email: " . $item["email"] . "<br/>";
}
// Select all columns.
$data = $database->select("account", "*");
// Select a single column.
$data = $database->select("account", "user_name");
// Example result:
// array(
// [0] => "foo",
// [1] => "cat"
// )
Fetching Rows with a Callback
By default,
select() loads the full result set into memory and returns it as an array.When retrieving a large number of rows, this can increase memory usage significantly. If you pass a callback such as
function ($data) {} as the last argument to select(), Medoo will fetch and process each row immediately instead of storing the entire result set in memory first.This approach is more memory-efficient when working with large datasets.
$database->select("account", ["name"], function ($data) {
echo $data["name"];
});
$database->select("account", [
"name"
], function ($data) {
echo $data["name"];
});
Performance Benchmark
The following example compares memory usage when fetching and outputting 1,000, 5,000, and 20,000 rows from a MySQL database. Memory usage is measured with
memory_get_usage().// Method 1
$database->select("account", ["name"], function ($data) {
echo $data["name"];
});
// Compare with:
// Method 2
$data = $database->select("account", ["name"]);
foreach ($data as $item) {
echo $item["name"];
}
| Method 1 | Method 2 | |
| 1,000 Records | 789 KB | 1.2 MB |
| 5,000 Records | 1.1 MB | 3.3 MB |
| 20,000 Records | 2.26 MB | 11.1 MB |
Table Joins
SQL JOIN clauses combine rows from multiple tables. Medoo provides a simple syntax for building joins.
- [>] ==> LEFT JOIN
- [<] ==> RIGHT JOIN
- [<>] ==> FULL JOIN
- [><] ==> INNER JOIN
$database->select("post", [
// Define the relationship between the main table and the joined table.
"[>]account" => ["author_id" => "user_id"]
], [
"post.title",
"account.city"
]);
The column
author_id in the post table is matched to the column user_id in the account table."[>]account" => ["author_id" => "user_id"]
LEFT JOIN "account" ON "post"."author_id" = "account"."user_id"
If both tables use the same column name, you can use the shorthand form.
"[>]album" => "user_id"
LEFT JOIN "album" USING ("user_id")
If multiple columns share the same names in both tables, you can pass them as an array.
"[>]photo" => ["user_id", "avatar_id"]
LEFT JOIN "photo" USING ("user_id", "avatar_id")
If you need to join the same table more than once, assign an alias to the joined table.
"[>]account (replier)" => ["replier_id" => "user_id"]
LEFT JOIN "account" AS "replier" ON "post"."replier_id" = "replier"."user_id"
You can also reference a previously joined table by prefixing the column with the table name.
"[>]account" => ["author_id" => "user_id"], "[>]album" => ["account.user_id" => "user_id"]
LEFT JOIN "account" ON "post"."author_id" = "account"."user_id" LEFT JOIN "album" ON "account"."user_id" = "album"."user_id"
Multiple JOIN Conditions
"[>]account" => [ "author_id" => "user_id", "album.user_id" => "user_id" ]
LEFT JOIN "account" ON "post"."author_id" = "account"."user_id" AND "album"."user_id" = "account"."user_id"
Additional JOIN Conditions
You can also add logical conditions to the join clause.
"[>]comment" => [ "author_id" => "user_id", "AND" => [ "rate[>]" => 50 ] ]
LEFT JOIN "comment" ON "post"."author_id" = "comment"."user_id" AND "rate" > 50
Join with a Raw Object
"[>]account" => Medoo::raw("ON <post.author_id> = <account.user_id>")
LEFT JOIN "account" ON "post"."author_id" = "account"."user_id"
Data Mapping
You can customize the structure of the returned data. The mapping key does not need to match the original column name, and nested output is supported.
$data = $database->select("post", [
"[>]account" => ["user_id"]
], [
"post.content",
"userData" => [
"account.user_id",
"account.email",
"meta" => [
"account.location",
"account.gender"
]
]
], [
"LIMIT" => [0, 2]
]);
echo json_encode($data);
[
{
"content": "Hello world!",
"userData": {
"user_id": "1",
"email": "foo@example.com",
"meta": {
"location": "New York",
"gender": "male"
}
}
},
{
"content": "Hey everyone",
"userData": {
"user_id": "2",
"email": "bar@example.com",
"meta": {
"location": "London",
"gender": "female"
}
}
}
]
Index Mapping
If you use a column name as the first key in the column definition, the result will be indexed by that column.
$data = $database->select("post", [
"user_id" => [
"nickname",
"location",
"email"
]
]);
{
"10": {
"nickname": "foo",
"location": "New York",
"email": "foo@example.com"
},
"12": {
"nickname": "bar",
"location": "New York",
"email": "bar@medoo.in"
}
}
Data Type Declarations
You can explicitly declare the output type for selected fields.
// Supported data types: [String | Bool | Int | Number | Object | JSON]
// [String] is the default type for all output values.
// [Object] represents PHP data serialized with serialize() and decoded with unserialize().
// [JSON] represents valid JSON data and will be decoded with json_decode().
$data = $database->select("post", [
"[>]account" => ["user_id"]
], [
"post.post_id",
"profile" => [
"account.age [Int]",
"account.is_locked [Bool]",
"account.userData [JSON]"
]
]);
echo json_encode($data);
[
{
"post_id": "1",
"profile": {
"age": 20,
"is_locked": true,
"userData": ["foo", "bar", "tim"]
}
},
{
"post_id": "2",
"profile": {
"age": 25,
"is_locked": false,
"userData": ["mydata1", "mydata2"]
}
}
]
// Store an object in the database, and retrieve it later.
class Foo {
var $bar = "cat";
public function __wakeup()
{
$this->bar = "dog";
}
}
$object_data = new Foo();
$database->insert("account", [
"data" => $object_data
]);
$data = $database->select("account", [
"data [Object]"
]);
echo $data[0]["data"]->bar;
// The object\'s __wakeup() method is called during unserialize().
// Therefore, the output is "dog".
Aliases
You can assign an alias to a column or table name. This is especially useful in joined queries to avoid name conflicts or make the output clearer.
$data = $database->select("account", [
"user_id",
"nickname (my_nickname)"
]);
// Example result:
// array(
// [0] => array(
// "user_id" => "1",
// "my_nickname" => "foo"
// ),
// [1] => array(
// "user_id" => "2",
// "my_nickname" => "bar"
// )
// )
$data = $database->select("post (content)", [
"[>]account (user)" => "user_id",
], [
"content.user_id (author_id)",
"user.user_id"
]);
// Example result:
// array(
// [0] => array(
// "author_id" => "1",
// "user_id" => "321"
// ),
// [1] => array(
// "author_id" => "2",
// "user_id" => "322"
// )
// )
SELECT
"content"."user_id" AS "author_id",
"user"."user_id"
FROM
"post" AS "content"
LEFT JOIN "account" AS "user" USING ("user_id")
DISTINCT
To add the
DISTINCT keyword to a selected column, prefix the column name with @.$data = $database->select("account", [
// DISTINCT will be applied to this column.
"@location",
"id",
"name",
]);
SELECT DISTINCT "location", "id", "name" FROM "account"
To count distinct values, use a raw expression.
$data = $database->select("account", [
"unique_locations" => Medoo::raw("COUNT(DISTINCT <location>)")
]);
SELECT COUNT(DISTINCT "location") AS "unique_locations" FROM "account"