Git Product home page Git Product logo

meekrodb's Introduction

MeekroDB -- The Simple PHP MySQL Library

Learn more: http://www.meekro.com

MeekroDB is:

  • A PHP MySQL library that lets you get more done with fewer lines of code, and makes SQL injection 100% impossible.
  • Google's #1 search result for "php mysql library" since 2013, with thousands of deployments worldwide.
  • A library with a perfect security track record. No bugs relating to security or SQL injection have ever been discovered.
  • Backwards and forwards-compatible, supporting all PHP versions from PHP 5.3 all the way through the latest release of PHP 8.

Installation

When you're ready to get started, see the Quick Start Guide on our website.

Manual Setup

Include the db.class.php file into your project and set it up like this:

require_once 'db.class.php';
DB::$user = 'my_database_user';
DB::$password = 'my_database_password';
DB::$dbName = 'my_database_name';

Composer

Add this to your composer.json

{
  "require": {
    "sergeytsalkov/meekrodb": "*"
  }
}

Code Examples

Grab some rows from the database and print out a field from each row.

$accounts = DB::query("SELECT * FROM accounts WHERE type = %s AND age > %i", $type, 15);
foreach ($accounts as $account) {
  echo $account['username'] . "\n";
}

Insert a new row.

DB::insert('mytable', array(
  'name' => $name,
  'rank' => $rank,
  'location' => $location,
  'age' => $age,
  'intelligence' => $intelligence
));

Grab one row or field

$account = DB::queryFirstRow("SELECT * FROM accounts WHERE username=%s", 'Joe');
$number_accounts = DB::queryFirstField("SELECT COUNT(*) FROM accounts");

Use a list in a query

DB::query("SELECT * FROM tbl WHERE name IN %ls AND age NOT IN %li", array('John', 'Bob'), array(12, 15));

Log all queries and errors

// log all queries and errors to file, or ..
DB::$logfile = '/home/username/logfile.txt';

// log all queries and errors to screen
DB::$logfile = fopen('php://output', 'w');

Nested Transactions

DB::$nested_transactions = true;
DB::startTransaction(); // outer transaction
// .. some queries..
$depth = DB::startTransaction(); // inner transaction
echo $depth . 'transactions are currently active'; // 2
 
// .. some queries..
DB::commit(); // commit inner transaction
// .. some queries..
DB::commit(); // commit outer transaction

Lots More - See: http://meekro.com/docs

How is MeekroDB better than PDO?

Optional Static Class Mode

Most web apps will only ever talk to one database. This means that passing $db objects to every function of your code just adds unnecessary clutter. The simplest approach is to use static methods such as DB::query(), and that's how MeekroDB works. Still, if you need database objects, MeekroDB can do that too.

Do more with fewer lines of code

The code below escapes your parameters for safety, runs the query, and grabs the first row of results. Try doing that in one line with PDO.

$account = DB::queryFirstRow("SELECT * FROM accounts WHERE username=%s", 'Joe');

Or how about just one field?

$created_at = DB::queryFirstField("SELECT created_at FROM accounts WHERE username=%s", 'Joe');

Work with list parameters easily

Using MySQL's IN keyword should not be hard. MeekroDB smooths out the syntax for you, PDO does not.

$accounts = DB::query("SELECT * FROM accounts WHERE username IN %ls", array('Joe', 'Frank'));

Simple inserts

Using MySQL's INSERT should not be more complicated than passing in an associative array. MeekroDB also simplifies many related commands, including the useful and bizarre INSERT .. ON DUPLICATE UPDATE command. PDO does none of this.

DB::insert('accounts', array('username' => 'John', 'password' => 'whatever'));

Nested transactions

MySQL's SAVEPOINT commands lets you create nested transactions, but only if you keep track of SAVEPOINT ids yourself. MeekroDB does this for you, so you can have nested transactions with no complexity or learning curve.

DB::$nested_transactions = true;
DB::startTransaction(); // outer transaction
// .. some queries..
$depth = DB::startTransaction(); // inner transaction
echo $depth . 'transactions are currently active'; // 2
 
// .. some queries..
DB::commit(); // commit inner transaction
// .. some queries..
DB::commit(); // commit outer transaction

Flexible debug logging and error handling

You can log all queries (and any errors they produce) to a file for debugging purposes. You can also add hooks that let you run your own functions at any point in the query handling process.

My Other Projects

A little shameless self-promotion!

  • Ark Server Hosting -- Ark: Survival Evolved server hosting by ArkServers.io!
  • Best Minecraft Server Hosting -- Ranking and recommendations for minecraft server hosting!
  • brooce - Language-agnostic job queue written in Go! Write your jobs in any language, schedule them from any language, run them anywhere!

meekrodb's People

Contributors

bcash avatar cgoedel avatar magma1447 avatar mikedamm avatar sergeytsalkov avatar wadih 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

meekrodb's Issues

SNIPPET: Checking if INSERT went well

Hello Meekro, thank you for a GREAT piece of software!

Sorry if this is in the wrong section (still learning Github) but I wanted to share this piece of code with others who might find it useful.

If you need to check if INSERT statement worked well or if you had errors, this is the way to do it:

        try {
            DB::insert('users', $user);
            // Record added successfully
            ...
        }catch (MeekroDBException $e){
            // Record not added, possible reason: it already exists
            ...
        }

It uses try/catch and in the "catch" part you can add checks to see exact error and/or use the error handler that's specified in MeekroDB's readme.

Hope this helps someone.

Potentially unsafe error handling

If you turn on error handling (especially the debug backtrace) you can run into a problem when you output the error you will get all the variables from the static class (like username and password) maybe there is a way to hide these values from the outside world?

Default encoding

Currently the default encoding is public static $encoding = 'latin1';
Why not make utf8 the default ?

Enable renaming

It would be nice to have all the code inside the DB class refer to itself as self:: instead of DB::. This way you could import this library into an existing framework which already has a class DB defined, by simply renaming the initial class name of this library.

Multidimensional Array support?

Quick question. is it, or will it be possible to add support for: Multidimensional Arrays. based on the table?
i.e.:

mysql table has id / type / name / name2
and set an option, that would allow the 'type' column to be the name of the Multidimensional Array. and for each record that has that the same, its in that same array.

DB::insertUpdate() with an array of associative arrays?

Hi, I recently switched my MySQL setup to use its own dedicated server accessed over the network, and I appreciate how MeekroDB lets me build up a big array of queries to run all at once, to minimize slowdowns from latency (it may only be a 500 microsecond round trip between the web server and the MySQL server, but it adds up...) One thing I have noticed, however, is that DB::insert() and DB::insertIgnore() will both take an array of arrays, but DB::insertUpdate() will not, making it relatively slow. I'm just wondering if there is a method for doing this with Meekro, or if it's a limitation within MySQL, or something else.

Documentation seems to be incorrect when using composer

Added following to composer.json require object:
"require": { .... "sergeytsalkov/meekrodb": "*" }
updated composer and now vendor contains folder for sergeytsalkov
verified existance of file /vendor/sergeytsalkov/meekrodb/db.class.php

added following file to projet "/inc/dbinit.php"
<?php require_once 'db.class.php'; DB::$user = 'test'; DB::$password = 'changeit'; DB::$dbName = 'test'; DB::$host = '127.0.0.1'; //defaults to localhost if omitted DB::$port = '3306'; // defaults to 3306 if omitted DB::$encoding = 'utf8'; // defaults to latin1 if omitted ?>

added following require statement to my /index.php

$root=pathinfo($_SERVER['SCRIPT_FILENAME']); define ('BASE_FOLDER', basename($root['dirname'])); define ('SITE_ROOT', realpath(dirname(__FILE__))); define ('SITE_URL', 'http://'.$_SERVER['HTTP_HOST'].'/'.BASE_FOLDER); require_once SITE_ROOT.'/inc/dbinit.php';
refresh url pointing to index.php and get following in error logs
[Sun May 15 10:47:34.980963 2016] [:error] [pid 11309] [client 127.0.0.1:54362] PHP Fatal error: require_once(): Failed opening required 'db.class.php' (include_path='.:/usr/share/php') in /_...excluding path ,.._ /inc/dbinit.php on line 2
I would have thought that the composer autoload process would have loaded this file and the require_once would not be needed. but certainly it is wrong since it doesn't point to the correct path to the file /vendor/sergeytsalkov/meekrodb/db.class.php

Here is the relevant composer.lock file contents:
{ "name": "sergeytsalkov/meekrodb", "version": "v2.3", "source": { "type": "git", "url": "https://github.com/SergeyTsalkov/meekrodb.git", "reference": "eb36858f1aff94ae1665900e681a1cfb78563ee1" }, "dist": { "type": "zip", "url": "https://api.github.com/repos/SergeyTsalkov/meekrodb/zipball/eb36858f1aff94ae1665900e681a1cfb78563ee1", "reference": "eb36858f1aff94ae1665900e681a1cfb78563ee1", "shasum": "" }, "require": { "php": ">=5.2.0" }, "type": "library", "autoload": { "classmap": [ "db.class.php" ] }, "notification-url": "https://packagist.org/downloads/", "license": [ "LGPL-3.0" ], "authors": [ { "name": "Sergey Tsalkov", "email": "[email protected]" } ], "description": "The Simple PHP/MySQL Library", "homepage": "http://www.meekro.com", "keywords": [ "database", "mysql", "mysqli", "pdo" ], "time": "2014-06-16 22:40:22" }

Noobie question

Hi there and thanks for your work
I stop developping almost 10 years ago and I'm trying to build php app again.
I met a problem with your class in order to use it in another class.
I want to do this kind of thing.

A class

class foo{
 public $db;
  public function __construct($dbObj){
    $this->db = $dbObj;
  }

  public function getList(){
    $results = $this->db->query("SELECT * FROM foo ");
    if ($this->db->count()<=0){return NULL;}
    else{return $results;}
  }
};

The "classic" way (in my memories)

$db = new DB($dbhost, $dbname, $dbuser, $dbpass);
$fooObj = new foo($db);
$list = $fooObj -> getList();

The MeekroDB Way

DB::$host           = _DB_HOST;
DB::$user           = _DB_USER;
DB::$password       = _DB_PASS;
DB::$dbName         = _DB_NAME;
$fooObj = new foo(DB::get());
$list = $fooObj -> getList();

When I do so I get an error on Call to undefined method mysqli::count().

What is the good way to use MeekroDb in the foo class ?
Many thanks.

Not possible to query for NULL value?

Is there a way I can handle a case like this, where $parent_id could be any number or NULL?

function FindChildren($parent_id) {
     $results = DB::query("SELECT item_id FROM items WHERE parent_item_id=%?", $parent_id);
}

I'm doing it the following way way now, but I was wondering if there was a way to make this happen automagically...

if($parent_id == null) $results = DB::query("SELECT item_id FROM items WHERE parent_item_id IS NULL");
else $results = DB::query("SELECT item_id FROM items WHERE parent_item_id=%i", $parent_id);

PS: love meekrodb a lot!

Testing Connection?

It'd be great to have a function to test the database connection without sending a query.

$db values changed in between statements

Somehow the $db object is having values changed in the section of the queryHelper() below.
With a call to $db->query(). This works fine, the SQL has a syntax error and the values get set properly in the $db object. "errno" is set to 1052 and "error" has a text string.
Then in the debugger, I step one line, which is "If ($this->success_handler)..."
And suddenly the error has be "reset"??? "errno" =0 and "error" = ''.
How is this possible? There is not any time to check $db->error to call the error_handler???

`
$result = $db->query($sql, $is_buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
if ($this->success_handler) $runtime = microtime(true) - $starttime;
else $runtime = 0;

// ----- BEGIN ERROR HANDLING
if (!$sql || $db->error) {`

Error when using array of named arguments with update()

When using the update function, if the where argument uses named arguments the array of parameters is not parsed.

The error "If you use named parameters, the second argument must be an array of parameters" is displayed, even when the parameter argument is present and correct according the the query syntax.

Example:

DB::update(
    'table',
    ['status' => 0] 
    '`member`=%i_member AND `group`=%i_group',
    ['member' => $member,'group' => $group]
);

This will return the above error, as does using numerical indexes. The only workaround I've found is to rewrite the call like this:

DB::update(
    'table',
    ['status' => 0] 
    '`member`=%i2 AND `group`=%i3',
    $member,
    $group
);

Note that the index numbers need to be incremented by 2, otherwise the table and update arguments are used instead.

Unable to get 2.3 to throw MeekroDBException

Hello,

Using a simple test case, I am unable to get MeekroDB to throw a simple exception for a database error.

    // Database Class
    require_once './meekrodb.2.3.class.php';

    DB::$error_handler  = false;
    DB::$throw_exception_on_error = true;
    DB::$user       = 'user';
    DB::$password   = 'pass';
    DB::$host       = 'my.server.com';
    DB::$dbName     = 'my_database';
    DB::$error_handler  = false;
    DB::$throw_exception_on_error = true;
    $DB_mysql = new MeekroDB();

    try {
        // table1 does not exist, should throw an exception
        $q = "SELECT id FROM table1 WHERE name = %s";
        $result = $DB_mysql->queryFirstRow($q, 'Administrator');
    } catch(MeekroDBException $e) {
        echo "Error: " . $e->getMessage() . "\n";
        echo "Query: " . $e->getQuery() . "\n";
    }
    if (array_key_exists('id', $result)) {
        echo $result['id'];
    }

    $DB_mysql->disconnect();

This sample code never returns an exception. I always get the generic error handler.

Have I missed something simple? Seems like this should work ok with 2.3.

Thanks,
Jay

composer autoload RuntimeException

composer.json

{
    "require": {
        "sergeytsalkov/meekrodb": "~2.3",
    },
    "autoload": {
        "classmap": [
            "db.class.php"
        ]
    }
}

composer update

  [RuntimeException]                                                                                
  Could not scan for classes inside "db.class.php" which does not appear to be a file nor a folder

the meekrodb path in /project/vendor/sergeytsalkov/meekrodb/db.class.php

PHP warning, line 547

Hi, thanks for the useful script. I'm getting this warning when I use it, it seems to do the job otherwise:

PHP Warning: strlen() expects parameter 1 to be string, array given in /<mywebsite>/lib/meekrodb.2.1.class.php on line 547

The problem seems to go away where I change that line from $result to $result[0].

Cheers,
George

Why there is no mysqli_close()!

I can find KILL function

public function disconnect()
 {
     $mysqli = $this->internal_mysql;
     if ($mysqli instanceof MySQLi)
     {
         if ($thread_id = $mysqli->thread_id) $mysqli->kill($thread_id);
         $mysqli->close();
     }
     $this->internal_mysql = null;
 }

But why dont you use mysqli_close !
and what is this function : $mysqli->close(); i can not find it !

Problems and fixes on class WhereClause

Hi,
I found a problem on negation of class WhereClause.
Allow me to give an example to clarify the problem

Example :
$where = new WhereClause('AND');
$where->add(" condition A ");
$where->add(" condition B ");
$where->negate();
and we will have WHERE SQL as
( NOT (condition A) AND (condition B) )
but the correct one on negation of the whole WHERE clause should be
NOT( (condition A) AND (condition B) )

Fix:
line 837 in the source code
original code : $sql = '(NOT ' . $sql . ')';
revised code : $sql = '( NOT ( ' . $sql . ') )';

Hope it helps you solve the problem

Sincerely,
Ken

how do you perform a search?

how would i go about doing a search using this?

SELECT * FROM bbcodes WHERE name LIKE '%$query%' (old style)

"SELECT * FROM bbcodes WHERE name LIKE %ss",$query ( this is what i am trying to do.)

%ss search string (string surrounded with % for use with LIKE)

but when i try this it gives no results

WHERE OR clause not recognizing second condition

When trying to do a simple WHERE ... OR clause, the results returned only includes the first conditional. The second is ignored.

$messages = DB::query("SELECT * FROM messages WHERE to_id=%i OR from_id=%i", $userid);

This returns only messages where the to_id = $userid but does not include messages where from_id = $userid.

The query works as expected in phpMyAdmin (returning all messages where to_id or from_id = $userid).

Date format not working

When i use a query like this:

$result = DB::query("SELECT t3.name as module,t2.firstname as user,t1.module_identifier,t1.field,t1.old_value,t1.new_value,DATE_FORMAT(t1.timestamp,'%d-%d-%Y %T') as timestamp FROM log t1 LEFT JOIN user t2 ON t2.id = t1.user_id LEFT JOIN module t3 ON t3.id = t1.module_id WHERE %l ORDER BY t1.timestamp ASC", $where);

MeekroDB processes the DATE_FORMAT settings as variables because of the % markup. Is there a workaround for this?

Verify the query.

Hi!
I use your script whit smarty. It very nice class for use mysql but i have one issue.
If i want insert in my database a query whit your class i make this.
$query = DB::insert('cliente', array(
'var_a' => $var_a,
'var_b' => $var_b
));

and if i want verify i make this
if($query){
$msg = "OK!";
} else {
$msg = "ERROR!";
}

but what the script when run ok say ERROR! and when don't run say the standard error.
What is the method for check the query go ok? It possible personalized the error?

Thank.

P.S. Sorry for my english.

mysqli_kill()?

Hi,

Is there any way of getting a mysqli_thread_id so that mysqli_kill could be used?

Thanks

How i can change CHARACTER SET?

Hi, my DB in utf8_general_ci but i have a problen with character => ?????????? without normal name.
How i can setup SET NAMES UTF8?

columnList is unsafe

sqlEval should also be used on columnList because now you cannot use
columnList("group");

WhereClause and LIKE queries failing

The documentation says I can use %%s for strings in LIKE queries.

When I do this:

$where = new WhereClause('and');
$where->add('Field LIKE %%s', $term); // $term is KGR
DB::query('SELECT * FROM table WHERE %l', $where->text());

I get this response:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%'KGR')' at line 1

Multiple databases

The library's great. The only thing I'm missing is setting it up for multiple databases, let's say like this:

<?php
$db1 = new MeekroDB(array(
    'dbName' => 'one',
    // ...
));
$db2 = new MeekroDB(array(
    'dbName' => 'two',
    // ...
));
$res1 = $db1->query('SELECT ...');
$res2 = $db2->query('SELECT ...');

Are you planning to implement this?

DB::query optional Placeholder Variables

I'm missing one small thing that can make my life easier. It is "optional placeholder".

Example:
DB::query("SELECT * FROM tbl WHERE name=%s[ AND age > %I]", "test", 15);
This will result in:
SELECT * FROM tbl WHERE name='test' AND age > 15

But this example:
DB::query("SELECT * FROM tbl WHERE name=%s[ AND age > %I]", "test", null);
will result in:
SELECT * FROM tbl WHERE name='test'

So it will allow having one query and "one" line of code to make SQL with optional WHERE, ORDER BY, ... rules.
Not sure how big change will this be in your code. I was used to using this in EzSQL lib that I switched from (still like meekro better). I don't need this, but it can be a time saver in some cases.

btw: I'm aware of the existence of new WhereClause('and');, but this optional placeholder can result in more compact code (not always)

Are functions like DB::insertUpdate escaping values?

Hi,

Just a quick question:

The doc shows queries with obvious escaping, such as :

DB::queryFirstRow("SELECT * FROM accounts WHERE username=%s", 'Joe');

However it is unclear as whether the following implies escaping or not:

DB::insertUpdate('accounts', array(
  'id' => 5, //primary key
  'username' => 'Joe',
  'password' => 'hello'
));

Is that insertUpdate as safe (regarding sql injection) as first example escaping? I suppose it is, just seeking for a confirmation from you.

Thanks in advance, and merry xmas!

Library is not IDE friendly

No IDE can figure out the parameters of the methods. Neither for DB, nor MeekroDB classes.

This makes development more challenging, since constant checking of previous code usages, documentation, or source code is required.

Having method parameters and, preferably, types of parameters available (via PHPDoc) would be very convenient.

The main sign of IDE hostile methods is usage of func_get_args().

strtolower affected by locale

I have been using MeekroDB for years and finally managed to understand a bug I have been seeing at times.

In MeekroDBs code there is use of the PHP function strtolower(). If doing an insertUpdate, it will get to this compare:
if (isset($options['update']) && is_array($options['update']) && $options['update'] && strtolower($which) == 'insert') {

If the locale is set to Turkish, the above if statement will fail. More precisely the last part of it.
strtolower('INSERT') does not equal 'insert' when the locale is Turkish.

Instead mb_strtolower() could be used, which is documented to not be affected by locale. This is what I have updated my local copy to use.
mb_convert_case() could most likely also be used, but I haven't tried it.

The fix is quite easy. Search and replace all strtolower into mb_strtolower.

Date format

It possiple expand the class whit a management of the date?
For example i use other my class to change the date before i insert to database (dd/mm/yyyy -> yyyy-mm-dd) and after i read it (yyyy-mm-dd -> dd/mm/yyyy).

Thanks and sorry for my english.
:)

Get the last query

Hi again

I love asking noob questions but : is there a proper way to get the last query ?
By example

$attendedResults = X;
$results = DB::query("SELECT ... FROM ... WHERE ... AND ... AND ... AND ... AND ... ORDER BY ...", $var1, $var2, $var3, $var4, $var5, $var6,  );
if ($results != $attendedResults){
  echo "Something went wrong with this query : ".DB::lastQuery().PHP_EOL;
}

Regards

Use "IS NULL"

Hello Sergey.

How I can use "IS NULL" with params?

For example, I have this request:

$arResult = DB::query("SELECT * FROM tbl WHERE ID=%s AND (sExpireDate >= %s OR sExpireDate IS NULL)", $_USER['ID'], date('Y-m-d H:i:s'));

In this case I ghave an nGinx error: 502 Bad Gateway.

If I use this code:

$arResult = DB::query("SELECT * FROM tbl WHERE ID=%s AND sExpireDate >= %s)", $_USER['ID'], date('Y-m-d H:i:s'));

I have no errors.

Thanks.

Namespace and whereClause in another class

Hi again
Sorry to be back but I've done many tests and I cannot find a solution to my noobie problem of namespace.
The goal : using the WhereClause in another class/namespace.

I wrote this test
foo.php

<?php
require __DIR__.'/config.inc.php';
require __DIR__.'/vendor/autoload.php';

use sergeytsalkov\meekrodb;
DB::$user           = _DB_USER;
DB::$host           = _DB_HOST;
DB::$password       = _DB_PASS;
DB::$dbName         = _DB_NAME;
DB::$encoding       = 'utf8';

$db = new DB();

include __DIR__.'/class_foo.php';
$foo = new foo\foo($db);
$result = $foo->getFoo();
?>

And this class class_foo.php

<?php
namespace foo;
class foo{
  public $db;
  public function __construct($dbObj){
    $this->db = $dbObj;
    echo "Class foo ok".PHP_EOL;
  }

  public function getFoo(){

    /* Uncaught Error: Class 'foo\WhereClause' not found
    $where = new WhereClause('and');
    $where->add('media_id=%s', 'Upxqhd_htzw');
     */
    // Uncaught Error: Class 'sergeytsalkov\meekrodb\WhereClause' not found
    $where = new \sergeytsalkov\meekrodb\WhereClause('and');
    $where->add('media_id=%s', 'Upxqhd_htzw');

    $results = $this->db->query("SELECT * FROM medias WHERE %l", $where);
    /* I know I could do this but I would want to know how to use whereClause in another namespace class
      $results = $this->db->query("SELECT * FROM medias WHERE media_id=%s", 'Upxqhd_htzw');
     */
    if ($this->db->count()<=0){return NULL;}
    else{return $results;}
  }
};
?>

Whatever I try to use WhereClause in my foo class, it fails.
If you have a solution or explanation it will be greatly appreciated.
Regards
PS : the example is much less complicated than in my true class but bases are the same.

How to get last executed SQL

Is there any way to debug complex query statements with seeing what is final SQL string resulted from meekrodb parsing and processing?

Needs some kind of DB::getLastQueryString()

Thank you

new function proposal

public function queryWithKeyColumn() { 
    $args = func_get_args();
    $column = array_shift($args);
    $results = call_user_func_array(array($this, 'query'), $args);
    $output = array();
    foreach($results as $row){
        if(!isset($row[$column])){
            $this->nonSQLError("Query is missing the column: $column");
        }
        $output[$row[$column]] = $row;
    }
}

Which will do something like:

$array = DB::queryWithKeyColumn('name', "SELECT name, age FROM users");

$array should be:

array(
    "Jim" => array("name"=>"Jim", "age" => 31),
    "John" => array("name"=>"John", "age" => 23),
)

$error_handler seems not function well

Hi There,

Sorry for bothering, actually I am not sure I put my message at the right place.

Basically, my code is just retrieving all the records in a database on my server through CURL, and then save them in my local MySQL DB, the server is running ASP.NET, exposing some WEB APIs to do that.
And for some reason (I am not sure what it is so far), I got error of duplicate primary key, which breaks down the PHP script execution. So I think about using $error_handler.

My error function is pretty simple:
function my_error_handler($params) {
global $logger;
if (VDEBUG_MODE)
{
echo "Error: " . $params['error'] . "
\n";
echo "Query: " . $params['query'] . "
\n";
}
$logger->log("DBA Error: " . $params['error']);
$logger->log("Query: " . $params['query']);
}

I don't call die or exit inside it because I want to see if the script can resume execution. But what I see is that the function my_error_handler is not invoked, and my PHP script just stop there. And if I put die at the bottom of the function, then I can see the output message.

I was wondering that if there is a way to catch up such SQL error, and log it, and make the script continue to run.

Relations?

Is it possible to use relatioins and how to use them?

License confusion... what license is MeekroDB actually available under..?

Hi there, I'm an open-source developer working on a BSD-licensed project. I'm just wondering what license MeekroDB uses?

  • The websites says it's free for personal use but you need to pay for commercial use.
  • The GitHub listing says it's full GPL.
  • The comments in the source code say that the license is LGPL.

By the way, I'm not saying any of the above is wrong. It's your project, and your choice of license!

However for a BSD-licensed project:

  • We're redistributing our project for free so can't include a paid library.
  • We can't include a GPL library because of the viral clause when redistributing makes it incompatible with BSD.
  • LGPL is fine to use!

...so obviously I'd need to be sure as to which one it uses!

Documentation improvement

So the documentation doesn't make it clear how to pass a WhereClause or Ass-Array with DB::delete(...).
Obviously doing DB::delete('myTable', $someWhereClause); fails (since argument 2 is no string).
I was about to write a patch to fix this issue (had allready finished it) when it dawned on me (also by unraveling how DB::query parameters work) that DB:delete('myTable', '%?', $someWhereClause); was what I was looking for. (Some for Ass-Array)

TLDR:
Add DB:delete('myTable', '%?', $someWhereClause); to "new WhereClause()" or "DB:delete()" section of the documentation. :)

Re-use connection

Hello,

I would like to re-use same connection for another library. Trying like this:

...
$reconnect = new MeekroDB();
$auth = new \Delight\Auth\Auth($reconnect);
...

And of course this is results in error. Any suggestions how to re-use meekrodb connection if third party library requires:

The database connection must be an instance of either PdoDatabase, PdoDsn or PDO?

pconnect

Mr.Tsalkov, how to use meekrodb in persistent pconnect way?

return value options, Array/Object

The return values from a meekrodb query are currently all Arrays
I have a project I would like to switch from ezsql to meekrodb, but all of my previous queries have returned objects. In ezsql there is an option to return Array, Associative Array or Object.

It is too much coding for me to convert everything back to Arrays and I dont want to just set a (object)$returnedValue as this is extra processing time

Is it possible to include an option in the meedrodb code to allow return value to be Array OR Object ?

At the moment I am using this

$query = ""SELECT * FROM posts WHERE post_id = %d";
$post = (object)DB::query($query, $post_id)[0];

where I want to use something like this

$query = ""SELECT * FROM posts WHERE post_id = %d";
$post = DB::queryObj($query, $post_id);

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.