Giter Club home page Giter Club logo

medoo's Introduction

Build Status Total Downloads Latest Stable Version License Backers on Open Collective Sponsors on Open Collective

The lightweight PHP database framework to accelerate development.

Features

  • Lightweight - Portable with only one file.

  • Easy - Easy to learn and use, with a friendly construction.

  • Powerful - Supports various common and complex SQL queries, data mapping and prevents SQL injection.

  • Compatible - Supports MySQL, MSSQL, SQLite, MariaDB, PostgreSQL, Sybase, Oracle, and more.

  • Friendly - Works well with every PHP framework, such as Laravel, Codeigniter, Yii, Slim, and frameworks that support singleton extension or composer.

  • Free - Under the MIT license, you can use it anywhere, for whatever purpose.

Requirements

  • PHP 7.3+
  • Installed PDO extension

Get Started

Install via composer

Add Medoo to the composer.json configuration file.

$ composer require catfan/medoo

And update the composer

$ composer update
// Require Composer's autoloader.
require 'vendor/autoload.php';

// Use the Medoo namespace.
use Medoo\Medoo;

// Connect to the database.
$database = new Medoo([
    'type' => 'mysql',
    'host' => 'localhost',
    'database' => 'name',
    'username' => 'your_username',
    'password' => 'your_password'
]);

$database->insert('account', [
    'user_name' => 'foo',
    'email' => '[email protected]'
]);

$data = $database->select('account', [
    'user_name',
    'email'
], [
    'user_id' => 50
]);

echo json_encode($data);

// [{
//    "user_name" : "foo",
//    "email" : "[email protected]",
// }]

Contribution Guidelines

Before starting a new pull request, please ensure compatibility with other databases and write unit tests whenever possible.

Run phpunit tests for unit testing and php-cs-fixer fix to fix code style.

Each commit should start with a tag indicating the type of change: [fix], [feature], or [update].

Please keep it simple and keep it clear.

License

Medoo is released under the MIT license.

Links

Support Our Other Product

Gear Browser - Web Browser for Geek

Gear Browser

medoo's People

Contributors

amoydavid avatar angelaon avatar catfan avatar etrappg avatar glenndavey83 avatar ifnotfr avatar indiwine avatar jackled avatar jfcherng avatar qatrix avatar r0manchak avatar shea-sollars avatar syutingsong avatar tianyiw2013 avatar utopiaio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

medoo's Issues

JOIN clause error

Hello,

when we use condition join we cant select atribute the 'ON' statement and 'WHERE' clause

Use json_encode/json_decode

Hi,

have you thought about using json_encode instead of serialize? I know, it's an easy fix if I want to use it, but having the "official" could be nice.

And is there a way to auto-unserialize data? I guess not.

How to use function in select statement in the right way ?

$news = $database->get('article', array(
    'id',
    'title',
    'DATE_FORMAT(date, "%m-%d-%Y")'
), array(
    'type' => 'news',
    'LIMIT' => '7'
));

->

SELECT "id","title","DATE_FORMAT(date, "%m-%d-%Y")" FROM "article" WHERE "type" = 'news' LIMIT 7

QAQ...

PS: Had no choice, My dirty patch:

    protected function column_quote($string)
    {
        if($string[0] == '~')
        {
            return substr($string, 1, strlen($string)-1) ;
        }
        else
        {
            return '"' . str_replace('.', '"."', $string) . '"';
        }
    }

Use this format...

$news = $database->select('article', array(
    'id',
    'title',
    '~DATE_FORMAT(date,\'%m-%d-%Y\') AS "date"'
), array(
    'type' => 'news',
    'LIMIT' => '7'
));
SELECT "id","title",DATE_FORMAT(date,'%m-%d-%Y') AS "date" FROM "article" WHERE "type" = 'news' LIMIT 7

More conditions in other condition

Hi!

I have a problem with this code:

$mysql->select("conversations", "*", array(
    "OR" => array(
        "AND" => array( "from" => 2, "to" => 1),
        "AND" => array( "to" => 2, "from" => 1)
    ), 
    "ORDER" => "sent ASC"
));

This code parse query:

SELECT * FROM "conversations" WHERE ("to" = '2' AND "from" = '1') ORDER BY "sent" ASC

There is missing first AND condition. Why? Is my code wrong or is it bug?

Thanks!

medoo::insert() issue

Hello,

Thank you for this nice framework.
My english is very bad,
Can you understand what I mean?

$config = require_once 'config.php';
require_once 'medoo.php';
$db = new medoo($config['DB']);
$query = $db->insert("sdfasdfa",array("sdf" => 1));
var_dump($db->error());

if table not exists, can not find error!

public function insert($table, $data)
{
    $keys = implode(',', array_keys($data));
    $values = array();
    foreach ($data as $key => $value)
    {
        $values[] = is_array($value) ? serialize($value) : $value;
    }
    return $this->query('INSERT INTO ' . $table . ' (' . $keys . ') VALUES (' . $this->data_implode(array_values($values), ',') . ')');
}

function lastInsertId()
{
    return $this->pdo->lastInsertId();
}

Exception for connection failure

Hi,

Currently, Medoo show a message when the connection on the DB failure.
Why not create an exception? Line 86 can be replace by :

throw new Exception($e->getMessage());

Thanks.

"ORDER BY FIELD" How?

I need query:

SELECT * FROM table WHERE row IN (1,2,3) ORDER BY FIELD (row, 1,2,3)

What solution with medoo?

Toggle Boolean values

I like to use tinyint 0 | 1 for boolean fields like active or not. This is how I would toggle the field.

UPDATE table SET field = NOT field WHERE id = ?

How would I replicate this with Medoo?

Thanks,
Stephen

Connection failed: SQLSTATE[HY000] [2002]

Database type is sqlite, and I use Win8.1.

$dbfile = APP_PATH . '/db.sqlite';

if ( ! file_exists($dbfile) ) {
    throw new Exception("Database file not exists.");
}

$db = new medoo($dbfile);

The last trace:

#0 E:\Dropbox\app\bootstrap.php(31): medoo->__construct('E:\Dropbox\a...')

No JOINS without WHERE

If I want to use the select-function with JOIN but without WHERE, it's not possible.
This is because (3rd. line in select()-function) the $where parameter is not strictly testet against null.
If the 3rd line of the select()-function is changed from:
if ($where)
to:
if ($where !== null)

it works.

MYSQL Functions

Hi (sorry for my english)

I have used salt for my user passwords. So, I should use mysql MD5 function like this:

...WHERE MD5(concat('$_POST['password']',salt))=password

How can i do this ? I think I can use the query() function but probably this cause sql injection.

Can you help me ?

no deserialization after select

We can insert array data without serialization, because Medoo will handle this automatically.

$database = new medoo("my_database");

$last_user_id = $database->insert("account", [
    "user_name" => "foo",
    "email" => "[email protected]",
    "age" => 25,
    "lang" => ["en", "fr", "jp", "cn"]
]);

BUT it seems that we CANNOT select the data with de-serialization!!

$datas = $database->select("account","*");

var_dump($datas);

// lang:
// string(58) "a:4:{i:0;s:2:"en";i:1;s:2:"fr";i:2;s:2:"jp";i:3;s:2:"cn";}"

a small bug when creating a medoo for sqlite

Because I need to use Medoo for both mysql and sqlte3.
I didn't want to modify database_type in medoo class.
So, I had trid to use:
$sqlitedb = new medoo([
'database_type' => 'sqlite',
'database_file' => $file,
]);
It doesn't work, because the "option" for PDO sqlite is an empty array while it expects a string in this way.
I change it to :
$sqlitedb = new medoo([
'database_type' => 'sqlite',
'database_file' => $file,
'option' => '',
]);

then, it works.

出错

mysql连接 380行 $join_key = array_keys($join); 报错: Warning: array_keys() expects parameter 1 to be array

且select时$condition数组转为str时,丢了where
var_dump($db);
public 'queryString' => string 'SELECT * FROM user WHERE id = 1 status = 1 LIMIT 1' (length=56)

medoo::where_clause() issue

Hello,

Thank you for this nice framework.

I hit a problem using the where conditions :
I need to delete records older than 12hrs, using mysql. The table "my_table" has one field called "created" type : datetime.

// purge older records
$date12h = new DateTime();
$date12h->sub(new DateInterval('PT12H'));
$term = $date12h->format('Y-m-d H:i:s');
// Assume $database is a medoo object (bonded the the DB)
$database->delete('my_table', array('created[<]'=>$term));

When I use this, medoo::last_query() returns "DELETE FROM my_table WHERE"
Because the method medoo::data_implode() detect the $match[3] as an '<' then tests if the value is numeric. But mysql accepts also '<' and '>' to compare strings.

For my own use I patch the code as ...

if (is_numeric($value))
{
    $wheres[] = $match[1] . ' ' . $match[3] . ' ' . $value;
} 
else // my uglly patch...
{
    $wheres[] = $match[1] . ' ' . $match[3] . ' ' . $this->quote($value);
}

... But I'm not sure -at all- will works on other DB engines.

Select using Like

First of all congratulation on medoo!
I got stuck in the following query
SELECT * FROM table WHERE ( name LIKE 'foo%' AND address LIKE '%bar' )
how to do it with Medoo
Excuse me if this is already answered or addressed some pace else, I just couldn't find it
thank you in advance
Best Regards

bug (?) in function get

As I understand the get-function (0.8.5/0.8.6):

  • if no where-clause is given no "limit 1" is set
  • if a where-clause is given "limit 1" is set

But return is always only one row ($data[0])

So functional it is not necessary to use limit 1.
I think people will use get-function only if they use a where-clause on primary key or unique index (e.g. user-id) so my wish is to delete the

if (is_array($where))

{
$where['LIMIT'] = 1;
}

medoo::where_clause() issue

Hello,

Thank you for this nice framework.

I hit a problem using the where conditions :

 $where = array(
    "OR" => array(
        "test" => "123",
        "test" => "456",
    )
 );
 $str = $db->where_clause($where);
 echo $str;
 //WHERE test = '456'

I want to get like this:

 //WHERE test = '123' OR test = '456'

#BIG BUG

In case mssql doesn't support use

`

to wrap columns and tables like

select `id` from `user`

so this framework will never support mssql,
if you don't have some change

why

There are lines 32 and lines 53 exactly the same, why not remove one?

Table aliases on JOIN clauses

Hello,

There seem to be no way to add table aliases when joining them, that's not a big deal when it comes to different tables, but when using the same table, an alias is mandatory.

Regards.

Don't work with cyrillic symbols

I tried to get some cyrillic data from MySQL test database, but instead of my data I got "??? ????? ??????". I tried on two different servers(MacOS and Debian) - the situation is the same.

mysql keywords that are not in quotes

I only tried with mysql.

If the column name of one table is mysql keyword, like "desc", "key" and so on. The insert function doesn't work.

For example:
$database->insert("my_table", [ 'title'=>"test", "desc" => "some text",]);

Then the SQL in background is:
INSERT INTO my_table (title,desc) VALUES ('test', 'some text')

because the key words are not in quotes with "`" character.

php_pdo_xxx

I am new to database programming and am attracted to Medoo because it looks quite simple and accessible. However, this line in the "new medoo" doc at http://medoo.in/api/new has me stumped: "Make sure php_pdo_xxx (xxx = the database name you want to use) extension is enabled and installed on php.ini."

I am guessing that the fact that I don't know what this means is the reason I am getting a "Fatal error: Uncaught exception 'Exception' with message 'SQLSTATE[HY000] [2002] No such file or directory'" error when trying to use Medoo.

Does anyone want to take pity on a newbie and help me understand? I am using a shared hosting site (DreamHost in this case) and need to know how to make sure the "extension is enabled and installed on php.ini." Can I use phprc or .user.ini to set this somehow?

Bool & Integer Value Errors

When writing to a MySQL database field that uses a BOOL value an error is thrown because Medoo is wrapping the Bool value in quotes. I also had errors trying to write Integer values.

This was my quick fix,

At line 524 I added
case 'boolean': $values[] = $value; break;

and replaced
case 'integer'
with
case 'integer': $values[] = $value; break;

and then again at line 575 I added
case 'boolean': $fields[] = $key . ' = ' . $value; break;

and replaced
case 'integer'
with
case 'integer': $fields[] = $key . ' = ' . $value; break;

There may be other places like the "Where" statements that this may be needed but this resolved my immediate problems.

[!empty]Instead of[isset]

function where_clause($where)
if (isset($where['AND']))

suggest:
if (!empty($where['AND']))

My code:

select("table", '*',array('AND'=>$where));

NO 'AND's in where statement

where array:
"PI_ID" => "125",
"PROGRAM_CODE" => "WS"

query statement output is:
WHERE PI_ID = '125' PROGRAM_CODE = 'WS'

no AND between 'PI_ID' and PROGRAM_CODE

could this be a bug?

function data_implode ADD LIKE

SELECT * FROM "mo_uv" WHERE "uid" = '1' AND "number" LIKE '%38%' LIMIT 0,20

$where = array();
$id && $where['uid'] = $id;
if ( $type == 2 ) {
$where['hasPaid'] = '1';
}else if ( $type == 1 ) {
$where['hasPaid'] = '0';
}
if ( $number ) {
$where['number[LIKE]'] = $number;
}
$list = db()->select("table", '*',array('AND'=>$where,'LIMIT'=>array(0,20)));


preg_match('/([\w.]+)([(>|>=|<|<=|!|<>|LIKE)])?/i', $key, $match);

} else if ( $match[3] == 'LIKE' ) {
$wheres[] = $this->column_quote($match[1]) . ' LIKE ' . $this->quote('%' . $value . '%');

More then one condition in Select method does not work

Hi.
I noticed there is a problem when using more then one condition for the select method.
Here is a basic example:

$user =  $database->select("users","*", ["users.username"=>$_POST["username"], "users.password"=>$_POST["password"]]);

And doing

echo $database->last_query();

Outputs

SELECT * FROM "users" WHERE "users"."username" = 'user' "users"."password" = 'password'

You see, clearly the bug is that the word AND is missing from the query.

sqlite issue

with this

$database = new medoo([
'database_type' => 'sqlite',
'database_file' => 'nwys.sqlite',
'option' => ''
]);
var_dump($database->error());

I get this
array(3) { [0]=> string(5) "00000" [1]=> int(1) [2]=> string(24) "near "SET": syntax error" } array(0) { }

any idea where the syntax error comes from ?

Thx, Gerd

Get Started

Get Started page of website:

// On PHP 5.1
var data = array("foo", "bar");

// On PHP 5.4+
var data = ["foo", "bar"];

But this is not correct PHP code:) Not even JavaScript, I don't know what is this)

Let assign ALIAS to Select Columns

Hi

If you need this query:

Select a.name, b.name from section as a left join gallery as b on(a.idsection=b.section_idsection)

In the Medoo format:

$Data = $database->select("section",
[
"[>]gallery" => ["idsection" => "section_idsection"]
],
[
"section.name",
"gallery.name",
]
]);

But you can't differentiate between NAME of Section or NAME of GALLERY. You need have an ALIAS in the query. So:

  1. Add in the LINE: 127
    protected function column_quote_as($string)
    {
            return str_replace('.', '`.`', $string);
    }
  1. Add in the LINE: 405 (original line)

if (is_array($columns)){
foreach($columns AS $Columns){
$columnsTemp =explode('[>]',$Columns);
$columnsVal = ($columnsTemp[1]!='') ? '' . $columnsTemp[0] . ' AS '' . $columnsTemp[1] . ''':'' .$columnsTemp[0] . '';
$ColumnsEnd[] = $columnsVal;
}
}else{
$ColumnsEnd[]='' .$columns . '';
}

  1. Change the LINE: 408 (original line)
                is_array($ColumnsEnd) ? $this->column_quote_as( implode(', ', $ColumnsEnd) ) :

And now, the new format to take the query is:

$Data = $database->select("section",
[
"[>]gallery" => ["idsection" => "section_idsection"]
],
[
"section.name",
"gallery.name[>]NameGallery",
]
]);

WHERE column1 LIKE a AND column2 = b (in the same sentence)

My problem is simple.
I wan't a WHERE clause with a LIKE condition and an EQUAL condition.
Is there a way or am I doing something wrong?

where clause:
$where=array("AND"=>array("user_id"=>$_SESSION['user_id'],"LIKE"=>array("name"=>"a")));

getting last query:
SELECT * FROM table WHERE user_id = '1' AND LIKE IN ('a')

Medoo and error managment

Hi

first of all, thank you fort the good work! I really like using Medoo, this is so easy!

However, i have to say that i don t really understand how it work when there is an error, for exemple, if i do a select request for a table that doesen t exist, how can i get the error specificly and not the array with var_dump($Db->error());

I'm sorry but i really don t understand?

no output

I try to use your class in my project but I don't get any output :(

i try this code:

$database = new medoo("authme");
$datas = $database->select("authme", "*");

print_r($datas);

after

$query = $this->query('SELECT ' . $this->column_push($columns) . ' FROM ' . $table . $this->where_clause($where));

I don't get any output? any solution?

Condition with date

Hi,

I had a problem using the where condition :

$nb = $db->sum('vie', 'nb', [
            'AND' => [
                'id' => $id,
                'date[<=]' => date('Y-m-d')]
  ]);

The last condition isn't considered. last_query give :

SELECT SUM(nb) FROM vie WHERE account = '1'

Sorry for my bad english . Thanks.

Database not exist

Hello. How can I verify if database already exists? And if it not exist create one.

doc wish

hello, I know you already have really good document for medoo at http://medoo.in/doc
and I wish u could use github-pages to refactor it.
My problem is I can't see your domain in China.
If you don't have free time enough, I think I can help u~~
waiting ur answer.

Let multiple condition in JOIN relation

If you need:

Select TABLEA.name, TABLEB.file from TABLEA LEFT JOIN TABLEB ON(TABLEA.idT = TABLEB.id AND TABLEB.status=1)

You need change from line 387 to 389:

                        $TotalRel = count($relation);
                        if ($TotalRel>1){   
                            $relation_temp[] = $table . '.`' . key($relation) . '` = `' . $match[3] . '`.`' . current($relation) . '`';

                            foreach($relation['AND'] as $sub_relation => $relation_detail){                                 
                                $relation_temp[] = '`' . $match[3] . '`.`' . $sub_relation . '` = \'' . $relation_detail . '\'';
                            }                               

                            $relation = 'ON (';
                            $relation .= implode(' AND ', $relation_temp);
                            $relation .= ')';
                        }else{
                            $relation = 'ON ' . $table . '.`' . key($relation) . '` = `' . $match[3] . '`.`' . current($relation) . '`';
                        }

And Construct the Query like:

$Data = $database->select("TABLEA",
[
"[>]TABLEB" => [
"idT" => "id",
"AND" => [
"status" => 1
]
]....

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.