1. 安装 Composer:
参考: https://www.digitalocean.com/community/tutorials/how-to-install-and-use-composer-on-ubuntu-14-04
sudo apt-get update
sudo apt-get install curl php5-cli git
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
也可以用简单的方法, 参考: https://medoo.in/api/new
下载: https://github.com/catfan/Medoo/blob/master/src/Medoo.php
然后用户 php 代码包含:
require 'Medoo.php';
即可。
2. 安装 Medoo:
参考: https://github.com/catfan/Medoo
composer require catfan/medoo
composer update
3. 测试程序:
<?php
// If you installed via composer, just use this code to require autoloader on the top of your projects.
require 'vendor/autoload.php';
// Using Medoo namespace
use Medoo\Medoo;
// Initialize
$database = new Medoo([
'database_type' => 'mysql',
'database_name' => 'name',
'server' => 'localhost',
'username' => 'your_username',
'password' => 'your_password'
]);
// Enjoy
$database->insert('account', [
'user_name' => 'foo',
'email' => 'foo@bar.com'
]);
$data = $database->select('account', [
'user_name',
'email'
], [
'user_id' => 50
]);
echo json_encode($data);
// [
// {
// "user_name" : "foo",
// "email" : "foo@bar.com",
// }
// ]
?>
离线
$database->create("account", [
"id" => [
"INT",
"NOT NULL",
"AUTO_INCREMENT",
"PRIMARY KEY"
],
"first_name" => [
"VARCHAR(30)",
"NOT NULL"
]
]);
// CREATE TABLE IF NOT EXISTS account (
// id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
// first_name VARCHAR(30) NOT NULL
// )
$database->create("account", [
"id" => [
"INT",
"NOT NULL",
"AUTO_INCREMENT"
],
"email" => [
"VARCHAR(70)",
"NOT NULL",
"UNIQUE"
],
"PRIMARY KEY (<id>)"
], [
"ENGINE" => "MyISAM",
"AUTO_INCREMENT" => 200
]);
// CREATE TABLE IF NOT EXISTS account (
// id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
// email VARCHAR(70) NOT NULL UNIQUE,
// PRIMARY KEY (`id`)
// )
// ENGINE = MyISAM,
// AUTO_INCREMENT = 200
调用确实非常方便。
离线
$data = $database->query("SELECT <email> FROM <account>")->fetchAll();
// This query will be translated to:
// SELECT "email" FROM "account"
// If you have set table prefix from initialization, the above query will be translated to:
$database = new Medoo([
....
"prefix" => "WP_"
]);
$data = $database->query("SELECT <account.email>,<account.nickname>
FROM <account>
WHERE <id> != 100
")->fetchAll();
// SELECT "WP_account"."email", "WP_account"."nickname" FROM "WP_account" WHERE "id" != 100
也支持 SQL 语句
离线